Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f25f2db885 | ||
|
|
621732ae0a | ||
|
|
ed85c659be | ||
|
|
f6dcd1c382 | ||
|
|
37c572fd98 | ||
|
|
1ff709d05c | ||
|
|
83726feae1 | ||
|
|
f24c87cc51 | ||
|
|
1c40968a94 | ||
|
|
c37ec7c1dd | ||
|
|
ff3e600302 | ||
|
|
3d064f5b9d | ||
|
|
ae8f8bda03 | ||
|
|
2dbae19c41 | ||
|
|
d3ef31f551 | ||
|
|
ff0c0369e8 | ||
|
|
b0dafe081b | ||
|
|
a88b5d01c1 | ||
|
|
e7d5e62671 | ||
|
|
5f41b9489d | ||
|
|
958e241e0e | ||
|
|
4b3efc0b6f | ||
|
|
1592fc2371 | ||
|
|
d5a6613428 | ||
|
|
9324473c9e | ||
|
|
456e797cca | ||
|
|
f960b9f9b4 | ||
|
|
8449b73423 | ||
|
|
f19ba9aac9 | ||
|
|
524849f6a9 | ||
|
|
0a64a9abe0 | ||
|
|
adb4127f5a | ||
|
|
f463593180 | ||
|
|
e53f257977 | ||
|
|
87199e856a | ||
|
|
bcf7cfbf76 | ||
|
|
9289e1388f | ||
|
|
84db9b7bb8 | ||
|
|
bd1098a181 | ||
|
|
6fd3db0063 | ||
|
|
bf52217cd5 | ||
|
|
b0cf5b3c61 | ||
|
|
347c1675ca | ||
|
|
961ae2d34f | ||
|
|
14827c3adc | ||
|
|
4a88453abc | ||
|
|
bc33d38f5e | ||
|
|
657a5ede86 | ||
|
|
dd046fe3e8 | ||
|
|
7391dbf5b1 | ||
|
|
a0ccb86bd4 | ||
|
|
c0eb5b165d | ||
|
|
9812babc7e | ||
|
|
c61c4570b0 | ||
|
|
d618feffff | ||
|
|
0fdc3c93d3 | ||
|
|
d6e76f7805 | ||
|
|
b05afe1085 | ||
|
|
2a4911f5f8 | ||
|
|
208074d845 | ||
|
|
616ff2c3fe | ||
|
|
987c939956 | ||
|
|
1615cc744e | ||
|
|
2d793a4b25 | ||
|
|
aeeb4d5504 | ||
|
|
daec801073 | ||
|
|
e4916a7b7c | ||
|
|
a08abd76e3 | ||
|
|
a2be709608 | ||
|
|
69002ef926 | ||
|
|
9ade5a7194 | ||
|
|
9b3f4f605b | ||
|
|
b862968d01 | ||
|
|
29f3ae5592 | ||
|
|
107d2a64fc | ||
|
|
e24bb884ef | ||
|
|
107a2ef962 | ||
|
|
9d58f2cf1e | ||
|
|
29f6860fe1 | ||
|
|
fa89026e05 | ||
|
|
9968452c46 | ||
|
|
9665634013 | ||
|
|
76d10ba8fb | ||
|
|
e9ea10203e | ||
|
|
92a4c2da02 | ||
|
|
b6d8eb98f6 | ||
|
|
b6b01bccd7 | ||
|
|
ace2339b4f | ||
|
|
166c1f9c9c | ||
|
|
e4039a08bc | ||
|
|
1da5b5941d | ||
|
|
6683f12c80 | ||
|
|
2277f48e46 | ||
|
|
d206bde15a | ||
|
|
af16d03915 | ||
|
|
bf26cd3cfb | ||
|
|
094062773a | ||
|
|
4cd95813bc | ||
|
|
c2064f0b64 | ||
|
|
fafd927610 | ||
|
|
7f46380054 | ||
|
|
351a8b18dd | ||
|
|
39833b333f | ||
|
|
888a41375b | ||
|
|
823abb22e4 | ||
|
|
a3c88309b4 | ||
|
|
beebc7e194 | ||
|
|
3f8f22ac61 | ||
|
|
12c95d0e92 | ||
|
|
b00f600cd9 | ||
|
|
a4925fc943 | ||
|
|
28248ac3c4 | ||
|
|
d2b5626977 | ||
|
|
b61429b52d | ||
|
|
d05b39d8ae | ||
|
|
6b3b0f1bd6 | ||
|
|
feb679ae77 | ||
|
|
9779e5552d | ||
|
|
fbd187dc29 | ||
|
|
e8b6116439 | ||
|
|
fcd3e79cb7 | ||
|
|
d03078cfd4 | ||
|
|
b94d859849 | ||
|
|
dc4fcdf578 | ||
|
|
da4c40017d | ||
|
|
ac420b6495 | ||
|
|
5791601c7e | ||
|
|
eb149184c3 | ||
|
|
d410073c64 | ||
|
|
b373f6c513 | ||
|
|
18395a2265 | ||
|
|
2e4c63ba7d | ||
|
|
9fdf7c4642 | ||
|
|
053a9050b6 | ||
|
|
7efabdfa70 | ||
|
|
e5077969e9 | ||
|
|
2688da5a82 | ||
|
|
4f46d077df | ||
|
|
bde856c576 | ||
|
|
083cb9f730 | ||
|
|
2644d720e7 | ||
|
|
2fe84ab801 | ||
|
|
ca1d79f848 | ||
|
|
e52572beaa | ||
|
|
0f77a98d76 | ||
|
|
ebede3d56b | ||
|
|
1692f5519f | ||
|
|
dad1aa1c45 | ||
|
|
5d2244db6e | ||
|
|
8a15cfe4b4 | ||
|
|
500c7fbe30 | ||
|
|
894b600b09 | ||
|
|
97f0b30cd6 | ||
|
|
9855e8a561 | ||
|
|
c2b259ade1 | ||
|
|
cfc185117c | ||
|
|
9e89920e79 | ||
|
|
af190da333 | ||
|
|
3e3ec45b19 | ||
|
|
f0fe593d78 | ||
|
|
8646118a27 | ||
|
|
31f21b3a6b | ||
|
|
12d87e30e1 | ||
|
|
6ecc3f72d1 | ||
|
|
e8c40dc6b8 | ||
|
|
0279517a42 | ||
|
|
072eab1703 | ||
|
|
3b38a6dd29 | ||
|
|
7f8d8be5fb | ||
|
|
3aa6b6a2ef | ||
|
|
d870cfbba6 | ||
|
|
13a9e1a5d7 | ||
|
|
06aba7e692 | ||
|
|
c73ff02bfb | ||
|
|
ed03170817 | ||
|
|
3079994a77 | ||
|
|
41b37f9edf | ||
|
|
8d65d3ef4e | ||
|
|
357c8b8be4 | ||
|
|
a47b343f93 | ||
|
|
4388e0f2e1 | ||
|
|
f2adff1d85 | ||
|
|
ad51da7950 | ||
|
|
7610a71829 | ||
|
|
8800f226d2 | ||
|
|
ba16932b44 | ||
|
|
81394345b4 | ||
|
|
72621d9d0e | ||
|
|
d35ded6502 | ||
|
|
b17e5c3db2 | ||
|
|
365c4df2a4 | ||
|
|
ab79d05e96 | ||
|
|
a208004fe0 | ||
|
|
51c714df25 | ||
|
|
87b45df180 | ||
|
|
accb15a92a | ||
|
|
a421825050 | ||
|
|
c55112c8f7 | ||
|
|
accbc5635e | ||
|
|
558ff7d141 | ||
|
|
fa70a0a4ab | ||
|
|
50b414a904 | ||
|
|
80c91039e1 | ||
|
|
966e01e7e2 | ||
|
|
82ffce1e25 | ||
|
|
c7257cc00a | ||
|
|
ab877c2e9a | ||
|
|
c6dcf307fd | ||
|
|
30d69e7ed1 | ||
|
|
bb8195c0d1 | ||
|
|
a813302e86 | ||
|
|
0f643664f7 | ||
|
|
665537cb6a | ||
|
|
766b9293cf | ||
|
|
6e014e30d9 | ||
|
|
30fc8ad1df | ||
|
|
bcad939a3d | ||
|
|
e153df85fb | ||
|
|
26908b5d81 | ||
|
|
0ddca8ff58 | ||
|
|
fd285d969e | ||
|
|
10bebe5eb5 | ||
|
|
fef5e81033 | ||
|
|
a325ae180a | ||
|
|
df1ae9cd55 | ||
|
|
d5380b4195 | ||
|
|
9e12ada4fa | ||
|
|
bb3240f1b3 | ||
|
|
7780ac89ef | ||
|
|
c58eae695e | ||
|
|
45244dcaa9 | ||
|
|
53b15fa74c | ||
|
|
9341b02f4b | ||
|
|
158db522a8 | ||
|
|
f3b76c0bc1 | ||
|
|
d11f961566 | ||
|
|
9d7f81d042 | ||
|
|
c95e1a829c | ||
|
|
7bd06e7b88 | ||
|
|
6e64b6feac | ||
|
|
f6c0e6265e | ||
|
|
662ce701ca | ||
|
|
72bbfb3f58 | ||
|
|
9306c12fcd | ||
|
|
9f1ea70c9f | ||
|
|
98913b359a | ||
|
|
a4905f0778 | ||
|
|
e603231633 | ||
|
|
345463322a | ||
|
|
c298866e3c | ||
|
|
75e97ac652 | ||
|
|
149ec16d57 | ||
|
|
31e30d94aa | ||
|
|
326f876410 | ||
|
|
58a7ae4229 | ||
|
|
8f796ad9dc | ||
|
|
8be860007a | ||
|
|
1985e201b4 | ||
|
|
4e4b41661b | ||
|
|
b24a99a11f | ||
|
|
69b151f990 | ||
|
|
2d4eb59d6c | ||
|
|
5037622fb6 | ||
|
|
962a089bf4 | ||
|
|
4c56565b66 | ||
|
|
8432038f09 | ||
|
|
929d916d41 | ||
|
|
675975d951 | ||
|
|
524ec87395 | ||
|
|
94f8193996 | ||
|
|
7c3fcf73c3 | ||
|
|
20bbf89679 | ||
|
|
86dca52d07 | ||
|
|
78d1561e74 | ||
|
|
054e4af258 | ||
|
|
dc03faa97e | ||
|
|
9a7635c2ae | ||
|
|
df3d79c20c | ||
|
|
d6144be7ed | ||
|
|
9afbb904b3 | ||
|
|
93558b2444 | ||
|
|
9f93f1ee18 | ||
|
|
30a9b53ba1 | ||
|
|
5175970d55 |
@@ -3,7 +3,7 @@ name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: bug
|
||||
assignees: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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,8 +1,40 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
|
||||
# Home Assistant
|
||||
.storage
|
||||
.cloud
|
||||
.google.token
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
.env
|
||||
.venv
|
||||
venv/
|
||||
ENV/
|
||||
Thumbs.db
|
||||
*.psd
|
||||
*.zip
|
||||
*.txt
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
# 🤝 Contributing Guide
|
||||
|
||||
We welcome contributions to the HA Text AI project! This document will help you contribute to the project's development.
|
||||
|
||||
## 🌟 How to Contribute
|
||||
|
||||
### 1. Preparation
|
||||
|
||||
1. Fork the Repository
|
||||
- Go to the repository page on GitHub
|
||||
- Click the "Fork" button in the top right corner
|
||||
|
||||
2. Clone Your Fork
|
||||
```bash
|
||||
git clone https://github.com/YOUR_USERNAME/ha-text-ai.git
|
||||
cd ha-text-ai
|
||||
```
|
||||
|
||||
3. Set Up Remote Repositories
|
||||
```bash
|
||||
git remote add upstream https://github.com/smkrv/ha-text-ai.git
|
||||
```
|
||||
|
||||
### 2. Creating a Development Branch
|
||||
|
||||
```bash
|
||||
# Update the main branch
|
||||
git checkout main
|
||||
git pull upstream main
|
||||
|
||||
# Create a new branch for your feature
|
||||
git checkout -b feature/short-description-of-changes
|
||||
```
|
||||
|
||||
### 3. Development
|
||||
|
||||
- Follow the project's coding standards
|
||||
- Write clean and understandable code
|
||||
- Add comments when necessary
|
||||
- Create unit tests for new functionality
|
||||
|
||||
### 4. Committing Changes
|
||||
|
||||
```bash
|
||||
# Add modified files
|
||||
git add .
|
||||
|
||||
# Create a meaningful commit
|
||||
git commit -m "Feat: Add [short feature description]"
|
||||
```
|
||||
|
||||
### 5. Commit Message Style
|
||||
|
||||
Use the following prefixes:
|
||||
- `Feat:` - new feature
|
||||
- `Fix:` - bug fixes
|
||||
- `Docs:` - documentation updates
|
||||
- `Style:` - formatting changes
|
||||
- `Refactor:` - code refactoring
|
||||
- `Test:` - adding tests
|
||||
- `Chore:` - project maintenance
|
||||
|
||||
### 6. Pushing Changes
|
||||
|
||||
```bash
|
||||
# Push changes to your fork
|
||||
git push origin feature/short-description-of-changes
|
||||
```
|
||||
|
||||
### 7. Creating a Pull Request (PR)
|
||||
|
||||
1. Go to your fork on GitHub
|
||||
2. Click "New Pull Request"
|
||||
3. Select the base branch `main` of the original repository
|
||||
4. Fill out the PR description:
|
||||
- Brief description of changes
|
||||
- Motivation for changes
|
||||
- Screenshots (if applicable)
|
||||
|
||||
### 8. Review Process
|
||||
|
||||
- Project maintainers will review your PR
|
||||
- There may be comments and requests for changes
|
||||
- After approval, the PR will be merged
|
||||
|
||||
## 🛠 Code Requirements
|
||||
|
||||
- Follow PEP 8 for Python
|
||||
- Write clear and self-documenting code
|
||||
- Add type hints
|
||||
- Cover code with tests
|
||||
|
||||
## 🐛 Found a Bug?
|
||||
|
||||
1. Check existing Issues
|
||||
2. Create a new Issue with:
|
||||
- Bug description
|
||||
- Reproduction steps
|
||||
- Home Assistant version
|
||||
- Plugin version
|
||||
|
||||
## 📜 License
|
||||
|
||||
By contributing to the project, you agree to the [project's license](LICENSE).
|
||||
|
||||
## 🤔 Questions?
|
||||
|
||||
If you have any questions, create an Issue or contact the project maintainers.
|
||||
|
||||
**Thank you for your contribution!** 🎉
|
||||
@@ -1,21 +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
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
||||
does not provide legal services or legal advice. Distribution of
|
||||
Creative Commons public licenses does not create a lawyer-client or
|
||||
other relationship. Creative Commons makes its licenses and related
|
||||
information available on an "as-is" basis. Creative Commons gives no
|
||||
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
|
||||
copies or substantial portions of the Software.
|
||||
Using Creative Commons Public Licenses
|
||||
|
||||
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.
|
||||
Creative Commons public licenses provide a standard set of terms and
|
||||
conditions that creators and other rights holders may use to share
|
||||
original works of authorship and other material subject to copyright
|
||||
and certain other rights specified in the public license below. The
|
||||
following considerations are for informational purposes only, are not
|
||||
exhaustive, and do not form part of our licenses.
|
||||
|
||||
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.
|
||||
|
||||
@@ -1,73 +1,134 @@
|
||||
# 🤖 HA Text AI for Home Assistant
|
||||
|
||||
<div align="center">
|
||||
<div align="center">
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
[](https://opensource.org/licenses/MIT)
|
||||
[](https://github.com/hacs/integration)
|
||||
[](https://community.home-assistant.io/t/ha-text-ai-integration)
|
||||
  [](https://opensource.org/licenses/MIT) [](https://github.com/hacs/integration)   
|
||||
|
||||
<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](https://www.home-assistant.io/) with LLM multi-provider support
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
Transform your smart home experience with powerful AI assistance powered by OpenAI's GPT models. Get intelligent responses, automate complex scenarios, and enhance your home automation with 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>
|
||||
|
||||
---
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 🚧 ALPHA VERSION 🚧
|
||||
> 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
|
||||
|
||||
- 🧠 **Advanced AI Integration**:
|
||||
- Support for latest GPT models
|
||||
- 🧠 **Multi-Provider AI Integration**:
|
||||
- Support for OpenAI GPT models
|
||||
- Anthropic Claude integration
|
||||
- Custom API endpoints
|
||||
- Flexible model selection
|
||||
|
||||
- 💬 **Advanced Language Processing**:
|
||||
- Context-aware responses
|
||||
- Multi-turn conversations
|
||||
- 💬 **Natural Language Control**:
|
||||
- Control devices using everyday language
|
||||
- Get detailed explanations and recommendations
|
||||
- Custom system instructions
|
||||
- Natural conversation flow
|
||||
- 📝 **Smart Memory Management**:
|
||||
|
||||
- 📝 **Enhanced Memory Management**:
|
||||
- Persistent conversation history
|
||||
- Context-aware responses
|
||||
- Customizable history limits
|
||||
- ⚡ **Performance Optimized**:
|
||||
- Model-specific filtering
|
||||
|
||||
- ⚡ **Performance Optimization**:
|
||||
- Efficient token usage
|
||||
- Rate limit handling
|
||||
- Smart rate limiting
|
||||
- Response caching
|
||||
- Request interval control
|
||||
|
||||
- 🎯 **Advanced Customization**:
|
||||
- Adjustable response parameters
|
||||
- Per-request model selection
|
||||
- Adjustable parameters
|
||||
- Custom system prompts
|
||||
- Model selection per request
|
||||
- Temperature control
|
||||
|
||||
- 🔒 **Enhanced Security**:
|
||||
- Secure API key storage
|
||||
- Rate limiting protection
|
||||
- Error handling
|
||||
- 🎨 **User Experience**:
|
||||
- Usage monitoring
|
||||
|
||||
- 🎨 **Improved User Experience**:
|
||||
- Intuitive configuration UI
|
||||
- Detailed sensor attributes
|
||||
- Rich service interface
|
||||
- Model selection UI
|
||||
|
||||
- 🔄 **Automation Integration**:
|
||||
- Event-driven responses
|
||||
- Conditional logic support
|
||||
- Template compatibility
|
||||
- Model-specific automation
|
||||
|
||||
## 📋 Prerequisites
|
||||
|
||||
- Home Assistant 2023.8.0 or newer
|
||||
- OpenAI API key ([Get one here](https://platform.openai.com/account/api-keys))
|
||||
- Home Assistant 2024.11 or later
|
||||
- Active API key from:
|
||||
- OpenAI ([Get key](https://platform.openai.com/account/api-keys))
|
||||
- Anthropic ([Get key](https://console.anthropic.com/))
|
||||
- OpenRouter ([Get key](https://openrouter.ai/keys))
|
||||
- Python 3.9 or newer
|
||||
- Stable internet connection
|
||||
|
||||
### Configuration Options
|
||||
- API Provider (OpenAI/Anthropic)
|
||||
- API Key (provider-specific)
|
||||
- Model Selection (flexible, provider-specific models)
|
||||
- Temperature (Creativity control, 0.0-2.0)
|
||||
- Max Tokens (Response length limit)
|
||||
- Request Interval (API call throttling)
|
||||
- Custom API Endpoint (optional)
|
||||
|
||||
#### ⓘ Potentially Compatible Providers
|
||||
The integration is designed to be flexible and may work with other providers offering OpenAI-compatible APIs:
|
||||
- Groq
|
||||
- Together AI
|
||||
- Perplexity AI
|
||||
- Mistral AI
|
||||
- Google AI
|
||||
- Local AI servers (like Ollama)
|
||||
- Custom OpenAI-compatible endpoints
|
||||
|
||||
#### Additional Notes
|
||||
- Not all providers guarantee full compatibility
|
||||
- Performance may vary between providers
|
||||
- Check individual provider's documentation
|
||||
- Ensure your API key has sufficient credits/quota
|
||||
|
||||
#### Provider Compatibility Requirements
|
||||
To be compatible, a provider should support:
|
||||
- OpenAI-like REST API structure
|
||||
- JSON request/response format
|
||||
- Standard authentication method
|
||||
- Similar model parameter handling
|
||||
|
||||
## ⚡ Installation
|
||||
|
||||
### HACS Installation (Recommended)
|
||||
<a href="https://my.home-assistant.io/redirect/hacs_repository/?owner=smkrv&repository=ha-text-ai&category=Integration"><img src="https://my.home-assistant.io/badges/hacs_repository.svg" width="170" height="auto"></a>
|
||||
1. Open HACS in Home Assistant
|
||||
2. Click the "+" button
|
||||
3. Search for "HA Text AI"
|
||||
4. Click "Install"
|
||||
5. Restart Home Assistant
|
||||
2. Click on "Integrations"
|
||||
3. Click "..." in top right corner
|
||||
4. Select "Custom repositories"
|
||||
5. Add repository URL: `https://github.com/smkrv/ha-text-ai`
|
||||
6. Choose "Integration" as category
|
||||
7. Click "Download"
|
||||
8. Restart Home Assistant
|
||||
|
||||
### Manual Installation
|
||||
1. Download the latest release
|
||||
@@ -84,16 +145,61 @@ Transform your smart home experience with powerful AI assistance powered by Open
|
||||
4. Follow the configuration steps
|
||||
|
||||
### Via YAML
|
||||
|
||||
### Platform Configuration (Global Settings)
|
||||
|
||||
```yaml
|
||||
ha_text_ai:
|
||||
api_key: !secret openai_api_key
|
||||
model: gpt-3.5-turbo
|
||||
temperature: 0.7
|
||||
max_tokens: 1000
|
||||
request_interval: 1.0
|
||||
api_endpoint: https://api.openai.com/v1 # optional
|
||||
api_provider: openai # Required
|
||||
api_key: !secret ai_api_key # Required
|
||||
model: gpt-4o-mini # Strongly recommended
|
||||
temperature: 0.7 # Optional
|
||||
max_tokens: 1000 # Optional
|
||||
request_interval: 1.0 # Optional
|
||||
api_endpoint: https://api.openai.com/v1 # Required
|
||||
system_prompt: | # Optional
|
||||
You are a home automation expert assistant.
|
||||
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 |
|
||||
|
||||
#### 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
|
||||
|
||||
### ask_question
|
||||
@@ -101,9 +207,11 @@ ha_text_ai:
|
||||
service: ha_text_ai.ask_question
|
||||
data:
|
||||
question: "What's the optimal temperature for sleeping?"
|
||||
model: "gpt-4o" # optional
|
||||
model: "claude-3-sonnet" # optional
|
||||
temperature: 0.5 # optional
|
||||
max_tokens: 500 # optional
|
||||
context_messages: 10 #optional, number of previous messages to include in context, default: 5
|
||||
system_prompt: "You are a sleep optimization expert" # optional
|
||||
```
|
||||
|
||||
### set_system_prompt
|
||||
@@ -128,115 +236,171 @@ service: ha_text_ai.clear_history
|
||||
service: ha_text_ai.get_history
|
||||
data:
|
||||
limit: 5 # optional
|
||||
filter_model: "gpt-4o" # optional
|
||||
```
|
||||
|
||||
## 🔧 Advanced Examples
|
||||
### 🏷️ HA Text AI Sensor Naming Convention
|
||||
|
||||
### Smart Energy Management
|
||||
#### 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 Energy Optimization"
|
||||
trigger:
|
||||
platform: time_pattern
|
||||
hours: "/2"
|
||||
action:
|
||||
- service: ha_text_ai.ask_question
|
||||
data:
|
||||
question: >
|
||||
Current power usage: {{ states('sensor.total_power') }}W
|
||||
Temperature: {{ states('sensor.indoor_temperature') }}°C
|
||||
Time: {{ now().strftime('%H:%M') }}
|
||||
Occupancy: {{ states('binary_sensor.occupancy') }}
|
||||
|
||||
Analyze current energy usage and suggest optimizations
|
||||
considering comfort and efficiency.
|
||||
temperature: 0.3
|
||||
max_tokens: 200
|
||||
- service: notify.mobile_app
|
||||
data:
|
||||
message: "{{ states.sensor.ha_text_ai.attributes.response }}"
|
||||
- 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') }}
|
||||
```
|
||||
|
||||
### Contextual Lighting Control
|
||||
### 💡 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
|
||||
automation:
|
||||
alias: "AI Lighting Assistant"
|
||||
trigger:
|
||||
platform: state
|
||||
entity_id: binary_sensor.motion
|
||||
variables:
|
||||
context: >
|
||||
Time: {{ now().strftime('%H:%M') }}
|
||||
Light Level: {{ states('sensor.illuminance') }}
|
||||
Room: {{ trigger.to_state.attributes.room }}
|
||||
Activity: {{ states('input_select.current_activity') }}
|
||||
Weather: {{ states('weather.home') }}
|
||||
action:
|
||||
- service: ha_text_ai.ask_question
|
||||
data:
|
||||
question: >
|
||||
Based on this context:
|
||||
{{ context }}
|
||||
# Name of the AI model currently in use (e.g., latest version of GPT)
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'Model') }} # gpt-4o
|
||||
|
||||
Suggest optimal lighting settings for current conditions.
|
||||
model: gpt-3.5-turbo
|
||||
temperature: 0.4
|
||||
- service: scene.turn_on
|
||||
data:
|
||||
entity_id: >
|
||||
{{ states.sensor.ha_text_ai.attributes.response | regex_findall('scene\.[a-z_]+') | first }}
|
||||
# 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
|
||||
```
|
||||
|
||||
## 📊 Performance Optimization
|
||||
#### System Status
|
||||
```yaml
|
||||
# Current operational readiness of the AI service API
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'Api status') }} # ready
|
||||
|
||||
### Token Usage
|
||||
- Use focused system prompts
|
||||
- Implement response caching
|
||||
- Clear history periodically
|
||||
- Monitor token usage
|
||||
# Indicates if a request is currently being processed
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'Is processing') }} # false
|
||||
|
||||
### Response Time
|
||||
- Adjust request_interval
|
||||
- Use faster models for simple queries
|
||||
- Implement timeout handling
|
||||
- Cache frequent responses
|
||||
# Shows if the API has hit its request rate limit
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'Is rate limited') }} # false
|
||||
|
||||
### Memory Management
|
||||
- Set appropriate history limits
|
||||
- Clear unused contexts
|
||||
- Monitor memory usage
|
||||
- Use efficient data structures
|
||||
# Status of the specific API endpoint being used
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'Endpoint status') }} # ready
|
||||
```
|
||||
|
||||
## ❗ Troubleshooting
|
||||
#### Performance Metrics
|
||||
```yaml
|
||||
# Total number of successfully completed API requests
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'Successful requests') }} # 0
|
||||
|
||||
### API Issues
|
||||
- Verify API key validity
|
||||
- Check rate limits
|
||||
- Monitor usage quotas
|
||||
- Test endpoint accessibility
|
||||
# Number of API requests that encountered errors
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'Failed requests') }} # 0
|
||||
|
||||
### Performance Issues
|
||||
- Reduce max_tokens
|
||||
- Increase request_interval
|
||||
- Clear conversation history
|
||||
- Check network connectivity
|
||||
# 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
|
||||
```
|
||||
|
||||
#### 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
|
||||
```
|
||||
|
||||
### 💡 Pro Tips
|
||||
- Always check attribute existence
|
||||
- Use these attributes for monitoring and automation
|
||||
- Some values might be 0 or empty initially
|
||||
|
||||
### Integration Issues
|
||||
- Verify HA version compatibility
|
||||
- Check component dependencies
|
||||
- Review log files
|
||||
- Update configuration
|
||||
|
||||
## 📘 FAQ
|
||||
|
||||
**Q: Which AI providers are supported?**
|
||||
A: Currently OpenAI (GPT models) and Anthropic (Claude models) are supported, with more providers planned.
|
||||
|
||||
**Q: How can I reduce API costs?**
|
||||
A: Use GPT-3.5-Turbo or Claude-3-Sonnet for most queries, implement caching, and optimize token usage.
|
||||
|
||||
**Q: Are there limitations on the number of requests?**
|
||||
A: Depends on your API provider's plan. We recommend monitoring usage and implementing request throttling via `request_interval` configuration.
|
||||
|
||||
**Q: Can I use custom models?**
|
||||
A: Yes, you can configure custom endpoints and use any compatible model by specifying it in the configuration.
|
||||
|
||||
**Q: How do I switch between different AI providers?**
|
||||
A: Simply change the model parameter in your configuration or service calls to use the desired provider's model.
|
||||
|
||||
**Q: How can I reduce API costs?**
|
||||
A: Use GPT-3.5-Turbo for most queries, implement caching, and optimize token usage.
|
||||
|
||||
**Q: Is my data secure?**
|
||||
A: Yes, API keys are stored securely and data is transmitted via encrypted connections.
|
||||
A: Yes, your data is secure. The system operates entirely on your local machine, keeping your data under your control. API keys are stored securely and all external communications use encrypted connections.
|
||||
|
||||
**Q: Can I use custom models?**
|
||||
A: Yes, configure custom endpoints and models via configuration options.
|
||||
**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.
|
||||
|
||||
## 🤝 Contributing
|
||||
|
||||
@@ -248,15 +412,45 @@ Contributions welcome! Please read our [Contributing Guide](CONTRIBUTING.md).
|
||||
4. Push branch (`git push origin feature/Enhancement`)
|
||||
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
|
||||
|
||||
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">
|
||||
|
||||
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)
|
||||
|
||||
|
||||
@@ -1,14 +1,31 @@
|
||||
"""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
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
import os
|
||||
import shutil
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict
|
||||
|
||||
import voluptuous as vol
|
||||
from async_timeout import timeout
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
from homeassistant.helpers import aiohttp_client
|
||||
from homeassistant.const import CONF_API_KEY, CONF_NAME, Platform
|
||||
from homeassistant.core import HomeAssistant, ServiceCall
|
||||
from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers import aiohttp_client
|
||||
|
||||
from .coordinator import HATextAICoordinator
|
||||
from .api_client import APIClient
|
||||
from .const import (
|
||||
DOMAIN,
|
||||
PLATFORMS,
|
||||
@@ -17,88 +34,273 @@ from .const import (
|
||||
CONF_MAX_TOKENS,
|
||||
CONF_API_ENDPOINT,
|
||||
CONF_REQUEST_INTERVAL,
|
||||
CONF_API_PROVIDER,
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
API_PROVIDER_OPENAI,
|
||||
API_PROVIDER_ANTHROPIC,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_TEMPERATURE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
DEFAULT_API_ENDPOINT,
|
||||
DEFAULT_OPENAI_ENDPOINT,
|
||||
DEFAULT_ANTHROPIC_ENDPOINT,
|
||||
DEFAULT_REQUEST_INTERVAL,
|
||||
DEFAULT_CONTEXT_MESSAGES,
|
||||
API_TIMEOUT,
|
||||
SERVICE_ASK_QUESTION,
|
||||
SERVICE_CLEAR_HISTORY,
|
||||
SERVICE_GET_HISTORY,
|
||||
SERVICE_SET_SYSTEM_PROMPT,
|
||||
DEFAULT_MAX_HISTORY,
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
|
||||
|
||||
async def async_setup(hass: HomeAssistant, config: dict[str, Any]) -> bool:
|
||||
SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
|
||||
vol.Required("instance"): cv.string,
|
||||
vol.Required("question"): cv.string,
|
||||
vol.Optional("system_prompt"): cv.string,
|
||||
vol.Optional("model"): cv.string,
|
||||
vol.Optional("temperature"): cv.positive_float,
|
||||
vol.Optional("max_tokens"): cv.positive_int,
|
||||
vol.Optional("context_messages"): cv.positive_int,
|
||||
})
|
||||
|
||||
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
|
||||
vol.Required("instance"): cv.string,
|
||||
vol.Required("prompt"): cv.string,
|
||||
})
|
||||
|
||||
SERVICE_SCHEMA_GET_HISTORY = vol.Schema({
|
||||
vol.Required("instance"): cv.string,
|
||||
vol.Optional("limit"): cv.positive_int,
|
||||
vol.Optional("filter_model"): cv.string,
|
||||
})
|
||||
|
||||
def get_coordinator_by_instance(hass: HomeAssistant, instance: str) -> HATextAICoordinator:
|
||||
"""Get coordinator by instance name."""
|
||||
if instance.startswith("sensor."):
|
||||
instance = instance.replace("sensor.ha_text_ai_", "", 1)
|
||||
|
||||
for entry_id, coord in hass.data[DOMAIN].items():
|
||||
if isinstance(coord, HATextAICoordinator) and coord.instance_name.lower() == instance.lower():
|
||||
return coord
|
||||
|
||||
raise HomeAssistantError(f"Instance {instance} not found")
|
||||
|
||||
async def async_setup(hass: HomeAssistant, config: Dict[str, Any]) -> bool:
|
||||
"""Set up the HA Text AI component."""
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
|
||||
try:
|
||||
source = os.path.join(os.path.dirname(__file__), 'icons', 'icon.svg')
|
||||
dest_dir = os.path.join(hass.config.path('www'), 'icons')
|
||||
os.makedirs(dest_dir, exist_ok=True)
|
||||
dest = os.path.join(dest_dir, 'icon.png')
|
||||
if not os.path.exists(dest):
|
||||
shutil.copyfile(source, dest)
|
||||
except Exception as ex:
|
||||
_LOGGER.warning("Failed to copy custom icon: %s", str(ex))
|
||||
|
||||
async def async_ask_question(call: ServiceCall) -> None:
|
||||
"""Handle ask_question service."""
|
||||
try:
|
||||
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||
await coordinator.async_ask_question(
|
||||
question=call.data["question"],
|
||||
model=call.data.get("model"),
|
||||
temperature=call.data.get("temperature"),
|
||||
max_tokens=call.data.get("max_tokens"),
|
||||
system_prompt=call.data.get("system_prompt"),
|
||||
context_messages=call.data.get("context_messages"),
|
||||
)
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error asking question: %s", str(err))
|
||||
raise HomeAssistantError(f"Failed to process question: {str(err)}")
|
||||
|
||||
async def async_clear_history(call: ServiceCall) -> None:
|
||||
"""Handle clear_history service."""
|
||||
try:
|
||||
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||
await coordinator.async_clear_history()
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error clearing history: %s", str(err))
|
||||
raise HomeAssistantError(f"Failed to clear history: {str(err)}")
|
||||
|
||||
async def async_get_history(call: ServiceCall) -> list:
|
||||
"""Handle get_history service."""
|
||||
try:
|
||||
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||
return await coordinator.async_get_history(
|
||||
limit=call.data.get("limit"),
|
||||
filter_model=call.data.get("filter_model")
|
||||
)
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error getting history: %s", str(err))
|
||||
raise HomeAssistantError(f"Failed to get history: {str(err)}")
|
||||
|
||||
async def async_set_system_prompt(call: ServiceCall) -> None:
|
||||
"""Handle set_system_prompt service."""
|
||||
try:
|
||||
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||
await coordinator.async_set_system_prompt(call.data["prompt"])
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error setting system prompt: %s", str(err))
|
||||
raise HomeAssistantError(f"Failed to set system prompt: {str(err)}")
|
||||
|
||||
hass.services.async_register(
|
||||
DOMAIN,
|
||||
SERVICE_ASK_QUESTION,
|
||||
async_ask_question,
|
||||
schema=SERVICE_SCHEMA_ASK_QUESTION
|
||||
)
|
||||
|
||||
hass.services.async_register(
|
||||
DOMAIN,
|
||||
SERVICE_CLEAR_HISTORY,
|
||||
async_clear_history,
|
||||
schema=vol.Schema({vol.Required("instance"): cv.string})
|
||||
)
|
||||
|
||||
hass.services.async_register(
|
||||
DOMAIN,
|
||||
SERVICE_GET_HISTORY,
|
||||
async_get_history,
|
||||
schema=SERVICE_SCHEMA_GET_HISTORY
|
||||
)
|
||||
|
||||
hass.services.async_register(
|
||||
DOMAIN,
|
||||
SERVICE_SET_SYSTEM_PROMPT,
|
||||
async_set_system_prompt,
|
||||
schema=SERVICE_SCHEMA_SET_SYSTEM_PROMPT
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
async def async_check_api(session, endpoint: str, headers: dict, provider: str) -> bool:
|
||||
"""Check API availability for different providers."""
|
||||
try:
|
||||
if provider == API_PROVIDER_ANTHROPIC:
|
||||
check_url = f"{endpoint}/v1/models"
|
||||
else: # OpenAI
|
||||
check_url = f"{endpoint}/models"
|
||||
|
||||
async with timeout(API_TIMEOUT):
|
||||
async with session.get(check_url, headers=headers) as response:
|
||||
if response.status in [200, 404]:
|
||||
return True
|
||||
elif response.status == 401:
|
||||
raise ConfigEntryNotReady("Invalid API key")
|
||||
elif response.status == 429:
|
||||
_LOGGER.warning("Rate limit exceeded during API check")
|
||||
return False
|
||||
else:
|
||||
_LOGGER.error("API check failed with status: %d", response.status)
|
||||
return False
|
||||
except Exception as ex:
|
||||
_LOGGER.error("API check error: %s", str(ex))
|
||||
return False
|
||||
|
||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Set up HA Text AI from a config entry."""
|
||||
_LOGGER.debug(f"Setting up HA Text AI entry: {entry.data}")
|
||||
|
||||
try:
|
||||
if CONF_API_PROVIDER not in entry.data:
|
||||
_LOGGER.error("API provider not specified")
|
||||
raise ConfigEntryNotReady("API provider is required")
|
||||
|
||||
# Get configuration
|
||||
session = aiohttp_client.async_get_clientsession(hass)
|
||||
api_provider = entry.data.get(CONF_API_PROVIDER)
|
||||
model = entry.data.get(CONF_MODEL, DEFAULT_MODEL)
|
||||
endpoint = entry.data.get(
|
||||
CONF_API_ENDPOINT,
|
||||
DEFAULT_OPENAI_ENDPOINT if api_provider == API_PROVIDER_OPENAI
|
||||
else DEFAULT_ANTHROPIC_ENDPOINT
|
||||
).rstrip('/')
|
||||
api_key = entry.data[CONF_API_KEY]
|
||||
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
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json"
|
||||
}
|
||||
|
||||
if is_anthropic:
|
||||
headers["x-api-key"] = api_key
|
||||
headers["anthropic-version"] = "2023-06-01"
|
||||
else:
|
||||
headers["Authorization"] = f"Bearer {api_key}"
|
||||
|
||||
if not await async_check_api(session, endpoint, headers, api_provider):
|
||||
raise ConfigEntryNotReady("API connection failed")
|
||||
|
||||
_LOGGER.debug("Creating API client for %s with endpoint %s", api_provider, endpoint)
|
||||
|
||||
api_client = APIClient(
|
||||
session=session,
|
||||
endpoint=endpoint,
|
||||
headers=headers,
|
||||
api_provider=api_provider,
|
||||
model=model,
|
||||
)
|
||||
|
||||
coordinator = HATextAICoordinator(
|
||||
hass,
|
||||
api_key=entry.data[CONF_API_KEY],
|
||||
endpoint=entry.data.get(CONF_API_ENDPOINT, DEFAULT_API_ENDPOINT),
|
||||
model=entry.data.get(CONF_MODEL, DEFAULT_MODEL),
|
||||
temperature=entry.data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE),
|
||||
max_tokens=entry.data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS),
|
||||
request_interval=entry.data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL),
|
||||
session=session,
|
||||
hass=hass,
|
||||
client=api_client,
|
||||
model=model,
|
||||
update_interval=request_interval,
|
||||
instance_name=instance_name,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
max_history_size=max_history_size,
|
||||
context_messages=context_messages,
|
||||
is_anthropic=is_anthropic,
|
||||
)
|
||||
|
||||
try:
|
||||
await coordinator.async_config_entry_first_refresh()
|
||||
except Exception as refresh_ex:
|
||||
_LOGGER.error("Failed to refresh coordinator: %s", str(refresh_ex))
|
||||
return False
|
||||
|
||||
if not coordinator.last_update_success:
|
||||
_LOGGER.error("Failed to communicate with OpenAI API")
|
||||
return False
|
||||
_LOGGER.debug(f"Created coordinator for {instance_name}")
|
||||
|
||||
# Store coordinator
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
hass.data[DOMAIN][entry.entry_id] = coordinator
|
||||
|
||||
try:
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
except Exception as setup_ex:
|
||||
_LOGGER.error("Failed to setup platforms: %s", str(setup_ex))
|
||||
return False
|
||||
_LOGGER.debug(f"Stored coordinator in hass.data[{DOMAIN}][{entry.entry_id}]")
|
||||
|
||||
_LOGGER.info(
|
||||
"Successfully set up HA Text AI with model: %s",
|
||||
entry.data.get(CONF_MODEL, DEFAULT_MODEL)
|
||||
)
|
||||
# Set up platforms
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
_LOGGER.debug(f"Setup completed for {instance_name}")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as ex:
|
||||
_LOGGER.exception("Unexpected error setting up entry: %s", str(ex))
|
||||
return False
|
||||
except Exception as err:
|
||||
_LOGGER.exception(f"Error setting up HA Text AI: {err}")
|
||||
raise
|
||||
|
||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
"""Unload a config entry."""
|
||||
try:
|
||||
if entry.entry_id not in hass.data.get(DOMAIN, {}):
|
||||
return True
|
||||
if entry.entry_id in hass.data[DOMAIN]:
|
||||
coordinator = hass.data[DOMAIN][entry.entry_id]
|
||||
|
||||
if hasattr(coordinator.client, 'shutdown'):
|
||||
await coordinator.client.shutdown()
|
||||
|
||||
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
if unload_ok:
|
||||
coordinator = hass.data[DOMAIN].pop(entry.entry_id)
|
||||
await coordinator.async_shutdown()
|
||||
hass.data[DOMAIN].pop(entry.entry_id)
|
||||
|
||||
return unload_ok
|
||||
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
|
||||
except Exception as ex:
|
||||
_LOGGER.exception("Error unloading entry: %s", str(ex))
|
||||
return False
|
||||
|
||||
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||
"""Reload config entry."""
|
||||
try:
|
||||
await async_unload_entry(hass, entry)
|
||||
await async_setup_entry(hass, entry)
|
||||
except Exception as ex:
|
||||
_LOGGER.exception("Error reloading entry: %s", str(ex))
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
"""
|
||||
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 asyncio
|
||||
from typing import Any, Dict, List, Optional
|
||||
from aiohttp import ClientSession, ClientTimeout
|
||||
from async_timeout import timeout
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from .const import (
|
||||
API_TIMEOUT,
|
||||
API_RETRY_COUNT,
|
||||
API_PROVIDER_ANTHROPIC,
|
||||
MIN_TEMPERATURE,
|
||||
MAX_TEMPERATURE,
|
||||
MIN_MAX_TOKENS,
|
||||
MAX_MAX_TOKENS,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class APIClient:
|
||||
"""API Client for OpenAI and Anthropic."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
session: ClientSession,
|
||||
endpoint: str,
|
||||
headers: Dict[str, str],
|
||||
api_provider: str,
|
||||
model: str,
|
||||
) -> None:
|
||||
"""Initialize API client."""
|
||||
self.session = session
|
||||
self.endpoint = endpoint
|
||||
self.headers = headers
|
||||
self.api_provider = api_provider
|
||||
self.model = model
|
||||
self.timeout = ClientTimeout(total=API_TIMEOUT)
|
||||
|
||||
def _validate_parameters(
|
||||
self,
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
) -> None:
|
||||
"""Validate API parameters."""
|
||||
if not MIN_TEMPERATURE <= temperature <= MAX_TEMPERATURE:
|
||||
raise ValueError(
|
||||
f"Temperature must be between {MIN_TEMPERATURE} and {MAX_TEMPERATURE}"
|
||||
)
|
||||
if not MIN_MAX_TOKENS <= max_tokens <= MAX_MAX_TOKENS:
|
||||
raise ValueError(
|
||||
f"Max tokens must be between {MIN_MAX_TOKENS} and {MAX_MAX_TOKENS}"
|
||||
)
|
||||
|
||||
async def _make_request(
|
||||
self,
|
||||
url: str,
|
||||
payload: Dict[str, Any],
|
||||
) -> Dict[str, Any]:
|
||||
"""Make API request with retry logic."""
|
||||
_LOGGER.debug(f"API Request: URL={url}, Payload={payload}")
|
||||
for attempt in range(API_RETRY_COUNT):
|
||||
try:
|
||||
async with timeout(API_TIMEOUT):
|
||||
async with self.session.post(
|
||||
url,
|
||||
json=payload,
|
||||
headers=self.headers,
|
||||
timeout=self.timeout,
|
||||
) as response:
|
||||
_LOGGER.debug(f"Response status: {response.status}")
|
||||
if response.status != 200:
|
||||
error_data = await response.json()
|
||||
_LOGGER.error(f"API error: {error_data}")
|
||||
raise HomeAssistantError(f"API error: {error_data}")
|
||||
return await response.json()
|
||||
except asyncio.TimeoutError:
|
||||
_LOGGER.warning(f"Timeout on attempt {attempt + 1}")
|
||||
if attempt == API_RETRY_COUNT - 1:
|
||||
raise HomeAssistantError("API request timed out")
|
||||
await asyncio.sleep(1 * (attempt + 1))
|
||||
except Exception as e:
|
||||
_LOGGER.warning(f"API request failed on attempt {attempt + 1}: {str(e)}")
|
||||
if attempt == API_RETRY_COUNT - 1:
|
||||
raise
|
||||
await asyncio.sleep(1 * (attempt + 1))
|
||||
|
||||
async def create(
|
||||
self,
|
||||
model: str,
|
||||
messages: List[Dict[str, str]],
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
) -> Dict[str, Any]:
|
||||
"""Create completion using appropriate API."""
|
||||
try:
|
||||
self._validate_parameters(temperature, max_tokens)
|
||||
|
||||
if self.api_provider == API_PROVIDER_ANTHROPIC:
|
||||
return await self._create_anthropic_completion(
|
||||
model, messages, temperature, max_tokens
|
||||
)
|
||||
else:
|
||||
return await self._create_openai_completion(
|
||||
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:
|
||||
_LOGGER.error("API request failed: %s", str(e))
|
||||
raise HomeAssistantError(f"API request failed: {str(e)}")
|
||||
|
||||
async def _create_openai_completion(
|
||||
self,
|
||||
model: str,
|
||||
messages: List[Dict[str, str]],
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
) -> Dict[str, Any]:
|
||||
"""Create completion using OpenAI API."""
|
||||
url = f"{self.endpoint}/chat/completions"
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
"temperature": temperature,
|
||||
"max_tokens": max_tokens,
|
||||
}
|
||||
|
||||
data = await self._make_request(url, payload)
|
||||
return {
|
||||
"choices": [
|
||||
{
|
||||
"message": {"content": data["choices"][0]["message"]["content"]},
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": data["usage"]["prompt_tokens"],
|
||||
"completion_tokens": data["usage"]["completion_tokens"],
|
||||
"total_tokens": data["usage"]["total_tokens"],
|
||||
},
|
||||
}
|
||||
|
||||
async def _create_anthropic_completion(
|
||||
self,
|
||||
model: str,
|
||||
messages: List[Dict[str, str]],
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
) -> Dict[str, Any]:
|
||||
"""Create completion using Anthropic API."""
|
||||
url = f"{self.endpoint}/v1/messages"
|
||||
|
||||
system_prompt = None
|
||||
filtered_messages = []
|
||||
for msg in messages:
|
||||
if msg['role'] == 'system':
|
||||
if system_prompt is None:
|
||||
system_prompt = msg['content']
|
||||
else:
|
||||
system_prompt += f" {msg['content']}"
|
||||
else:
|
||||
filtered_messages.append(msg)
|
||||
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": filtered_messages,
|
||||
"max_tokens": max_tokens,
|
||||
"temperature": temperature,
|
||||
}
|
||||
|
||||
if system_prompt:
|
||||
payload["system"] = system_prompt
|
||||
|
||||
data = await self._make_request(url, payload)
|
||||
return {
|
||||
"choices": [
|
||||
{
|
||||
"message": {"content": data["content"][0]["text"]},
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": data["usage"]["input_tokens"],
|
||||
"completion_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()
|
||||
@@ -1,19 +1,21 @@
|
||||
"""Config flow for HA text AI integration."""
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
import voluptuous as vol
|
||||
import ssl
|
||||
import certifi
|
||||
import asyncio
|
||||
from async_timeout import timeout
|
||||
import aiohttp
|
||||
from urllib.parse import urlparse
|
||||
"""
|
||||
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
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
import voluptuous as vol
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.const import CONF_API_KEY, CONF_NAME
|
||||
from homeassistant.core import callback
|
||||
from openai import AsyncOpenAI
|
||||
from openai import OpenAIError, APIError, APIConnectionError, AuthenticationError, RateLimitError
|
||||
from homeassistant.data_entry_flow import FlowResult
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
from homeassistant.helpers import selector
|
||||
|
||||
from .const import (
|
||||
DOMAIN,
|
||||
@@ -22,261 +24,326 @@ from .const import (
|
||||
CONF_MAX_TOKENS,
|
||||
CONF_API_ENDPOINT,
|
||||
CONF_REQUEST_INTERVAL,
|
||||
CONF_API_PROVIDER,
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
API_PROVIDER_OPENAI,
|
||||
API_PROVIDER_ANTHROPIC,
|
||||
API_PROVIDERS,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_TEMPERATURE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
DEFAULT_API_ENDPOINT,
|
||||
DEFAULT_REQUEST_INTERVAL,
|
||||
DEFAULT_OPENAI_ENDPOINT,
|
||||
DEFAULT_ANTHROPIC_ENDPOINT,
|
||||
DEFAULT_CONTEXT_MESSAGES,
|
||||
MIN_TEMPERATURE,
|
||||
MAX_TEMPERATURE,
|
||||
MIN_MAX_TOKENS,
|
||||
MAX_MAX_TOKENS,
|
||||
MIN_REQUEST_INTERVAL,
|
||||
DEFAULT_NAME_PREFIX,
|
||||
DEFAULT_MAX_HISTORY,
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
)
|
||||
|
||||
import logging
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# Create SSL context at module level
|
||||
SSL_CONTEXT = ssl.create_default_context(cafile=certifi.where())
|
||||
|
||||
STEP_USER_DATA_SCHEMA = vol.Schema({
|
||||
vol.Required(CONF_API_KEY): str,
|
||||
vol.Optional(CONF_MODEL, default=DEFAULT_MODEL): str,
|
||||
vol.Optional(
|
||||
CONF_TEMPERATURE,
|
||||
default=DEFAULT_TEMPERATURE
|
||||
): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=0, max=2)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_MAX_TOKENS,
|
||||
default=DEFAULT_MAX_TOKENS
|
||||
): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=4096)
|
||||
),
|
||||
vol.Optional(CONF_API_ENDPOINT, default=DEFAULT_API_ENDPOINT): str,
|
||||
vol.Optional(
|
||||
CONF_REQUEST_INTERVAL,
|
||||
default=DEFAULT_REQUEST_INTERVAL
|
||||
): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=0.1)
|
||||
),
|
||||
})
|
||||
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()
|
||||
|
||||
async def validate_endpoint(endpoint: str) -> Tuple[bool, str]:
|
||||
"""Validate API endpoint accessibility."""
|
||||
try:
|
||||
parsed_url = urlparse(endpoint)
|
||||
if parsed_url.scheme not in ('http', 'https'):
|
||||
return False, "invalid_endpoint_scheme"
|
||||
|
||||
connector = aiohttp.TCPConnector(ssl=SSL_CONTEXT)
|
||||
async with timeout(5):
|
||||
async with aiohttp.ClientSession(connector=connector) as session:
|
||||
async with session.get(endpoint) as response:
|
||||
if response.status != 200:
|
||||
return False, "endpoint_not_available"
|
||||
return True, ""
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error validating endpoint: %s", str(e))
|
||||
return False, "endpoint_error"
|
||||
|
||||
async def validate_api_connection(
|
||||
api_key: str,
|
||||
endpoint: str,
|
||||
model: str,
|
||||
retry_count: int = 3,
|
||||
retry_delay: float = 1.0
|
||||
) -> Tuple[bool, str, list]:
|
||||
"""Validate API connection with improved retry logic."""
|
||||
# Validate endpoint first
|
||||
endpoint_valid, endpoint_error = await validate_endpoint(endpoint)
|
||||
if not endpoint_valid:
|
||||
return False, endpoint_error, []
|
||||
|
||||
connector = aiohttp.TCPConnector(ssl=SSL_CONTEXT)
|
||||
async with aiohttp.ClientSession(connector=connector) as session:
|
||||
for attempt in range(retry_count):
|
||||
try:
|
||||
async with timeout(10):
|
||||
client = AsyncOpenAI(
|
||||
api_key=api_key,
|
||||
base_url=endpoint,
|
||||
http_client=session
|
||||
)
|
||||
|
||||
models = await client.models.list()
|
||||
model_ids = [model.id for model in models.data]
|
||||
|
||||
if model not in model_ids:
|
||||
_LOGGER.warning(
|
||||
"Model %s not found in available models: %s",
|
||||
model,
|
||||
", ".join(model_ids)
|
||||
)
|
||||
return False, "invalid_model", model_ids
|
||||
return True, "", model_ids
|
||||
|
||||
except asyncio.TimeoutError:
|
||||
_LOGGER.warning(
|
||||
"Timeout during API validation (attempt %d/%d)",
|
||||
attempt + 1,
|
||||
retry_count
|
||||
)
|
||||
if attempt == retry_count - 1:
|
||||
return False, "timeout", []
|
||||
await asyncio.sleep(retry_delay)
|
||||
|
||||
except AuthenticationError as err:
|
||||
_LOGGER.error("Authentication error: %s", str(err))
|
||||
return False, "invalid_auth", []
|
||||
|
||||
except RateLimitError as err:
|
||||
_LOGGER.error("Rate limit exceeded: %s", str(err))
|
||||
return False, "rate_limit", []
|
||||
|
||||
except APIConnectionError as err:
|
||||
_LOGGER.error("API connection error: %s", str(err))
|
||||
return False, "cannot_connect", []
|
||||
|
||||
except APIError as err:
|
||||
_LOGGER.error("API error: %s", str(err))
|
||||
return False, "api_error", []
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.exception("Unexpected error during validation: %s", str(err))
|
||||
return False, "unknown", []
|
||||
|
||||
class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow for HA text AI."""
|
||||
|
||||
VERSION = 1
|
||||
|
||||
async def async_step_user(
|
||||
self,
|
||||
user_input: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
def __init__(self) -> None:
|
||||
"""Initialize flow."""
|
||||
self._errors = {}
|
||||
self._data = {}
|
||||
self._provider = None
|
||||
|
||||
async def async_step_user(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
||||
"""Handle the initial step."""
|
||||
errors: Dict[str, str] = {}
|
||||
|
||||
if user_input is not None:
|
||||
try:
|
||||
# Validate URL format
|
||||
endpoint = user_input.get(CONF_API_ENDPOINT, DEFAULT_API_ENDPOINT)
|
||||
try:
|
||||
result = urlparse(endpoint)
|
||||
if not all([result.scheme, result.netloc]):
|
||||
errors["base"] = "invalid_url_format"
|
||||
return self.async_show_form(
|
||||
step_id="user",
|
||||
data_schema=STEP_USER_DATA_SCHEMA,
|
||||
errors=errors
|
||||
if user_input is None:
|
||||
return self.async_show_form(
|
||||
step_id="user",
|
||||
data_schema=vol.Schema({
|
||||
vol.Required(CONF_API_PROVIDER): selector.SelectSelector(
|
||||
selector.SelectSelectorConfig(
|
||||
options=API_PROVIDERS,
|
||||
translation_key="api_provider"
|
||||
)
|
||||
except Exception as e:
|
||||
_LOGGER.error("URL parsing error: %s", str(e))
|
||||
errors["base"] = "invalid_url_format"
|
||||
return self.async_show_form(
|
||||
step_id="user",
|
||||
data_schema=STEP_USER_DATA_SCHEMA,
|
||||
errors=errors
|
||||
)
|
||||
),
|
||||
})
|
||||
)
|
||||
|
||||
# Validate input data
|
||||
user_input = STEP_USER_DATA_SCHEMA(user_input)
|
||||
self._provider = user_input[CONF_API_PROVIDER]
|
||||
return await self.async_step_provider()
|
||||
|
||||
is_valid, error_code, available_models = await validate_api_connection(
|
||||
user_input[CONF_API_KEY],
|
||||
endpoint,
|
||||
user_input[CONF_MODEL]
|
||||
async def async_step_provider(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
||||
"""Handle provider configuration step."""
|
||||
self._errors = {}
|
||||
|
||||
if user_input is None:
|
||||
default_endpoint = (
|
||||
DEFAULT_OPENAI_ENDPOINT if self._provider == API_PROVIDER_OPENAI
|
||||
else DEFAULT_ANTHROPIC_ENDPOINT
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="provider",
|
||||
data_schema=vol.Schema({
|
||||
vol.Required(CONF_NAME, default="my_assistant"): str,
|
||||
vol.Required(CONF_API_KEY): str,
|
||||
vol.Required(CONF_MODEL, default=DEFAULT_MODEL): str,
|
||||
vol.Required(CONF_API_ENDPOINT, default=default_endpoint): str,
|
||||
vol.Optional(CONF_TEMPERATURE, default=DEFAULT_TEMPERATURE): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
||||
),
|
||||
vol.Optional(CONF_MAX_TOKENS, default=DEFAULT_MAX_TOKENS): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
|
||||
),
|
||||
vol.Optional(CONF_REQUEST_INTERVAL, default=DEFAULT_REQUEST_INTERVAL): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
default=DEFAULT_CONTEXT_MESSAGES
|
||||
): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=20)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
default=DEFAULT_MAX_HISTORY
|
||||
): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=100)
|
||||
),
|
||||
})
|
||||
)
|
||||
|
||||
input_copy = user_input.copy()
|
||||
|
||||
try:
|
||||
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)}
|
||||
)
|
||||
|
||||
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)}
|
||||
)
|
||||
|
||||
if is_valid:
|
||||
await self.async_set_unique_id(user_input[CONF_API_KEY])
|
||||
self._abort_if_unique_id_configured()
|
||||
return await self._create_entry(input_copy)
|
||||
|
||||
return self.async_create_entry(
|
||||
title="HA text AI",
|
||||
data=user_input
|
||||
)
|
||||
def _validate_and_normalize_name(self, name: str) -> str:
|
||||
"""
|
||||
Validate and normalize name with detailed error handling.
|
||||
|
||||
errors["base"] = error_code
|
||||
if error_code == "invalid_model":
|
||||
_LOGGER.warning(
|
||||
"Selected model %s not found in available models: %s",
|
||||
user_input[CONF_MODEL],
|
||||
", ".join(available_models)
|
||||
)
|
||||
Raises:
|
||||
ValueError: If name is invalid
|
||||
|
||||
except vol.Invalid as err:
|
||||
_LOGGER.error("Validation error: %s", str(err))
|
||||
errors["base"] = "invalid_input"
|
||||
Returns:
|
||||
Normalized name
|
||||
"""
|
||||
if not name:
|
||||
raise ValueError("empty")
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="user",
|
||||
data_schema=STEP_USER_DATA_SCHEMA,
|
||||
errors=errors,
|
||||
description_placeholders={
|
||||
"default_model": DEFAULT_MODEL,
|
||||
"default_endpoint": DEFAULT_API_ENDPOINT,
|
||||
name = name.strip()
|
||||
normalized = ''.join(
|
||||
c if c.isalnum() or c in ' _' else '_' # Only allow underscores
|
||||
for c in name
|
||||
)
|
||||
|
||||
normalized = normalized.replace(' ', '_').lower()
|
||||
|
||||
for entry in self._async_current_entries():
|
||||
if entry.data.get(CONF_NAME, "") == normalized:
|
||||
raise ValueError("name_exists")
|
||||
|
||||
normalized = normalized[:50]
|
||||
|
||||
if not normalized:
|
||||
raise ValueError("empty")
|
||||
|
||||
return normalized
|
||||
|
||||
async def _async_validate_api(self, user_input: Dict[str, Any]) -> bool:
|
||||
"""Validate API connection."""
|
||||
try:
|
||||
session = async_get_clientsession(self.hass)
|
||||
headers = self._get_api_headers(user_input)
|
||||
endpoint = user_input[CONF_API_ENDPOINT].rstrip('/')
|
||||
|
||||
check_url = (
|
||||
f"{endpoint}/v1/models" if self._provider == API_PROVIDER_ANTHROPIC
|
||||
else f"{endpoint}/models"
|
||||
)
|
||||
|
||||
async with session.get(check_url, headers=headers) as response:
|
||||
if response.status == 401:
|
||||
self._errors["base"] = "invalid_auth"
|
||||
return False
|
||||
elif response.status not in [200, 404]:
|
||||
self._errors["base"] = "cannot_connect"
|
||||
return False
|
||||
return True
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.error("API validation error: %s", str(err))
|
||||
self._errors["base"] = "cannot_connect"
|
||||
return False
|
||||
|
||||
def _get_api_headers(self, user_input: Dict[str, Any]) -> Dict[str, str]:
|
||||
"""Get API headers based on provider."""
|
||||
api_key = user_input[CONF_API_KEY]
|
||||
|
||||
if self._provider == API_PROVIDER_ANTHROPIC:
|
||||
return {
|
||||
"x-api-key": api_key,
|
||||
"anthropic-version": "2023-06-01",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
return {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
async def _create_entry(self, user_input: Dict[str, Any]) -> FlowResult:
|
||||
"""Create the config entry with comprehensive data preservation."""
|
||||
instance_name = user_input[CONF_NAME]
|
||||
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(
|
||||
title=instance_name,
|
||||
data=entry_data
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@callback
|
||||
def async_get_options_flow(
|
||||
config_entry: config_entries.ConfigEntry,
|
||||
) -> config_entries.OptionsFlow:
|
||||
def async_get_options_flow(config_entry: config_entries.ConfigEntry) -> config_entries.OptionsFlow:
|
||||
"""Get the options flow for this handler."""
|
||||
return OptionsFlowHandler(config_entry)
|
||||
|
||||
|
||||
class OptionsFlowHandler(config_entries.OptionsFlow):
|
||||
"""Handle options flow for HA text AI."""
|
||||
"""Handle options flow."""
|
||||
|
||||
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
|
||||
"""Initialize options flow."""
|
||||
self.config_entry = config_entry
|
||||
|
||||
async def async_step_init(
|
||||
self,
|
||||
user_input: Optional[Dict[str, Any]] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""Handle options flow."""
|
||||
async def async_step_init(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
||||
"""Manage the options."""
|
||||
if user_input is not None:
|
||||
return self.async_create_entry(title="", data=user_input)
|
||||
|
||||
options_schema = vol.Schema({
|
||||
vol.Optional(
|
||||
CONF_TEMPERATURE,
|
||||
default=self.config_entry.options.get(
|
||||
CONF_TEMPERATURE, DEFAULT_TEMPERATURE
|
||||
),
|
||||
description={"suggested_value": DEFAULT_TEMPERATURE},
|
||||
): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=0, max=2)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_MAX_TOKENS,
|
||||
default=self.config_entry.options.get(
|
||||
CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS
|
||||
),
|
||||
description={"suggested_value": DEFAULT_MAX_TOKENS},
|
||||
): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=4096)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_REQUEST_INTERVAL,
|
||||
default=self.config_entry.options.get(
|
||||
CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL
|
||||
),
|
||||
description={"suggested_value": DEFAULT_REQUEST_INTERVAL},
|
||||
): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=0.1)
|
||||
),
|
||||
})
|
||||
current_data = {**self.config_entry.data, **self.config_entry.options}
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="init",
|
||||
data_schema=options_schema,
|
||||
data_schema=vol.Schema({
|
||||
vol.Optional(
|
||||
CONF_MODEL,
|
||||
default=current_data.get(CONF_MODEL, DEFAULT_MODEL)
|
||||
): str,
|
||||
vol.Optional(
|
||||
CONF_TEMPERATURE,
|
||||
default=current_data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
||||
): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_MAX_TOKENS,
|
||||
default=current_data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
||||
): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_REQUEST_INTERVAL,
|
||||
default=current_data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
||||
): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
default=current_data.get(
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
DEFAULT_CONTEXT_MESSAGES
|
||||
)
|
||||
): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=20)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
default=current_data.get(
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
DEFAULT_MAX_HISTORY
|
||||
)
|
||||
): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=100)
|
||||
),
|
||||
})
|
||||
)
|
||||
|
||||
@@ -1,10 +1,33 @@
|
||||
"""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 homeassistant.const import Platform
|
||||
import voluptuous as vol
|
||||
from homeassistant.const import Platform, CONF_API_KEY, CONF_NAME
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
|
||||
# Domain and platforms
|
||||
DOMAIN: Final = "ha_text_ai"
|
||||
PLATFORMS: Final = [Platform.SENSOR]
|
||||
PLATFORMS: list[str] = ["sensor"]
|
||||
|
||||
# Provider configuration
|
||||
CONF_API_PROVIDER: Final = "api_provider"
|
||||
API_PROVIDER_OPENAI: Final = "openai"
|
||||
API_PROVIDER_ANTHROPIC: Final = "anthropic"
|
||||
|
||||
API_PROVIDERS: Final = [
|
||||
API_PROVIDER_OPENAI,
|
||||
API_PROVIDER_ANTHROPIC
|
||||
]
|
||||
|
||||
# Default endpoints
|
||||
DEFAULT_OPENAI_ENDPOINT: Final = "https://api.openai.com/v1"
|
||||
DEFAULT_ANTHROPIC_ENDPOINT: Final = "https://api.anthropic.com"
|
||||
|
||||
# Configuration constants
|
||||
CONF_MODEL: Final = "model"
|
||||
@@ -12,16 +35,21 @@ CONF_TEMPERATURE: Final = "temperature"
|
||||
CONF_MAX_TOKENS: Final = "max_tokens"
|
||||
CONF_API_ENDPOINT: Final = "api_endpoint"
|
||||
CONF_REQUEST_INTERVAL: Final = "request_interval"
|
||||
CONF_INSTANCE: Final = "instance"
|
||||
CONF_MAX_HISTORY_SIZE: Final = "max_history_size" # Correct constant name
|
||||
CONF_IS_ANTHROPIC: Final = "is_anthropic"
|
||||
CONF_CONTEXT_MESSAGES: Final = "context_messages"
|
||||
|
||||
# Default values
|
||||
DEFAULT_MODEL: Final = "gpt-3.5-turbo"
|
||||
DEFAULT_TEMPERATURE: Final = 0.7
|
||||
DEFAULT_MODEL: Final = "gpt-4o-mini"
|
||||
DEFAULT_TEMPERATURE: Final = 0.1
|
||||
DEFAULT_MAX_TOKENS: Final = 1000
|
||||
DEFAULT_API_ENDPOINT: Final = "https://api.openai.com/v1"
|
||||
DEFAULT_REQUEST_INTERVAL: Final = 1.0
|
||||
DEFAULT_TIMEOUT: Final = 30
|
||||
DEFAULT_QUEUE_SIZE: Final = 100
|
||||
DEFAULT_HISTORY_LIMIT: Final = 50
|
||||
DEFAULT_MAX_HISTORY: Final = 50
|
||||
DEFAULT_NAME: Final = "HA Text AI"
|
||||
DEFAULT_NAME_PREFIX = "ha_text_ai"
|
||||
DEFAULT_CONTEXT_MESSAGES: Final = 5
|
||||
|
||||
# Parameter constraints
|
||||
MIN_TEMPERATURE: Final = 0.0
|
||||
@@ -29,8 +57,11 @@ MAX_TEMPERATURE: Final = 2.0
|
||||
MIN_MAX_TOKENS: Final = 1
|
||||
MAX_MAX_TOKENS: Final = 4096
|
||||
MIN_REQUEST_INTERVAL: Final = 0.1
|
||||
MIN_TIMEOUT: Final = 5
|
||||
MAX_TIMEOUT: Final = 120
|
||||
MAX_REQUEST_INTERVAL: Final = 60.0
|
||||
|
||||
# API constants
|
||||
API_TIMEOUT: Final = 30
|
||||
API_RETRY_COUNT: Final = 3
|
||||
|
||||
# Service names
|
||||
SERVICE_ASK_QUESTION: Final = "ask_question"
|
||||
@@ -38,26 +69,48 @@ SERVICE_CLEAR_HISTORY: Final = "clear_history"
|
||||
SERVICE_GET_HISTORY: Final = "get_history"
|
||||
SERVICE_SET_SYSTEM_PROMPT: Final = "set_system_prompt"
|
||||
|
||||
# Service descriptions
|
||||
SERVICE_ASK_QUESTION_DESCRIPTION: Final = "Ask a question to the AI model"
|
||||
SERVICE_CLEAR_HISTORY_DESCRIPTION: Final = "Clear conversation history"
|
||||
SERVICE_GET_HISTORY_DESCRIPTION: Final = "Get conversation history"
|
||||
SERVICE_SET_SYSTEM_PROMPT_DESCRIPTION: Final = "Set system prompt for AI model"
|
||||
|
||||
# Attribute keys
|
||||
ATTR_QUESTION: Final = "question"
|
||||
ATTR_RESPONSE: Final = "response"
|
||||
ATTR_LAST_UPDATED: Final = "last_updated"
|
||||
ATTR_INSTANCE: Final = "instance"
|
||||
ATTR_MODEL: Final = "model"
|
||||
ATTR_TEMPERATURE: Final = "temperature"
|
||||
ATTR_MAX_TOKENS: Final = "max_tokens"
|
||||
ATTR_TOTAL_RESPONSES: Final = "total_responses"
|
||||
ATTR_SYSTEM_PROMPT: Final = "system_prompt"
|
||||
ATTR_RESPONSE_TIME: Final = "response_time"
|
||||
ATTR_QUEUE_SIZE: Final = "queue_size"
|
||||
ATTR_API_STATUS: Final = "api_status"
|
||||
ATTR_ERROR_COUNT: Final = "error_count"
|
||||
ATTR_CONVERSATION_HISTORY: Final = "conversation_history"
|
||||
|
||||
# Sensor attributes
|
||||
ATTR_TOTAL_RESPONSES: Final = "total_responses"
|
||||
ATTR_TOTAL_ERRORS: Final = "total_errors"
|
||||
ATTR_AVG_RESPONSE_TIME: Final = "average_response_time"
|
||||
ATTR_LAST_REQUEST_TIME: Final = "last_request_time"
|
||||
ATTR_LAST_ERROR: Final = "last_error"
|
||||
ATTR_IS_PROCESSING: Final = "is_processing"
|
||||
ATTR_IS_RATE_LIMITED: Final = "is_rate_limited"
|
||||
ATTR_IS_MAINTENANCE: Final = "is_maintenance"
|
||||
ATTR_API_VERSION: Final = "api_version"
|
||||
ATTR_ENDPOINT_STATUS: Final = "endpoint_status"
|
||||
ATTR_PERFORMANCE_METRICS: Final = "performance_metrics"
|
||||
ATTR_HISTORY_SIZE: Final = "history_size"
|
||||
ATTR_UPTIME: Final = "uptime"
|
||||
ATTR_API_PROVIDER: Final = "api_provider"
|
||||
ATTR_METRICS: Final = "metrics"
|
||||
ATTR_STATE: Final = "state"
|
||||
ATTR_LAST_RESPONSE: Final = "last_response"
|
||||
ATTR_ERROR: Final = "error"
|
||||
ATTR_TIMESTAMP: Final = "timestamp"
|
||||
|
||||
# Sensor metrics
|
||||
METRIC_TOTAL_TOKENS: Final = "total_tokens"
|
||||
METRIC_PROMPT_TOKENS: Final = "prompt_tokens"
|
||||
METRIC_COMPLETION_TOKENS: Final = "completion_tokens"
|
||||
METRIC_SUCCESSFUL_REQUESTS: Final = "successful_requests"
|
||||
METRIC_FAILED_REQUESTS: Final = "failed_requests"
|
||||
METRIC_AVERAGE_LATENCY: Final = "average_latency"
|
||||
METRIC_MAX_LATENCY: Final = "max_latency"
|
||||
METRIC_MIN_LATENCY: Final = "min_latency"
|
||||
|
||||
# Error messages
|
||||
ERROR_INVALID_API_KEY: Final = "invalid_api_key"
|
||||
@@ -68,74 +121,89 @@ ERROR_RATE_LIMIT: Final = "rate_limit_exceeded"
|
||||
ERROR_CONTEXT_LENGTH: Final = "context_length_exceeded"
|
||||
ERROR_API_ERROR: Final = "api_error"
|
||||
ERROR_TIMEOUT: Final = "timeout_error"
|
||||
ERROR_QUEUE_FULL: Final = "queue_full"
|
||||
ERROR_INVALID_PROMPT: Final = "invalid_prompt"
|
||||
|
||||
# Configuration descriptions
|
||||
CONF_MODEL_DESCRIPTION: Final = "AI model to use for responses"
|
||||
CONF_TEMPERATURE_DESCRIPTION: Final = "Temperature for response generation (0-2)"
|
||||
CONF_MAX_TOKENS_DESCRIPTION: Final = "Maximum tokens in response (1-4096)"
|
||||
CONF_API_ENDPOINT_DESCRIPTION: Final = "API endpoint URL"
|
||||
CONF_REQUEST_INTERVAL_DESCRIPTION: Final = "Minimum time between API requests (seconds)"
|
||||
|
||||
# Entity attributes descriptions
|
||||
ATTR_QUESTION_DESCRIPTION: Final = "Last question asked"
|
||||
ATTR_RESPONSE_DESCRIPTION: Final = "Last response received"
|
||||
ATTR_LAST_UPDATED_DESCRIPTION: Final = "Time of last update"
|
||||
ATTR_MODEL_DESCRIPTION: Final = "Current AI model in use"
|
||||
ATTR_TEMPERATURE_DESCRIPTION: Final = "Current temperature setting"
|
||||
ATTR_MAX_TOKENS_DESCRIPTION: Final = "Current max tokens setting"
|
||||
ATTR_TOTAL_RESPONSES_DESCRIPTION: Final = "Total number of responses"
|
||||
ATTR_SYSTEM_PROMPT_DESCRIPTION: Final = "Current system prompt"
|
||||
ATTR_RESPONSE_TIME_DESCRIPTION: Final = "Time taken for last response"
|
||||
ATTR_QUEUE_SIZE_DESCRIPTION: Final = "Current size of question queue"
|
||||
ATTR_API_STATUS_DESCRIPTION: Final = "Current API connection status"
|
||||
ATTR_ERROR_COUNT_DESCRIPTION: Final = "Total number of errors"
|
||||
ATTR_LAST_ERROR_DESCRIPTION: Final = "Last error message"
|
||||
ERROR_INVALID_INSTANCE: Final = "invalid_instance"
|
||||
ERROR_NAME_EXISTS: Final = "name_exists"
|
||||
|
||||
# Entity attributes
|
||||
ENTITY_NAME: Final = "HA Text AI"
|
||||
ENTITY_ICON: Final = "mdi:robot"
|
||||
ENTITY_ICON_ERROR: Final = "mdi:robot-dead"
|
||||
ENTITY_ICON_PROCESSING: Final = "mdi:robot-excited"
|
||||
|
||||
# Translation keys
|
||||
TRANSLATION_KEY_CONFIG: Final = "config"
|
||||
TRANSLATION_KEY_OPTIONS: Final = "options"
|
||||
TRANSLATION_KEY_ERROR: Final = "error"
|
||||
TRANSLATION_KEY_STATE: Final = "state"
|
||||
TRANSLATION_KEY_SERVICES: Final = "services"
|
||||
|
||||
# State attributes
|
||||
STATE_READY: Final = "ready"
|
||||
STATE_PROCESSING: Final = "processing"
|
||||
STATE_ERROR: Final = "error"
|
||||
STATE_DISCONNECTED: Final = "disconnected"
|
||||
STATE_RATE_LIMITED: Final = "rate_limited"
|
||||
STATE_INITIALIZING: Final = "initializing"
|
||||
|
||||
# Logging
|
||||
LOGGER_NAME: Final = "custom_components.ha_text_ai"
|
||||
LOG_LEVEL_DEFAULT: Final = "INFO"
|
||||
|
||||
# Queue constants
|
||||
QUEUE_TIMEOUT: Final = 5
|
||||
QUEUE_MAX_SIZE: Final = 100
|
||||
|
||||
# API constants
|
||||
API_TIMEOUT: Final = 30
|
||||
API_RETRY_COUNT: Final = 3
|
||||
API_BACKOFF_FACTOR: Final = 1.5
|
||||
|
||||
# Service schema constants
|
||||
SCHEMA_QUESTION: Final = "question"
|
||||
SCHEMA_MODEL: Final = "model"
|
||||
SCHEMA_TEMPERATURE: Final = "temperature"
|
||||
SCHEMA_MAX_TOKENS: Final = "max_tokens"
|
||||
SCHEMA_PROMPT: Final = "prompt"
|
||||
SCHEMA_LIMIT: Final = "limit"
|
||||
STATE_MAINTENANCE: Final = "maintenance"
|
||||
STATE_RATE_LIMITED: Final = "rate_limited"
|
||||
STATE_DISCONNECTED: Final = "disconnected"
|
||||
|
||||
# Event names
|
||||
EVENT_RESPONSE_RECEIVED: Final = f"{DOMAIN}_response_received"
|
||||
EVENT_ERROR_OCCURRED: Final = f"{DOMAIN}_error_occurred"
|
||||
EVENT_STATE_CHANGED: Final = f"{DOMAIN}_state_changed"
|
||||
|
||||
# Service schema constants
|
||||
SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
|
||||
vol.Required(CONF_INSTANCE): cv.string,
|
||||
vol.Required("question"): cv.string,
|
||||
vol.Optional("system_prompt"): cv.string,
|
||||
vol.Optional("model"): cv.string,
|
||||
vol.Optional("temperature"): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
||||
),
|
||||
vol.Optional("max_tokens"): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
|
||||
),
|
||||
vol.Optional("context_messages"): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=20)
|
||||
)
|
||||
})
|
||||
|
||||
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
|
||||
vol.Required(CONF_INSTANCE): cv.string,
|
||||
vol.Required("prompt"): cv.string
|
||||
})
|
||||
|
||||
SERVICE_SCHEMA_GET_HISTORY = vol.Schema({
|
||||
vol.Required(CONF_INSTANCE): cv.string,
|
||||
vol.Optional("limit", default=10): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=100),
|
||||
),
|
||||
vol.Optional("filter_model"): cv.string
|
||||
})
|
||||
|
||||
# Configuration schema
|
||||
CONFIG_SCHEMA = vol.Schema({
|
||||
DOMAIN: vol.Schema({
|
||||
vol.Required(CONF_NAME): cv.string,
|
||||
vol.Required(CONF_API_KEY): cv.string,
|
||||
vol.Required(CONF_API_PROVIDER): vol.In(API_PROVIDERS),
|
||||
vol.Optional(CONF_MODEL, default=DEFAULT_MODEL): cv.string,
|
||||
vol.Optional(CONF_TEMPERATURE, default=DEFAULT_TEMPERATURE): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
||||
),
|
||||
vol.Optional(CONF_MAX_TOKENS, default=DEFAULT_MAX_TOKENS): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
|
||||
),
|
||||
vol.Optional(CONF_API_ENDPOINT): cv.string,
|
||||
vol.Optional(CONF_REQUEST_INTERVAL, default=DEFAULT_REQUEST_INTERVAL): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_REQUEST_INTERVAL, max=MAX_REQUEST_INTERVAL)
|
||||
),
|
||||
vol.Optional(CONF_MAX_HISTORY_SIZE, default=DEFAULT_MAX_HISTORY): vol.All( # Correct usage
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=100),
|
||||
),
|
||||
vol.Optional(CONF_CONTEXT_MESSAGES, default=DEFAULT_CONTEXT_MESSAGES): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=20)
|
||||
)
|
||||
})
|
||||
}, extra=vol.ALLOW_EXTRA)
|
||||
|
||||
@@ -1,194 +1,562 @@
|
||||
"""Data coordinator for HA text AI."""
|
||||
import asyncio
|
||||
"""
|
||||
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
|
||||
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
from typing import Any, Dict, Optional
|
||||
import traceback
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from openai import AsyncOpenAI, APIError, AuthenticationError, RateLimitError
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
|
||||
import async_timeout
|
||||
from homeassistant.util import dt as dt_util
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.const import CONF_NAME
|
||||
from .config_flow import normalize_name
|
||||
|
||||
from .const import DOMAIN
|
||||
from .const import (
|
||||
DOMAIN,
|
||||
STATE_READY,
|
||||
STATE_PROCESSING,
|
||||
STATE_ERROR,
|
||||
STATE_RATE_LIMITED,
|
||||
STATE_MAINTENANCE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
DEFAULT_TEMPERATURE,
|
||||
DEFAULT_MAX_HISTORY,
|
||||
DEFAULT_CONTEXT_MESSAGES,
|
||||
DEFAULT_NAME_PREFIX,
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class HATextAICoordinator(DataUpdateCoordinator):
|
||||
"""Class to manage fetching data from the API."""
|
||||
"""The HA Text AI coordinator."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
api_key: str,
|
||||
endpoint: str,
|
||||
client: Any,
|
||||
model: str,
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
request_interval: float,
|
||||
session: Optional[Any] = None,
|
||||
update_interval: int,
|
||||
instance_name: str,
|
||||
max_tokens: int = DEFAULT_MAX_TOKENS,
|
||||
temperature: float = DEFAULT_TEMPERATURE,
|
||||
max_history_size: int = DEFAULT_MAX_HISTORY,
|
||||
context_messages: int = DEFAULT_CONTEXT_MESSAGES,
|
||||
is_anthropic: bool = False,
|
||||
) -> None:
|
||||
"""Initialize."""
|
||||
"""Initialize coordinator."""
|
||||
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.client = client
|
||||
self.model = model
|
||||
self.temperature = temperature
|
||||
self.max_tokens = max_tokens
|
||||
self.max_history_size = max_history_size
|
||||
self.is_anthropic = is_anthropic
|
||||
|
||||
# Initialize with default state
|
||||
self._initial_state = {
|
||||
"state": STATE_READY,
|
||||
"metrics": {
|
||||
"total_tokens": 0,
|
||||
"prompt_tokens": 0,
|
||||
"completion_tokens": 0,
|
||||
"successful_requests": 0,
|
||||
"failed_requests": 0,
|
||||
"total_errors": 0,
|
||||
"average_latency": 0,
|
||||
"max_latency": 0,
|
||||
"min_latency": float("inf"),
|
||||
},
|
||||
"last_response": {
|
||||
"timestamp": dt_util.utcnow().isoformat(),
|
||||
"question": "",
|
||||
"response": "",
|
||||
"model": model,
|
||||
"instance": instance_name,
|
||||
"normalized_name": self.normalized_name,
|
||||
"error": None,
|
||||
},
|
||||
"is_processing": False,
|
||||
"is_rate_limited": False,
|
||||
"is_maintenance": False,
|
||||
"endpoint_status": "ready",
|
||||
"uptime": 0,
|
||||
"system_prompt": None,
|
||||
"history_size": 0,
|
||||
"conversation_history": [],
|
||||
}
|
||||
|
||||
update_interval_td = timedelta(seconds=update_interval)
|
||||
|
||||
super().__init__(
|
||||
hass,
|
||||
_LOGGER,
|
||||
name=DOMAIN,
|
||||
update_interval=timedelta(seconds=request_interval),
|
||||
name=instance_name,
|
||||
update_interval=update_interval_td,
|
||||
)
|
||||
|
||||
self._validate_params(api_key, temperature, max_tokens)
|
||||
# Register instance
|
||||
self.hass.data.setdefault(DOMAIN, {})
|
||||
self.hass.data[DOMAIN][instance_name] = self
|
||||
self.context_messages = context_messages
|
||||
|
||||
self.api_key = api_key
|
||||
self.endpoint = endpoint
|
||||
self.model = model
|
||||
self.temperature = float(temperature)
|
||||
self.max_tokens = int(max_tokens)
|
||||
self._question_queue = asyncio.Queue()
|
||||
self._responses: Dict[str, Any] = {}
|
||||
self.system_prompt: Optional[str] = None
|
||||
self._is_ready = False
|
||||
self._error_count = 0
|
||||
self._MAX_ERRORS = 3
|
||||
self._system_prompt = None
|
||||
self._conversation_history = []
|
||||
self._performance_metrics = self._initial_state["metrics"].copy()
|
||||
self._is_processing = False
|
||||
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()
|
||||
|
||||
self.client = AsyncOpenAI(
|
||||
api_key=self.api_key,
|
||||
base_url=self.endpoint,
|
||||
http_client=session,
|
||||
_LOGGER.info(
|
||||
f"Initialized HA Text AI coordinator with instance: {instance_name}"
|
||||
)
|
||||
|
||||
def _validate_params(self, api_key: str, temperature: float, max_tokens: int) -> None:
|
||||
"""Validate initialization parameters."""
|
||||
if not api_key:
|
||||
raise ValueError("API key is required")
|
||||
if not isinstance(temperature, (int, float)) or not 0 <= temperature <= 2:
|
||||
raise ValueError("Temperature must be between 0 and 2")
|
||||
if not isinstance(max_tokens, int) or max_tokens < 1:
|
||||
raise ValueError("Max tokens must be a positive integer")
|
||||
|
||||
async def _async_update_data(self) -> Dict[str, Any]:
|
||||
"""Update data via OpenAI API."""
|
||||
if self._question_queue.empty():
|
||||
return self._responses
|
||||
|
||||
"""Update data via library."""
|
||||
try:
|
||||
async with async_timeout.timeout(30):
|
||||
question = await self._question_queue.get()
|
||||
try:
|
||||
response_content = await self._make_api_call(question)
|
||||
self._responses[question] = {
|
||||
"question": question,
|
||||
"response": response_content,
|
||||
"error": None,
|
||||
"timestamp": self.hass.loop.time()
|
||||
}
|
||||
self._error_count = 0
|
||||
self._is_ready = True
|
||||
_LOGGER.debug("Response received for question: %s", question)
|
||||
|
||||
except Exception as err:
|
||||
self._handle_api_error(question, err)
|
||||
finally:
|
||||
self._question_queue.task_done()
|
||||
|
||||
return self._responses
|
||||
|
||||
except asyncio.TimeoutError as err:
|
||||
_LOGGER.error("Timeout while processing question")
|
||||
await self._handle_timeout_error()
|
||||
return self._responses
|
||||
|
||||
def _handle_api_error(self, question: str, error: Exception) -> None:
|
||||
"""Handle API errors."""
|
||||
self._error_count += 1
|
||||
error_msg = str(error)
|
||||
|
||||
if isinstance(error, AuthenticationError):
|
||||
error_msg = "Authentication failed - invalid API key"
|
||||
self._is_ready = False
|
||||
elif isinstance(error, RateLimitError):
|
||||
error_msg = "Rate limit exceeded"
|
||||
elif isinstance(error, APIError):
|
||||
error_msg = f"API error: {error}"
|
||||
|
||||
self._responses[question] = {
|
||||
"question": question,
|
||||
"response": None,
|
||||
"error": error_msg,
|
||||
"timestamp": self.hass.loop.time()
|
||||
}
|
||||
|
||||
_LOGGER.error("API error (%s): %s", type(error).__name__, error_msg)
|
||||
|
||||
if self._error_count >= self._MAX_ERRORS:
|
||||
_LOGGER.warning(
|
||||
"Multiple errors occurred (%d). Coordinator needs attention.",
|
||||
self._error_count
|
||||
current_state = self._get_current_state()
|
||||
_LOGGER.debug(
|
||||
f"Updating data for {self.instance_name}, current state: {current_state}"
|
||||
)
|
||||
|
||||
async def _handle_timeout_error(self) -> None:
|
||||
"""Handle timeout errors."""
|
||||
self._error_count += 1
|
||||
if not self._question_queue.empty():
|
||||
try:
|
||||
# Clear the queue if we have timeout issues
|
||||
while not self._question_queue.empty():
|
||||
self._question_queue.get_nowait()
|
||||
self._question_queue.task_done()
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error clearing question queue: %s", err)
|
||||
data = {
|
||||
"state": current_state,
|
||||
"metrics": self._performance_metrics,
|
||||
"last_response": self.last_response,
|
||||
"is_processing": self._is_processing,
|
||||
"is_rate_limited": self._is_rate_limited,
|
||||
"is_maintenance": self._is_maintenance,
|
||||
"endpoint_status": self.endpoint_status,
|
||||
"uptime": (dt_util.utcnow() - self._start_time).total_seconds(),
|
||||
"system_prompt": self._system_prompt,
|
||||
"history_size": len(self._conversation_history),
|
||||
"conversation_history": self._conversation_history,
|
||||
"normalized_name": self.normalized_name,
|
||||
}
|
||||
|
||||
async def _make_api_call(self, question: str) -> str:
|
||||
"""Make API call to OpenAI."""
|
||||
try:
|
||||
messages = []
|
||||
if self.system_prompt:
|
||||
messages.append({"role": "system", "content": self.system_prompt})
|
||||
messages.append({"role": "user", "content": question})
|
||||
# Validate data
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("Invalid data format")
|
||||
|
||||
completion = await self.client.chat.completions.create(
|
||||
model=self.model,
|
||||
messages=messages,
|
||||
temperature=self.temperature,
|
||||
max_tokens=self.max_tokens,
|
||||
)
|
||||
return completion.choices[0].message.content
|
||||
_LOGGER.debug(f"Updated data for {self.instance_name}: {data}")
|
||||
return data
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error in API call: %s", err)
|
||||
_LOGGER.error(f"Error updating data for {self.instance_name}: {err}")
|
||||
return self._initial_state
|
||||
|
||||
async def async_update_ha_state(self) -> None:
|
||||
"""Update Home Assistant state."""
|
||||
try:
|
||||
_LOGGER.debug(
|
||||
f"Requesting state update for {self.instance_name} (normalized: {self.normalized_name})"
|
||||
)
|
||||
await self.async_request_refresh()
|
||||
|
||||
# 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():
|
||||
if entity_id.startswith(entity_id_base):
|
||||
self.hass.states.async_set(entity_id, self._get_current_state())
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.error(f"Error updating HA state for {self.instance_name}: {err}")
|
||||
|
||||
def _get_current_state(self) -> str:
|
||||
"""Get current state based on internal flags."""
|
||||
if self._is_processing:
|
||||
return STATE_PROCESSING
|
||||
elif self._is_rate_limited:
|
||||
return STATE_RATE_LIMITED
|
||||
elif self._is_maintenance:
|
||||
return STATE_MAINTENANCE
|
||||
elif self.last_response.get("error"):
|
||||
return STATE_ERROR
|
||||
return STATE_READY
|
||||
|
||||
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:
|
||||
# Anthropic specific token counting
|
||||
if self.is_anthropic and hasattr(self.client, 'count_tokens'):
|
||||
return sum(self.client.count_tokens(msg['content']) 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:
|
||||
# Safe fallback with detailed logging
|
||||
_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(
|
||||
self,
|
||||
question: str,
|
||||
model: Optional[str] = None,
|
||||
temperature: Optional[float] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
system_prompt: Optional[str] = None,
|
||||
context_messages: Optional[int] = None,
|
||||
) -> dict:
|
||||
"""
|
||||
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(
|
||||
question, model, temperature, max_tokens, system_prompt, context_messages
|
||||
)
|
||||
|
||||
async def async_process_question(
|
||||
self,
|
||||
question: str,
|
||||
model: Optional[str] = None,
|
||||
temperature: Optional[float] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
system_prompt: Optional[str] = None,
|
||||
context_messages: Optional[int] = None,
|
||||
) -> dict:
|
||||
"""
|
||||
Enhanced question processing with intelligent token management.
|
||||
"""
|
||||
try:
|
||||
self._is_processing = True
|
||||
await self.async_update_ha_state()
|
||||
|
||||
temp_context_messages = context_messages or self.context_messages
|
||||
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 timing
|
||||
start_time = dt_util.utcnow()
|
||||
|
||||
# Prepare messages with system prompt
|
||||
messages = []
|
||||
if temp_system_prompt:
|
||||
messages.append({"role": "system", "content": temp_system_prompt})
|
||||
|
||||
# Context history management
|
||||
context_history = self._conversation_history[-temp_context_messages:]
|
||||
|
||||
# Comprehensive token calculation
|
||||
context_tokens = self._calculate_context_tokens(
|
||||
[{"content": entry["question"]} for entry in context_history] +
|
||||
[{"content": entry["response"]} for entry in context_history] +
|
||||
[{"content": question}],
|
||||
temp_model
|
||||
)
|
||||
|
||||
# Dynamic token allocation
|
||||
available_tokens = max(0, temp_max_tokens - context_tokens)
|
||||
|
||||
# Context trimming if over token limit
|
||||
if context_tokens > temp_max_tokens:
|
||||
_LOGGER.warning(
|
||||
f"Token limit exceeded. "
|
||||
f"Context: {context_tokens}, "
|
||||
f"Max: {temp_max_tokens}"
|
||||
)
|
||||
|
||||
# Intelligent context reduction
|
||||
while context_tokens > temp_max_tokens // 2 and context_history:
|
||||
context_history.pop(0)
|
||||
context_tokens = self._calculate_context_tokens(
|
||||
[{"content": entry["question"]} for entry in context_history] +
|
||||
[{"content": entry["response"]} for entry in context_history] +
|
||||
[{"content": question}],
|
||||
temp_model
|
||||
)
|
||||
|
||||
# Rebuild messages with trimmed context
|
||||
for entry in context_history:
|
||||
messages.append({"role": "user", "content": entry["question"]})
|
||||
messages.append({"role": "assistant", "content": entry["response"]})
|
||||
|
||||
messages.append({"role": "user", "content": question})
|
||||
|
||||
# Detailed token logging
|
||||
_LOGGER.debug(
|
||||
f"Token Analysis: "
|
||||
f"Context Tokens: {context_tokens}, "
|
||||
f"Max Tokens: {temp_max_tokens}, "
|
||||
f"Available Tokens: {available_tokens}"
|
||||
)
|
||||
|
||||
# Prepare API call with dynamic token management
|
||||
kwargs = {
|
||||
"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)
|
||||
|
||||
# Update history
|
||||
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:
|
||||
"""Process message using the AI client."""
|
||||
try:
|
||||
if self.is_anthropic:
|
||||
response = await self._process_anthropic_message(question, **kwargs)
|
||||
else:
|
||||
response = await self._process_openai_message(question, **kwargs)
|
||||
|
||||
self.last_response = {
|
||||
"timestamp": dt_util.utcnow().isoformat(),
|
||||
"question": question,
|
||||
"response": response["content"],
|
||||
"model": kwargs.get("model", self.model),
|
||||
"instance": self.instance_name,
|
||||
"error": None,
|
||||
}
|
||||
|
||||
return response
|
||||
|
||||
except Exception as err:
|
||||
self._handle_error(err)
|
||||
raise
|
||||
|
||||
async def async_ask_question(self, question: str) -> None:
|
||||
"""Add question to queue."""
|
||||
if not self._is_ready and self._error_count >= self._MAX_ERRORS:
|
||||
_LOGGER.warning("Coordinator is not ready due to previous errors")
|
||||
return
|
||||
async def _process_anthropic_message(self, question: str, **kwargs) -> dict:
|
||||
"""Process message using Anthropic API."""
|
||||
try:
|
||||
_LOGGER.debug(f"Anthropic API call: model={kwargs['model']}, max_tokens={kwargs['max_tokens']}")
|
||||
response = await self.client.messages.create(
|
||||
model=kwargs["model"],
|
||||
max_tokens=kwargs["max_tokens"],
|
||||
messages=kwargs["messages"],
|
||||
temperature=kwargs["temperature"],
|
||||
)
|
||||
_LOGGER.debug(f"Anthropic response: tokens={response.usage}")
|
||||
return {
|
||||
"content": response.content[0].text,
|
||||
"tokens": {
|
||||
"prompt": response.usage.input_tokens,
|
||||
"completion": response.usage.output_tokens,
|
||||
"total": response.usage.input_tokens + response.usage.output_tokens,
|
||||
},
|
||||
}
|
||||
except Exception as e:
|
||||
_LOGGER.error(f"Anthropic API error: {str(e)}")
|
||||
raise
|
||||
|
||||
await self._question_queue.put(question)
|
||||
await self.async_refresh()
|
||||
async def _process_openai_message(self, question: str, **kwargs) -> dict:
|
||||
"""Process message using OpenAI API."""
|
||||
try:
|
||||
response = await self.client.create(
|
||||
model=kwargs["model"],
|
||||
messages=kwargs["messages"],
|
||||
temperature=kwargs["temperature"],
|
||||
max_tokens=kwargs["max_tokens"],
|
||||
)
|
||||
|
||||
return {
|
||||
"content": response["choices"][0]["message"]["content"],
|
||||
"tokens": {
|
||||
"prompt": response["usage"]["prompt_tokens"],
|
||||
"completion": response["usage"]["completion_tokens"],
|
||||
"total": response["usage"]["total_tokens"],
|
||||
},
|
||||
}
|
||||
except Exception as e:
|
||||
_LOGGER.error(f"Error in OpenAI API call: {str(e)}")
|
||||
raise
|
||||
|
||||
def _update_metrics(self, latency: float, response: dict) -> None:
|
||||
"""Update performance metrics."""
|
||||
metrics = self._performance_metrics
|
||||
tokens = response.get("tokens", {})
|
||||
|
||||
metrics["total_tokens"] += tokens.get("total", 0)
|
||||
metrics["prompt_tokens"] += tokens.get("prompt", 0)
|
||||
metrics["completion_tokens"] += tokens.get("completion", 0)
|
||||
metrics["successful_requests"] += 1
|
||||
|
||||
metrics["average_latency"] = (
|
||||
(metrics["average_latency"] * (metrics["successful_requests"] - 1) + latency)
|
||||
/ metrics["successful_requests"]
|
||||
)
|
||||
metrics["max_latency"] = max(metrics["max_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:
|
||||
"""
|
||||
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["failed_requests"] += 1
|
||||
|
||||
error_details = {
|
||||
"timestamp": dt_util.utcnow().isoformat(),
|
||||
"model": self.model,
|
||||
"instance": self.instance_name,
|
||||
"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:
|
||||
"""Clear conversation history."""
|
||||
self._conversation_history = []
|
||||
await self.async_update_ha_state()
|
||||
|
||||
async def async_get_history(self) -> List[Dict[str, str]]:
|
||||
"""Get conversation history."""
|
||||
return self._conversation_history
|
||||
|
||||
async def async_set_system_prompt(self, prompt: str) -> None:
|
||||
"""Set system prompt."""
|
||||
self._system_prompt = prompt
|
||||
await self.async_update_ha_state()
|
||||
|
||||
async def async_shutdown(self) -> None:
|
||||
"""Shutdown the coordinator."""
|
||||
try:
|
||||
# Clear the queue
|
||||
while not self._question_queue.empty():
|
||||
self._question_queue.get_nowait()
|
||||
self._question_queue.task_done()
|
||||
|
||||
await self.client.close()
|
||||
self._is_ready = False
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error during shutdown: %s", err)
|
||||
|
||||
@property
|
||||
def is_ready(self) -> bool:
|
||||
"""Return if coordinator is ready."""
|
||||
return self._is_ready
|
||||
|
||||
@property
|
||||
def error_count(self) -> int:
|
||||
"""Return current error count."""
|
||||
return self._error_count
|
||||
|
||||
def reset_error_count(self) -> None:
|
||||
"""Reset error counter."""
|
||||
self._error_count = 0
|
||||
"""Shutdown coordinator."""
|
||||
_LOGGER.debug(f"Shutting down coordinator for {self.instance_name}")
|
||||
self.hass.data[DOMAIN].pop(self.instance_name, None)
|
||||
|
||||
|
After Width: | Height: | Size: 16 KiB |
|
After Width: | Height: | Size: 45 KiB |
|
After Width: | Height: | Size: 12 KiB |
|
After Width: | Height: | Size: 34 KiB |
@@ -1,14 +1,28 @@
|
||||
{
|
||||
"domain": "ha_text_ai",
|
||||
"name": "HA Text AI",
|
||||
"after_dependencies": ["http"],
|
||||
"bluetooth": [],
|
||||
"codeowners": ["@smkrv"],
|
||||
"config_flow": true,
|
||||
"dependencies": [],
|
||||
"documentation": "https://github.com/smkrv/ha-text-ai/wiki",
|
||||
"documentation": "https://github.com/smkrv/ha-text-ai",
|
||||
"integration_type": "service",
|
||||
"iot_class": "cloud_polling",
|
||||
"issue_tracker": "https://github.com/smkrv/ha-text-ai/issues",
|
||||
"requirements": ["openai>=1.0.0"],
|
||||
"loggers": ["custom_components.ha_text_ai"],
|
||||
"mqtt": [],
|
||||
"quality_scale": "silver",
|
||||
"requirements": [
|
||||
"openai>=1.12.0",
|
||||
"anthropic>=0.8.0",
|
||||
"aiohttp>=3.8.0",
|
||||
"async-timeout>=4.0.0",
|
||||
"certifi>=2024.2.2"
|
||||
],
|
||||
"single_config_entry": false,
|
||||
"ssdp": [],
|
||||
"version": "1.0.8",
|
||||
"usb": [],
|
||||
"version": "2.0.4-beta",
|
||||
"zeroconf": []
|
||||
}
|
||||
|
||||
@@ -1,64 +1,108 @@
|
||||
"""Sensor platform for HA text AI."""
|
||||
from datetime import datetime
|
||||
"""
|
||||
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
|
||||
from typing import Any, Dict, Optional
|
||||
import math
|
||||
from typing import Any, Dict
|
||||
|
||||
from homeassistant.components.sensor import (
|
||||
SensorEntity,
|
||||
SensorStateClass,
|
||||
SensorDeviceClass,
|
||||
SensorEntityDescription,
|
||||
)
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.typing import StateType
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
from homeassistant.util import dt as dt_util
|
||||
from homeassistant.util import slugify
|
||||
|
||||
from .const import (
|
||||
DOMAIN,
|
||||
ATTR_QUESTION,
|
||||
ATTR_RESPONSE,
|
||||
ATTR_LAST_UPDATED,
|
||||
ATTR_MODEL,
|
||||
ATTR_TEMPERATURE,
|
||||
ATTR_MAX_TOKENS,
|
||||
CONF_MODEL,
|
||||
CONF_API_PROVIDER,
|
||||
ATTR_TOTAL_RESPONSES,
|
||||
ATTR_SYSTEM_PROMPT,
|
||||
ATTR_QUEUE_SIZE,
|
||||
ATTR_API_STATUS,
|
||||
ATTR_ERROR_COUNT,
|
||||
ATTR_TOTAL_ERRORS,
|
||||
ATTR_AVG_RESPONSE_TIME,
|
||||
ATTR_LAST_REQUEST_TIME,
|
||||
ATTR_LAST_ERROR,
|
||||
ATTR_RESPONSE_TIME,
|
||||
ENTITY_ICON,
|
||||
ENTITY_ICON_ERROR,
|
||||
ENTITY_ICON_PROCESSING,
|
||||
ATTR_IS_PROCESSING,
|
||||
ATTR_IS_RATE_LIMITED,
|
||||
ATTR_IS_MAINTENANCE,
|
||||
ATTR_API_VERSION,
|
||||
ATTR_ENDPOINT_STATUS,
|
||||
ATTR_PERFORMANCE_METRICS,
|
||||
ATTR_HISTORY_SIZE,
|
||||
ATTR_UPTIME,
|
||||
ATTR_API_PROVIDER,
|
||||
ATTR_MODEL,
|
||||
ATTR_SYSTEM_PROMPT,
|
||||
ATTR_API_STATUS,
|
||||
ATTR_RESPONSE,
|
||||
ATTR_QUESTION,
|
||||
ATTR_CONVERSATION_HISTORY,
|
||||
METRIC_TOTAL_TOKENS,
|
||||
METRIC_PROMPT_TOKENS,
|
||||
METRIC_COMPLETION_TOKENS,
|
||||
METRIC_SUCCESSFUL_REQUESTS,
|
||||
METRIC_FAILED_REQUESTS,
|
||||
METRIC_AVERAGE_LATENCY,
|
||||
METRIC_MAX_LATENCY,
|
||||
METRIC_MIN_LATENCY,
|
||||
STATE_READY,
|
||||
STATE_PROCESSING,
|
||||
STATE_ERROR,
|
||||
STATE_DISCONNECTED,
|
||||
STATE_RATE_LIMITED,
|
||||
STATE_INITIALIZING,
|
||||
STATE_MAINTENANCE,
|
||||
STATE_RATE_LIMITED,
|
||||
STATE_DISCONNECTED,
|
||||
ENTITY_ICON,
|
||||
ENTITY_ICON_ERROR,
|
||||
ENTITY_ICON_PROCESSING,
|
||||
DEFAULT_NAME_PREFIX,
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
)
|
||||
|
||||
from .coordinator import HATextAICoordinator
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
entry: ConfigEntry,
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up the HA text AI sensor."""
|
||||
coordinator = hass.data[DOMAIN][entry.entry_id]
|
||||
async_add_entities([HATextAISensor(coordinator, entry)], True)
|
||||
"""Set up the HA Text AI sensor."""
|
||||
_LOGGER.debug(f"Starting sensor setup for entry: {entry.entry_id}")
|
||||
|
||||
try:
|
||||
coordinator = hass.data[DOMAIN][entry.entry_id]
|
||||
_LOGGER.debug(f"Found coordinator for entry {entry.entry_id}")
|
||||
|
||||
instance_name = coordinator.instance_name
|
||||
_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):
|
||||
"""HA text AI Sensor."""
|
||||
"""HA Text AI Sensor."""
|
||||
|
||||
_attr_has_entity_name = True
|
||||
_attr_state_class = SensorStateClass.MEASUREMENT
|
||||
_attr_device_class = SensorDeviceClass.TIMESTAMP
|
||||
coordinator: HATextAICoordinator
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -66,116 +110,230 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||
config_entry: ConfigEntry,
|
||||
) -> None:
|
||||
"""Initialize the sensor."""
|
||||
_LOGGER.debug(f"Initializing sensor with config entry: {config_entry.data}")
|
||||
|
||||
super().__init__(coordinator)
|
||||
|
||||
self._config_entry = config_entry
|
||||
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._system_prompt = None
|
||||
|
||||
self._attr_name = f"HA Text AI {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_name = "Last Response"
|
||||
self._attr_suggested_display_precision = 0
|
||||
|
||||
_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(
|
||||
key=f"ha_text_ai_{self._normalized_name.lower()}",
|
||||
entity_registry_enabled_default=True,
|
||||
)
|
||||
|
||||
self._current_state = STATE_INITIALIZING
|
||||
self._error_count = 0
|
||||
self._last_error = None
|
||||
self._state = STATE_INITIALIZING
|
||||
self._last_update = None
|
||||
self._is_processing = False
|
||||
self._last_response = {}
|
||||
self._metrics = {}
|
||||
|
||||
@property
|
||||
def icon(self) -> str:
|
||||
"""Return the icon based on the current state."""
|
||||
if self._state == STATE_PROCESSING:
|
||||
return ENTITY_ICON_PROCESSING
|
||||
elif self._state in [STATE_ERROR, STATE_DISCONNECTED, STATE_RATE_LIMITED]:
|
||||
return ENTITY_ICON_ERROR
|
||||
return ENTITY_ICON
|
||||
model = config_entry.data.get(CONF_MODEL, "Unknown")
|
||||
api_provider = config_entry.data.get(CONF_API_PROVIDER, "Unknown")
|
||||
|
||||
@property
|
||||
def state(self) -> StateType:
|
||||
"""Return the state of the sensor."""
|
||||
if not self.coordinator.data or not self.coordinator.last_update_success_time:
|
||||
return None
|
||||
self._attr_device_info = DeviceInfo(
|
||||
identifiers={(DOMAIN, self._attr_unique_id)},
|
||||
name=self._attr_name,
|
||||
manufacturer="Community",
|
||||
model=f"{model} ({api_provider} provider)",
|
||||
sw_version="1.0.0",
|
||||
)
|
||||
|
||||
try:
|
||||
if isinstance(self.coordinator.last_update_success_time, datetime):
|
||||
return dt_util.as_local(self.coordinator.last_update_success_time)
|
||||
return self.coordinator.last_update_success_time
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error getting state: %s", err, exc_info=True)
|
||||
return None
|
||||
|
||||
@property
|
||||
def extra_state_attributes(self) -> Dict[str, Any]:
|
||||
"""Return entity specific state attributes."""
|
||||
attributes = {
|
||||
ATTR_TOTAL_RESPONSES: 0,
|
||||
ATTR_MODEL: self.coordinator.model,
|
||||
ATTR_TEMPERATURE: self.coordinator.temperature,
|
||||
ATTR_MAX_TOKENS: self.coordinator.max_tokens,
|
||||
ATTR_SYSTEM_PROMPT: self.coordinator.system_prompt,
|
||||
ATTR_QUEUE_SIZE: self.coordinator._question_queue.qsize(),
|
||||
ATTR_API_STATUS: self._state,
|
||||
ATTR_ERROR_COUNT: self._error_count,
|
||||
ATTR_LAST_ERROR: self._last_error,
|
||||
}
|
||||
|
||||
if not self.coordinator.data:
|
||||
return attributes
|
||||
|
||||
try:
|
||||
history = list(self.coordinator.data.items())
|
||||
if history:
|
||||
last_question, last_data = history[-1]
|
||||
|
||||
# Handle different response formats
|
||||
if isinstance(last_data, dict):
|
||||
last_response = last_data.get("response", "")
|
||||
last_updated = last_data.get("timestamp", self.coordinator.last_update_success_time)
|
||||
response_time = last_data.get("response_time")
|
||||
else:
|
||||
last_response = str(last_data)
|
||||
last_updated = self.coordinator.last_update_success_time
|
||||
response_time = None
|
||||
|
||||
# Convert timestamp to local time if needed
|
||||
if isinstance(last_updated, datetime):
|
||||
last_updated = dt_util.as_local(last_updated)
|
||||
|
||||
attributes.update({
|
||||
ATTR_QUESTION: last_question,
|
||||
ATTR_RESPONSE: last_response,
|
||||
ATTR_LAST_UPDATED: last_updated,
|
||||
ATTR_TOTAL_RESPONSES: len(history),
|
||||
})
|
||||
|
||||
if response_time is not None:
|
||||
attributes[ATTR_RESPONSE_TIME] = response_time
|
||||
|
||||
return attributes
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error getting attributes: %s", err, exc_info=True)
|
||||
self._error_count += 1
|
||||
self._last_error = str(err)
|
||||
self._state = STATE_ERROR
|
||||
return attributes
|
||||
_LOGGER.debug(
|
||||
f"Initialized sensor: {self.entity_id} for instance: {self._instance_name}"
|
||||
)
|
||||
|
||||
@property
|
||||
def available(self) -> bool:
|
||||
"""Return if entity is available."""
|
||||
return self.coordinator.last_update_success
|
||||
return (
|
||||
self.coordinator.last_update_success
|
||||
and self.coordinator.data is not None
|
||||
and self._current_state != STATE_DISCONNECTED
|
||||
)
|
||||
|
||||
def _sanitize_value(self, value: Any) -> Any:
|
||||
"""Sanitize values for JSON serialization."""
|
||||
if isinstance(value, float):
|
||||
if math.isinf(value) or math.isnan(value):
|
||||
return None
|
||||
return value
|
||||
|
||||
def _sanitize_attributes(self, attributes: Dict[str, Any]) -> Dict[str, Any]:
|
||||
"""Sanitize all attributes for JSON serialization."""
|
||||
return {
|
||||
key: self._sanitize_value(value)
|
||||
for key, value in attributes.items()
|
||||
if value is not None
|
||||
}
|
||||
|
||||
@property
|
||||
def native_value(self) -> StateType:
|
||||
"""Return the native value of the sensor."""
|
||||
if not self.coordinator.last_update_success or not self.coordinator.data:
|
||||
self._current_state = STATE_DISCONNECTED
|
||||
return self._current_state
|
||||
|
||||
status = self.coordinator.data.get("state", STATE_READY)
|
||||
self._current_state = status
|
||||
return status
|
||||
|
||||
@property
|
||||
def icon(self) -> str:
|
||||
"""Return the icon based on the current state."""
|
||||
if self._current_state == STATE_ERROR:
|
||||
return ENTITY_ICON_ERROR
|
||||
elif self._current_state == STATE_PROCESSING:
|
||||
return ENTITY_ICON_PROCESSING
|
||||
return ENTITY_ICON
|
||||
|
||||
@property
|
||||
def extra_state_attributes(self) -> Dict[str, Any]:
|
||||
"""Return entity specific state attributes."""
|
||||
if not self.coordinator.data:
|
||||
return {}
|
||||
|
||||
try:
|
||||
data = self.coordinator.data
|
||||
attributes = {
|
||||
ATTR_MODEL: self._config_entry.data.get(CONF_MODEL, "Unknown"),
|
||||
ATTR_API_PROVIDER: self._config_entry.data.get(
|
||||
CONF_API_PROVIDER, "Unknown"
|
||||
),
|
||||
ATTR_API_STATUS: self._current_state,
|
||||
ATTR_TOTAL_ERRORS: self._error_count,
|
||||
ATTR_LAST_ERROR: self._last_error,
|
||||
"instance_name": self._instance_name,
|
||||
"normalized_name": self._normalized_name,
|
||||
ATTR_SYSTEM_PROMPT: data.get("system_prompt"),
|
||||
ATTR_IS_PROCESSING: data.get("is_processing", False),
|
||||
ATTR_IS_RATE_LIMITED: data.get("is_rate_limited", False),
|
||||
ATTR_IS_MAINTENANCE: data.get("is_maintenance", False),
|
||||
ATTR_ENDPOINT_STATUS: data.get("endpoint_status", "unknown"),
|
||||
ATTR_UPTIME: data.get("uptime", 0),
|
||||
ATTR_HISTORY_SIZE: data.get("history_size", 0),
|
||||
ATTR_CONVERSATION_HISTORY: data.get("conversation_history", []),
|
||||
}
|
||||
|
||||
# Add metrics
|
||||
metrics = data.get("metrics", {})
|
||||
if isinstance(metrics, dict):
|
||||
self._metrics = metrics
|
||||
attributes.update(
|
||||
{
|
||||
METRIC_TOTAL_TOKENS: metrics.get("total_tokens", 0),
|
||||
METRIC_PROMPT_TOKENS: metrics.get("prompt_tokens", 0),
|
||||
METRIC_COMPLETION_TOKENS: metrics.get("completion_tokens", 0),
|
||||
METRIC_SUCCESSFUL_REQUESTS: metrics.get(
|
||||
"successful_requests", 0
|
||||
),
|
||||
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
|
||||
last_response = data.get("last_response", {})
|
||||
if isinstance(last_response, dict):
|
||||
self._last_response = last_response
|
||||
attributes.update(
|
||||
{
|
||||
ATTR_RESPONSE: last_response.get("response", ""),
|
||||
ATTR_QUESTION: last_response.get("question", ""),
|
||||
"last_model": last_response.get("model", ""),
|
||||
"last_timestamp": last_response.get("timestamp", ""),
|
||||
"last_error": last_response.get("error"),
|
||||
}
|
||||
)
|
||||
|
||||
# Add performance metrics if available
|
||||
if ATTR_PERFORMANCE_METRICS in data:
|
||||
attributes[ATTR_PERFORMANCE_METRICS] = data[
|
||||
ATTR_PERFORMANCE_METRICS
|
||||
]
|
||||
|
||||
# Add API version if available
|
||||
if ATTR_API_VERSION in data:
|
||||
attributes[ATTR_API_VERSION] = data[ATTR_API_VERSION]
|
||||
|
||||
return self._sanitize_attributes(attributes)
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error preparing attributes: %s", err, exc_info=True)
|
||||
return {}
|
||||
|
||||
async def async_added_to_hass(self) -> None:
|
||||
"""When entity is added to hass."""
|
||||
await super().async_added_to_hass()
|
||||
self._handle_coordinator_update()
|
||||
self._state = STATE_READY
|
||||
_LOGGER.debug(f"Entity {self.entity_id} added to Home Assistant")
|
||||
|
||||
def _handle_coordinator_update(self) -> None:
|
||||
"""Handle updated data from the coordinator."""
|
||||
try:
|
||||
if self.coordinator.data:
|
||||
self._state = STATE_READY
|
||||
data = self.coordinator.data
|
||||
if not self.coordinator.last_update_success or not data:
|
||||
self._current_state = STATE_DISCONNECTED
|
||||
_LOGGER.warning(f"No data available for {self.entity_id}")
|
||||
self.async_write_ha_state()
|
||||
return
|
||||
|
||||
self._is_processing = data.get("is_processing", False)
|
||||
|
||||
# Update conversation history and system prompt
|
||||
self._conversation_history = data.get("conversation_history", [])
|
||||
self._system_prompt = data.get("system_prompt")
|
||||
|
||||
# Update state based on conditions
|
||||
if self._is_processing:
|
||||
self._current_state = STATE_PROCESSING
|
||||
elif data.get("is_rate_limited"):
|
||||
self._current_state = STATE_RATE_LIMITED
|
||||
elif data.get("is_maintenance"):
|
||||
self._current_state = STATE_MAINTENANCE
|
||||
elif data.get("error"):
|
||||
self._current_state = STATE_ERROR
|
||||
self._last_error = data["error"]
|
||||
self._error_count += 1
|
||||
else:
|
||||
self._state = STATE_DISCONNECTED
|
||||
self._current_state = data.get("state", STATE_READY)
|
||||
|
||||
# Update last update timestamp
|
||||
self._last_update = dt_util.utcnow()
|
||||
|
||||
_LOGGER.debug(
|
||||
f"Updated {self.entity_id} state to: {self._current_state} "
|
||||
f"(available: {self.available})"
|
||||
)
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error handling update: %s", err, exc_info=True)
|
||||
self._error_count += 1
|
||||
self._current_state = STATE_ERROR
|
||||
self._last_error = str(err)
|
||||
self._state = STATE_ERROR
|
||||
self._error_count += 1
|
||||
_LOGGER.error(
|
||||
"Error handling update for %s: %s",
|
||||
self.entity_id,
|
||||
err,
|
||||
exc_info=True,
|
||||
)
|
||||
|
||||
self.async_write_ha_state()
|
||||
|
||||
@@ -3,59 +3,55 @@ ask_question:
|
||||
description: >-
|
||||
Send a question to the AI model and receive a detailed response.
|
||||
The response will be stored in the conversation history and can be retrieved later.
|
||||
Response time may vary based on model selection and server load.
|
||||
fields:
|
||||
instance:
|
||||
name: Instance
|
||||
description: Name of the HA Text AI instance to use
|
||||
required: true
|
||||
selector:
|
||||
entity:
|
||||
integration: ha_text_ai
|
||||
domain: sensor
|
||||
|
||||
question:
|
||||
name: Question
|
||||
description: >-
|
||||
Your question or prompt for the AI assistant. Be specific and clear for better results.
|
||||
You can ask about home automation, technical advice, or general questions.
|
||||
For complex queries, consider breaking them into smaller parts.
|
||||
description: Your question or prompt for the AI assistant
|
||||
required: true
|
||||
example: |
|
||||
What automations would you recommend for a smart kitchen?
|
||||
Consider energy efficiency, convenience, and integration with:
|
||||
- Smart lighting
|
||||
- Appliance control
|
||||
- Temperature monitoring
|
||||
- Voice commands
|
||||
selector:
|
||||
text:
|
||||
multiline: true
|
||||
type: text
|
||||
|
||||
system_prompt:
|
||||
name: System Prompt
|
||||
description: Optional system prompt to set context for this specific question
|
||||
required: false
|
||||
selector:
|
||||
text:
|
||||
multiline: true
|
||||
|
||||
context_messages:
|
||||
name: Context Messages
|
||||
description: Number of previous messages to include in context (1-20)
|
||||
required: false
|
||||
default: 5
|
||||
selector:
|
||||
number:
|
||||
min: 1
|
||||
max: 20
|
||||
step: 1
|
||||
mode: slider
|
||||
|
||||
model:
|
||||
name: Model
|
||||
description: >-
|
||||
Select an AI model to use (optional, overrides default setting).
|
||||
Different models have different capabilities and token limits.
|
||||
Note: More capable models may have longer response times and higher API costs.
|
||||
description: "Select AI model to use (optional, overrides default setting)"
|
||||
required: false
|
||||
example: "gpt-3.5-turbo"
|
||||
default: "gpt-3.5-turbo"
|
||||
selector:
|
||||
select:
|
||||
options:
|
||||
- label: "GPT-3.5 Turbo (Fast & Efficient)"
|
||||
value: "gpt-3.5-turbo"
|
||||
- label: "GPT-3.5 Turbo 16K (Extended)"
|
||||
value: "gpt-3.5-turbo-16k"
|
||||
- label: "GPT-4 (Most Capable)"
|
||||
value: "gpt-4"
|
||||
- label: "GPT-4 32K (Extended Context)"
|
||||
value: "gpt-4-32k"
|
||||
- label: "GPT-4 Turbo (Latest)"
|
||||
value: "gpt-4-1106-preview"
|
||||
mode: dropdown
|
||||
text: {}
|
||||
|
||||
temperature:
|
||||
name: Temperature
|
||||
description: >-
|
||||
Controls response creativity (0-2):
|
||||
0.0-0.3: Focused, consistent responses (best for technical/factual queries)
|
||||
0.4-0.7: Balanced responses (recommended for most uses)
|
||||
0.8-2.0: More creative, varied responses (best for brainstorming)
|
||||
Note: Higher values may produce less predictable results.
|
||||
description: Controls response creativity (0.0-2.0)
|
||||
required: false
|
||||
default: 0.7
|
||||
selector:
|
||||
@@ -64,17 +60,10 @@ ask_question:
|
||||
max: 2.0
|
||||
step: 0.1
|
||||
mode: slider
|
||||
unit_of_measurement: ""
|
||||
|
||||
max_tokens:
|
||||
name: Max Tokens
|
||||
description: >-
|
||||
Maximum length of the response. Higher values allow longer responses but use more API tokens.
|
||||
Recommended ranges:
|
||||
- Short responses (256-512): Quick answers, status updates
|
||||
- Medium responses (512-1024): Detailed explanations, instructions
|
||||
- Long responses (1024-4096): Complex analysis, multiple examples
|
||||
Note: Actual response length may be shorter based on content.
|
||||
description: Maximum length of the response (1-4096 tokens)
|
||||
required: false
|
||||
default: 1000
|
||||
selector:
|
||||
@@ -87,23 +76,33 @@ ask_question:
|
||||
clear_history:
|
||||
name: Clear History
|
||||
description: >-
|
||||
Delete all stored questions and responses from the conversation history.
|
||||
This action cannot be undone. Consider using 'get_history' first if you need to backup the data.
|
||||
System prompt settings will be preserved.
|
||||
fields: {}
|
||||
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 recent conversation history, including questions, responses, and timestamps.
|
||||
Results are ordered from newest to oldest and include metadata like model used and response times.
|
||||
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 most recent conversations to return (1-100).
|
||||
Higher values return more history but may take longer to process.
|
||||
Default: 10 conversations
|
||||
description: Number of conversations to return (1-100)
|
||||
required: false
|
||||
default: 10
|
||||
selector:
|
||||
@@ -114,41 +113,57 @@ get_history:
|
||||
mode: box
|
||||
|
||||
filter_model:
|
||||
name: Filter by Model
|
||||
description: >-
|
||||
Only return conversations using a specific AI model.
|
||||
Leave empty to show all models.
|
||||
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:
|
||||
- label: "All Models"
|
||||
value: ""
|
||||
- label: "GPT-3.5 Turbo"
|
||||
value: "gpt-3.5-turbo"
|
||||
- label: "GPT-4"
|
||||
value: "gpt-4"
|
||||
mode: dropdown
|
||||
- newest
|
||||
- oldest
|
||||
|
||||
set_system_prompt:
|
||||
fields:
|
||||
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.
|
||||
Be specific about the desired expertise, tone, and format of responses.
|
||||
Maximum length: 1000 characters.
|
||||
description: Instructions that define how the AI should behave and respond
|
||||
required: true
|
||||
example: |
|
||||
You are a home automation expert assistant. Focus on:
|
||||
1. Practical and efficient solutions
|
||||
2. Energy-saving recommendations
|
||||
3. Integration with popular smart home platforms
|
||||
4. Security and privacy considerations
|
||||
Provide detailed but concise responses with clear steps when applicable.
|
||||
Format complex responses with bullet points or numbered lists.
|
||||
Include warnings about potential risks or limitations.
|
||||
selector:
|
||||
text:
|
||||
multiline: true
|
||||
type: text
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "KI-Anbieter auswählen",
|
||||
"description": "Wählen Sie den KI-Dienstanbieter für diese Instanz aus.",
|
||||
"data": {
|
||||
"api_provider": "API-Anbieter",
|
||||
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "HA Text AI-Instanz konfigurieren",
|
||||
"description": "Richten Sie eine neue KI-Assistenteninstanz mit Ihrem ausgewählten Anbieter ein.",
|
||||
"data": {
|
||||
"name": "Instanzname (z. B. 'GPT-Assistent', 'Claude-Helfer')",
|
||||
"api_key": "API-Schlüssel zur Authentifizierung",
|
||||
"model": "Zu verwendendes KI-Modell",
|
||||
"temperature": "Antwortkreativität (0-2, niedriger = fokussierter)",
|
||||
"max_tokens": "Maximale Antwortlänge (1-4096 Token)",
|
||||
"api_endpoint": "Benutzerdefinierte API-Endpunkt-URL (optional)",
|
||||
"api_provider": "API-Anbieter",
|
||||
"request_interval": "Mindestzeit zwischen Anfragen (0,1-60 Sekunden)",
|
||||
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
|
||||
"max_history_size": "Maximale Größe des Konversationsverlaufs (1-100)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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 - überprüfen Sie Ihre Anmeldedaten",
|
||||
"cannot_connect": "Verbindung zum API-Dienst fehlgeschlagen",
|
||||
"invalid_model": "Das ausgewählte Modell ist nicht verfügbar",
|
||||
"rate_limit": "Ratenlimit überschritten",
|
||||
"context_length": "Kontextlänge überschritten",
|
||||
"rate_limit_exceeded": "API-Ratenlimit überschritten",
|
||||
"maintenance": "Dienst befindet sich in der Wartung",
|
||||
"invalid_response": "Ungültige API-Antwort empfangen",
|
||||
"api_error": "Fehler im API-Dienst aufgetreten",
|
||||
"timeout": "Anfrage ist abgelaufen",
|
||||
"invalid_instance": "Ungültige Instanz angegeben",
|
||||
"unknown": "Es ist ein 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 maximal 50 Zeichen lang sein"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "Instanzeinstellungen aktualisieren",
|
||||
"description": "Ändern Sie die Einstellungen für diese KI-Assistenteninstanz.",
|
||||
"data": {
|
||||
"model": "KI-Modell",
|
||||
"temperature": "Antwortkreativität (0-2)",
|
||||
"max_tokens": "Maximale Antwortlänge (1-4096)",
|
||||
"request_interval": "Mindestzeitraum zwischen Anfragen (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 Konversationsverlaufs (1-100)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "Frage stellen (HA Text AI)",
|
||||
"description": "Senden Sie eine Frage an das KI-Modell und erhalten Sie eine detaillierte Antwort. Die Antwort wird im Konversationsverlauf 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 an den KI-Assistenten"
|
||||
},
|
||||
"context_messages": {
|
||||
"name": "Kontextnachrichten",
|
||||
"description": "Anzahl der vorherigen Nachrichten, die im Kontext enthalten sein sollen (1-20)"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "Systemprompt",
|
||||
"description": "Optionaler Systemprompt, um den Kontext für diese spezielle Frage festzulegen"
|
||||
},
|
||||
"model": {
|
||||
"name": "Modell",
|
||||
"description": "Wählen Sie das zu verwendende KI-Modell aus (optional, überschreibt die Standardeinstellung)"
|
||||
},
|
||||
"temperature": {
|
||||
"name": "Temperatur",
|
||||
"description": "Steuert die Antwortkreativitä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 Konversationsverlauf löschen",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Instanz",
|
||||
"description": "Name der HA Text AI-Instanz, deren Verlauf gelöscht werden soll"
|
||||
}
|
||||
}
|
||||
},
|
||||
"get_history": {
|
||||
"name": "Verlauf abrufen",
|
||||
"description": "Konversationsverlauf mit optionalem Filtern und Sortieren abrufen",
|
||||
"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 Konversationen (1-100)"
|
||||
},
|
||||
"filter_model": {
|
||||
"name": "Modell filtern",
|
||||
"description": "Konversationen nach einem bestimmten KI-Modell filtern"
|
||||
},
|
||||
"start_date": {
|
||||
"name": "Startdatum",
|
||||
"description": "Konversationen ab diesem Datum/Uhrzeit filtern"
|
||||
},
|
||||
"include_metadata": {
|
||||
"name": "Metadaten einschließen",
|
||||
"description": "Zusätzliche Informationen wie verwendete Token, Antwortzeit usw. einschließen"
|
||||
},
|
||||
"sort_order": {
|
||||
"name": "Sortierreihenfolge",
|
||||
"description": "Sortierreihenfolge für die Ergebnisse (neueste oder älteste zuerst)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"set_system_prompt": {
|
||||
"name": "Systemprompt festlegen",
|
||||
"description": "Legen Sie Standardanweisungen für das Systemverhalten für alle zukünftigen Konversationen fest",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Instanz",
|
||||
"description": "Name der HA Text AI-Instanz, für die der Systemprompt festgelegt werden soll"
|
||||
},
|
||||
"prompt": {
|
||||
"name": "Systemprompt",
|
||||
"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": "Ratenlimit",
|
||||
"maintenance": "Wartung",
|
||||
"initializing": "Initialisierung",
|
||||
"retrying": "Wiederholen",
|
||||
"queued": "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": "Systemprompt"
|
||||
},
|
||||
"response_time": {
|
||||
"name": "Letzte Antwortzeit"
|
||||
},
|
||||
"total_responses": {
|
||||
"name": "Gesamtzahl der Antworten"
|
||||
},
|
||||
"error_count": {
|
||||
"name": "Fehleranzahl"
|
||||
},
|
||||
"last_error": {
|
||||
"name": "Letzter Fehler"
|
||||
},
|
||||
"api_status": {
|
||||
"name": "API-Status"
|
||||
},
|
||||
"tokens_used": {
|
||||
"name": "Verwendete Token insgesamt"
|
||||
},
|
||||
"average_response_time": {
|
||||
"name": "Durchschnittliche Antwortzeit"
|
||||
},
|
||||
"last_request_time": {
|
||||
"name": "Zeitpunkt der letzten Anfrage"
|
||||
},
|
||||
"is_processing": {
|
||||
"name": "Verarbeitungsstatus"
|
||||
},
|
||||
"is_rate_limited": {
|
||||
"name": "Ratenlimit-Status"
|
||||
},
|
||||
"is_maintenance": {
|
||||
"name": "Wartungsstatus"
|
||||
},
|
||||
"api_version": {
|
||||
"name": "API-Version"
|
||||
},
|
||||
"endpoint_status": {
|
||||
"name": "Endpunkt-Status"
|
||||
},
|
||||
"performance_metrics": {
|
||||
"name": "Leistungsmetriken"
|
||||
},
|
||||
"history_size": {
|
||||
"name": "Verlaufsgröße"
|
||||
},
|
||||
"uptime": {
|
||||
"name": "Betriebszeit"
|
||||
},
|
||||
"total_tokens": {
|
||||
"name": "Gesamtzahl der Token"
|
||||
},
|
||||
"prompt_tokens": {
|
||||
"name": "Prompt-Token"
|
||||
},
|
||||
"completion_tokens": {
|
||||
"name": "Completion-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"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,54 +1,266 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"user": {
|
||||
"title": "Set up HA Text AI",
|
||||
"description": "Configure your OpenAI integration",
|
||||
"data": {
|
||||
"api_key": "Your OpenAI API key",
|
||||
"model": "AI model to use for responses",
|
||||
"temperature": "Temperature for response generation (0-2)",
|
||||
"max_tokens": "Maximum tokens in response (1-4096)",
|
||||
"api_endpoint": "API endpoint URL",
|
||||
"request_interval": "Minimum time between API requests (seconds)"
|
||||
}
|
||||
}
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "Select AI Provider",
|
||||
"description": "Choose which AI service provider to use for this instance.",
|
||||
"data": {
|
||||
"api_provider": "API Provider",
|
||||
"context_messages": "Number of context messages to retain (1-20)"
|
||||
}
|
||||
},
|
||||
"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": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "HA Text AI Options",
|
||||
"data": {
|
||||
"temperature": "Response temperature (0-2)",
|
||||
"max_tokens": "Maximum response length",
|
||||
"request_interval": "Time between requests"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "Ask Question",
|
||||
"description": "Send a question to the AI model",
|
||||
"fields": {
|
||||
"question": {
|
||||
"name": "Question",
|
||||
"description": "Your question for the AI"
|
||||
}
|
||||
}
|
||||
},
|
||||
"clear_history": {
|
||||
"name": "Clear History",
|
||||
"description": "Clear conversation history"
|
||||
},
|
||||
"get_history": {
|
||||
"name": "Get History",
|
||||
"description": "Retrieve conversation history"
|
||||
},
|
||||
"set_system_prompt": {
|
||||
"name": "Set System Prompt",
|
||||
"description": "Set system behavior instructions"
|
||||
}
|
||||
"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",
|
||||
"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"
|
||||
}
|
||||
},
|
||||
"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)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"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,266 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "Seleccionar proveedor de IA",
|
||||
"description": "Elige qué proveedor de servicios de IA usar para esta instancia.",
|
||||
"data": {
|
||||
"api_provider": "Proveedor de API",
|
||||
"context_messages": "Número de mensajes de contexto que conservar (1-20)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "Configurar instancia de HA Text AI",
|
||||
"description": "Configura una nueva instancia de asistente de IA con el proveedor seleccionado.",
|
||||
"data": {
|
||||
"name": "Nombre de la instancia (p. ej., 'Asistente GPT', 'Ayudante de Claude')",
|
||||
"api_key": "Clave API para la autenticación",
|
||||
"model": "Modelo de IA a usar",
|
||||
"temperature": "Creatividad de la respuesta (0-2, cuanto menor, más enfocada)",
|
||||
"max_tokens": "Longitud máxima de la respuesta (1-4096 tokens)",
|
||||
"api_endpoint": "URL del punto final de la API personalizada (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 que conservar (1-20)",
|
||||
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"name_exists": "Ya existe una instancia con este nombre",
|
||||
"invalid_name": "Nombre de instancia no válido",
|
||||
"invalid_auth": "Error de autenticación: comprueba tu clave API",
|
||||
"invalid_api_key": "Clave API no válida: verifica tus credenciales",
|
||||
"cannot_connect": "No se pudo conectar al servicio API",
|
||||
"invalid_model": "El modelo seleccionado no está disponible",
|
||||
"rate_limit": "Límite de tasa excedido",
|
||||
"context_length": "Longitud de contexto excedida",
|
||||
"rate_limit_exceeded": "Límite de tasa de API excedido",
|
||||
"maintenance": "El servicio está en mantenimiento",
|
||||
"invalid_response": "Se recibió una respuesta de API no válida",
|
||||
"api_error": "Se produjo un error en el servicio API",
|
||||
"timeout": "Tiempo de espera de la solicitud agotado",
|
||||
"invalid_instance": "Instancia especificada no válida",
|
||||
"unknown": "Se produjo 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"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "Actualizar configuración de la instancia",
|
||||
"description": "Modifica la configuración de 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 que se incluirán en el contexto (1-20)",
|
||||
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "Hacer pregunta (HA Text AI)",
|
||||
"description": "Envía una pregunta al modelo de IA y recibe una respuesta detallada. La respuesta se almacenará en el historial de conversación y se podrá recuperar más tarde.",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Instancia",
|
||||
"description": "Nombre de la instancia de HA Text AI a utilizar"
|
||||
},
|
||||
"question": {
|
||||
"name": "Pregunta",
|
||||
"description": "Tu pregunta o indicación para el asistente de IA"
|
||||
},
|
||||
"context_messages": {
|
||||
"name": "Mensajes de contexto",
|
||||
"description": "Número de mensajes anteriores que se incluirán en el contexto (1-20)"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "Indicación del sistema",
|
||||
"description": "Indicación del sistema opcional para establecer el contexto de esta pregunta específica"
|
||||
},
|
||||
"model": {
|
||||
"name": "Modelo",
|
||||
"description": "Selecciona el modelo de IA que se va 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 HA Text AI para la que se va a borrar el historial"
|
||||
}
|
||||
}
|
||||
},
|
||||
"get_history": {
|
||||
"name": "Obtener historial",
|
||||
"description": "Recupera el historial de conversaciones con filtrado y ordenación opcionales",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Instancia",
|
||||
"description": "Nombre de la instancia de HA Text AI de la que se va a obtener el historial"
|
||||
},
|
||||
"limit": {
|
||||
"name": "Límite",
|
||||
"description": "Número de conversaciones que se van a devolver (1-100)"
|
||||
},
|
||||
"filter_model": {
|
||||
"name": "Filtrar modelo",
|
||||
"description": "Filtra las conversaciones por un modelo de IA específico"
|
||||
},
|
||||
"start_date": {
|
||||
"name": "Fecha de inicio",
|
||||
"description": "Filtra las conversaciones a partir de esta fecha/hora"
|
||||
},
|
||||
"include_metadata": {
|
||||
"name": "Incluir metadatos",
|
||||
"description": "Incluir información adicional como los tokens utilizados, el tiempo de respuesta, etc."
|
||||
},
|
||||
"sort_order": {
|
||||
"name": "Orden de clasificación",
|
||||
"description": "Orden de clasificación de los resultados (más recientes o más antiguos primero)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"set_system_prompt": {
|
||||
"name": "Establecer indicación del sistema",
|
||||
"description": "Establece instrucciones predeterminadas de comportamiento del sistema para todas las conversaciones futuras",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Instancia",
|
||||
"description": "Nombre de la instancia de HA Text AI para la que se va a establecer la indicación del sistema"
|
||||
},
|
||||
"prompt": {
|
||||
"name": "Indicación 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": "Límite de tasa alcanzado",
|
||||
"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": "Indicación del sistema"
|
||||
},
|
||||
"response_time": {
|
||||
"name": "Tiempo de la última respuesta"
|
||||
},
|
||||
"total_responses": {
|
||||
"name": "Total de respuestas"
|
||||
},
|
||||
"error_count": {
|
||||
"name": "Recuento de errores"
|
||||
},
|
||||
"last_error": {
|
||||
"name": "Último error"
|
||||
},
|
||||
"api_status": {
|
||||
"name": "Estado de la API"
|
||||
},
|
||||
"tokens_used": {
|
||||
"name": "Total de tokens usados"
|
||||
},
|
||||
"average_response_time": {
|
||||
"name": "Tiempo medio de respuesta"
|
||||
},
|
||||
"last_request_time": {
|
||||
"name": "Tiempo de la última solicitud"
|
||||
},
|
||||
"is_processing": {
|
||||
"name": "Estado de procesamiento"
|
||||
},
|
||||
"is_rate_limited": {
|
||||
"name": "Estado de límite de tasa"
|
||||
},
|
||||
"is_maintenance": {
|
||||
"name": "Estado de mantenimiento"
|
||||
},
|
||||
"api_version": {
|
||||
"name": "Versión de la API"
|
||||
},
|
||||
"endpoint_status": {
|
||||
"name": "Estado del punto final"
|
||||
},
|
||||
"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 indicación"
|
||||
},
|
||||
"completion_tokens": {
|
||||
"name": "Tokens de compleción"
|
||||
},
|
||||
"successful_requests": {
|
||||
"name": "Solicitudes exitosas"
|
||||
},
|
||||
"failed_requests": {
|
||||
"name": "Solicitudes fallidas"
|
||||
},
|
||||
"average_latency": {
|
||||
"name": "Latencia media"
|
||||
},
|
||||
"max_latency": {
|
||||
"name": "Latencia máxima"
|
||||
},
|
||||
"min_latency": {
|
||||
"name": "Latencia mínima"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "AI प्रदाता का चयन करें",
|
||||
"description": "इस उदाहरण के लिए उपयोग करने के लिए AI सेवा प्रदाता चुनें।",
|
||||
"data": {
|
||||
"api_provider": "API प्रदाता",
|
||||
"context_messages": "बनाए रखने के लिए संदर्भ संदेशों की संख्या (1-20)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "HA टेक्स्ट AI उदाहरण को कॉन्फ़िगर करें",
|
||||
"description": "अपने चयनित प्रदाता के साथ एक नया AI सहायक उदाहरण सेट करें।",
|
||||
"data": {
|
||||
"name": "उदाहरण का नाम (जैसे, 'GPT सहायक', 'क्लाउड सहायक')",
|
||||
"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": {
|
||||
"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 वर्ण या उससे कम होना चाहिए"
|
||||
}
|
||||
},
|
||||
"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)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"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": "न्यूनतम विलंबता"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "Seleziona Provider AI",
|
||||
"description": "Scegli quale provider di servizio AI utilizzare per questa istanza.",
|
||||
"data": {
|
||||
"api_provider": "Provider API",
|
||||
"context_messages": "Numero di messaggi di contesto da conservare (1-20)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "Configura Istanza HA Text AI",
|
||||
"description": "Configura una nuova istanza di assistente AI con il provider selezionato.",
|
||||
"data": {
|
||||
"name": "Nome dell'istanza (es. 'Assistente GPT', 'Aiutante 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 endpoint API personalizzato (opzionale)",
|
||||
"api_provider": "Provider API",
|
||||
"request_interval": "Tempo minimo tra le richieste (0,1-60 secondi)",
|
||||
"context_messages": "Numero di messaggi di contesto da conservare (1-20)",
|
||||
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"name_exists": "Un'istanza con questo nome esiste già",
|
||||
"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 velocità superato",
|
||||
"context_length": "Lunghezza del contesto superata",
|
||||
"rate_limit_exceeded": "Limite di velocità API superato",
|
||||
"maintenance": "Il servizio è in manutenzione",
|
||||
"invalid_response": "Risposta API non valida ricevuta",
|
||||
"api_error": "Si è verificato un errore del servizio API",
|
||||
"timeout": "Richiesta scaduta",
|
||||
"invalid_instance": "Istanza non valida specificata",
|
||||
"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 non può superare i 50 caratteri"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "Aggiorna Impostazioni 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 tra le richieste (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)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "Fai una Domanda (HA Text AI)",
|
||||
"description": "Invia una domanda al modello AI e ricevi una risposta dettagliata. La risposta verrà memorizzata nella cronologia delle conversazioni e potrà essere recuperata in seguito.",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Istanza",
|
||||
"description": "Nome dell'istanza HA Text AI da utilizzare"
|
||||
},
|
||||
"question": {
|
||||
"name": "Domanda",
|
||||
"description": "La tua domanda o prompt 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": "Max Token",
|
||||
"description": "Lunghezza massima della risposta (1-4096 token)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"clear_history": {
|
||||
"name": "Cancella Cronologia",
|
||||
"description": "Elimina tutte le domande e le risposte memorizzate dalla cronologia delle conversazioni",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Istanza",
|
||||
"description": "Nome dell'istanza HA Text AI per cui cancellare la cronologia"
|
||||
}
|
||||
}
|
||||
},
|
||||
"get_history": {
|
||||
"name": "Ottieni Cronologia",
|
||||
"description": "Recupera la cronologia delle conversazioni con filtro e ordinamento opzionali",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Istanza",
|
||||
"description": "Nome dell'istanza HA Text AI da cui ottenere la cronologia"
|
||||
},
|
||||
"limit": {
|
||||
"name": "Limite",
|
||||
"description": "Numero di conversazioni da restituire (1-100)"
|
||||
},
|
||||
"filter_model": {
|
||||
"name": "Filtro Modello",
|
||||
"description": "Filtra le conversazioni per specifico modello AI"
|
||||
},
|
||||
"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ù recente o più vecchio per primo)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"set_system_prompt": {
|
||||
"name": "Imposta Prompt di Sistema",
|
||||
"description": "Imposta le istruzioni di comportamento predefinite del sistema per tutte le future conversazioni",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Istanza",
|
||||
"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'IA dovrebbe comportarsi e rispondere"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"entity": {
|
||||
"sensor": {
|
||||
"ha_text_ai": {
|
||||
"name": "{name}",
|
||||
"state": {
|
||||
"ready": "Pronto",
|
||||
"processing": "In elaborazione",
|
||||
"error": "Errore",
|
||||
"disconnected": "Disconnesso",
|
||||
"rate_limited": "Limite di Velocità Raggiunto",
|
||||
"maintenance": "Manutenzione",
|
||||
"initializing": "Inizializzazione",
|
||||
"retrying": "Riprovando",
|
||||
"queued": "In coda"
|
||||
},
|
||||
"state_attributes": {
|
||||
"question": {
|
||||
"name": "Ultima Domanda"
|
||||
},
|
||||
"response": {
|
||||
"name": "Ultima Risposta"
|
||||
},
|
||||
"model": {
|
||||
"name": "Modello Attuale"
|
||||
},
|
||||
"temperature": {
|
||||
"name": "Temperatura"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "Max Token"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "Prompt di Sistema"
|
||||
},
|
||||
"response_time": {
|
||||
"name": "Tempo di Risposta Ultima"
|
||||
},
|
||||
"total_responses": {
|
||||
"name": "Totale Risposte"
|
||||
},
|
||||
"error_count": {
|
||||
"name": "Numero di Errori"
|
||||
},
|
||||
"last_error": {
|
||||
"name": "Ultimo Errore"
|
||||
},
|
||||
"api_status": {
|
||||
"name": "Stato API"
|
||||
},
|
||||
"tokens_used": {
|
||||
"name": "Totale Token Utilizzati"
|
||||
},
|
||||
"average_response_time": {
|
||||
"name": "Tempo di Risposta Medio"
|
||||
},
|
||||
"last_request_time": {
|
||||
"name": "Tempo Ultima Richiesta"
|
||||
},
|
||||
"is_processing": {
|
||||
"name": "Stato Elaborazione"
|
||||
},
|
||||
"is_rate_limited": {
|
||||
"name": "Stato Limite Velocità"
|
||||
},
|
||||
"is_maintenance": {
|
||||
"name": "Stato Manutenzione"
|
||||
},
|
||||
"api_version": {
|
||||
"name": "Versione API"
|
||||
},
|
||||
"endpoint_status": {
|
||||
"name": "Stato Endpoint"
|
||||
},
|
||||
"performance_metrics": {
|
||||
"name": "Metriche Prestazioni"
|
||||
},
|
||||
"history_size": {
|
||||
"name": "Dimensione Cronologia"
|
||||
},
|
||||
"uptime": {
|
||||
"name": "Tempo di Funzionamento"
|
||||
},
|
||||
"total_tokens": {
|
||||
"name": "Totale Token"
|
||||
},
|
||||
"prompt_tokens": {
|
||||
"name": "Token Prompt"
|
||||
},
|
||||
"completion_tokens": {
|
||||
"name": "Token Completamento"
|
||||
},
|
||||
"successful_requests": {
|
||||
"name": "Richieste Riuscite"
|
||||
},
|
||||
"failed_requests": {
|
||||
"name": "Richieste Fallite"
|
||||
},
|
||||
"average_latency": {
|
||||
"name": "Latency Media"
|
||||
},
|
||||
"max_latency": {
|
||||
"name": "Latency Massima"
|
||||
},
|
||||
"min_latency": {
|
||||
"name": "Latency Minima"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,54 +1,266 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"user": {
|
||||
"title": "Настройка HA Text AI",
|
||||
"description": "Настройка интеграции с OpenAI",
|
||||
"data": {
|
||||
"api_key": "Ваш ключ API OpenAI",
|
||||
"model": "Модель ИИ для генерации ответов",
|
||||
"temperature": "Температура генерации ответов (0-2)",
|
||||
"max_tokens": "Максимальное количество токенов в ответе (1-4096)",
|
||||
"api_endpoint": "URL конечной точки API",
|
||||
"request_interval": "Минимальное время между запросами к API (секунды)"
|
||||
}
|
||||
}
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "Выбор поставщика ИИ",
|
||||
"description": "Выберите поставщика услуг ИИ для этой инстанции.",
|
||||
"data": {
|
||||
"api_provider": "Поставщик API",
|
||||
"context_messages": "Количество контекстных сообщений для сохранения (1-20)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "Настройка инстанции HA Text AI",
|
||||
"description": "Настройте новую инстанцию помощника ИИ с выбранным вами поставщиком.",
|
||||
"data": {
|
||||
"name": "Имя инстанции (например, 'GPT Assistant', 'Claude Helper')",
|
||||
"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": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "Настройки HA Text AI",
|
||||
"data": {
|
||||
"temperature": "Температура ответов (0-2)",
|
||||
"max_tokens": "Максимальная длина ответа",
|
||||
"request_interval": "Время между запросами"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "Задать вопрос",
|
||||
"description": "Отправить вопрос модели ИИ",
|
||||
"fields": {
|
||||
"question": {
|
||||
"name": "Вопрос",
|
||||
"description": "Ваш вопрос для ИИ"
|
||||
}
|
||||
}
|
||||
},
|
||||
"clear_history": {
|
||||
"name": "Очистить историю",
|
||||
"description": "Очистить историю разговора"
|
||||
},
|
||||
"get_history": {
|
||||
"name": "Получить историю",
|
||||
"description": "Получить историю разговора"
|
||||
},
|
||||
"set_system_prompt": {
|
||||
"name": "Установить системный промпт",
|
||||
"description": "Установить инструкции поведения системы"
|
||||
}
|
||||
"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 символов"
|
||||
}
|
||||
},
|
||||
"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)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"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": "Минимальная задержка"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "Изаберите добављача вештачке интелигенције",
|
||||
"description": "Изаберите добављача услуга вештачке интелигенције који ћете користити за ову инстанцу.",
|
||||
"data": {
|
||||
"api_provider": "Добављач API-ја",
|
||||
"context_messages": "Број порука контекста које треба задржати (1-20)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "Конфигуришите инстанцу HA Text AI",
|
||||
"description": "Поставите нову инстанцу асистента вештачке интелигенције са изабраним добављачем.",
|
||||
"data": {
|
||||
"name": "Назив инстанце (нпр. 'GPT Assistant', 'Claude Helper')",
|
||||
"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)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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 карактера или мање"
|
||||
}
|
||||
},
|
||||
"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)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"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": "Минимална латенција"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "选择 AI 提供商",
|
||||
"description": "选择要用于此实例的 AI 服务提供商。",
|
||||
"data": {
|
||||
"api_provider": "API 提供商",
|
||||
"context_messages": "要保留的上下文消息数量 (1-20)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "配置 HA Text AI 实例",
|
||||
"description": "使用您选择的提供商设置新的 AI 助手实例。",
|
||||
"data": {
|
||||
"name": "实例名称(例如,“GPT 助手”、“Claude 助手”)",
|
||||
"api_key": "用于身份验证的 API 密钥",
|
||||
"model": "要使用的 AI 模型",
|
||||
"temperature": "回复创意度 (0-2,数值越低,回复越聚焦)",
|
||||
"max_tokens": "最大回复长度(1-4096 个 Token)",
|
||||
"api_endpoint": "自定义 API 端点 URL(可选)",
|
||||
"api_provider": "API 提供商",
|
||||
"request_interval": "请求之间的最短时间间隔(0.1-60 秒)",
|
||||
"context_messages": "要保留的上下文消息数量 (1-20)",
|
||||
"max_history_size": "最大对话历史记录大小 (1-100)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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 个字符或更少"
|
||||
}
|
||||
},
|
||||
"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)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"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": "最大 Token 数",
|
||||
"description": "回复的最大长度(1-4096 个 Token)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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": "包含其他信息,例如使用的 Token 数、响应时间等。"
|
||||
},
|
||||
"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": "最大 Token 数"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "系统提示"
|
||||
},
|
||||
"response_time": {
|
||||
"name": "上次回复时间"
|
||||
},
|
||||
"total_responses": {
|
||||
"name": "总回复次数"
|
||||
},
|
||||
"error_count": {
|
||||
"name": "错误计数"
|
||||
},
|
||||
"last_error": {
|
||||
"name": "上次错误"
|
||||
},
|
||||
"api_status": {
|
||||
"name": "API 状态"
|
||||
},
|
||||
"tokens_used": {
|
||||
"name": "已使用的 Token 总数"
|
||||
},
|
||||
"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": "总 Token 数"
|
||||
},
|
||||
"prompt_tokens": {
|
||||
"name": "提示 Token 数"
|
||||
},
|
||||
"completion_tokens": {
|
||||
"name": "完成 Token 数"
|
||||
},
|
||||
"successful_requests": {
|
||||
"name": "成功请求数"
|
||||
},
|
||||
"failed_requests": {
|
||||
"name": "失败请求数"
|
||||
},
|
||||
"average_latency": {
|
||||
"name": "平均延迟"
|
||||
},
|
||||
"max_latency": {
|
||||
"name": "最大延迟"
|
||||
},
|
||||
"min_latency": {
|
||||
"name": "最小延迟"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,5 @@
|
||||
{
|
||||
"name": "HA text AI",
|
||||
"render_readme": true,
|
||||
"domains": ["sensor"],
|
||||
"homeassistant": "2024.11.0",
|
||||
"icon": "mdi:brain",
|
||||
"version": "1.0.8",
|
||||
"documentation": "https://github.com/smkrv/ha-text-ai"
|
||||
"homeassistant": "2024.11.0"
|
||||
}
|
||||
|
||||
|
After Width: | Height: | Size: 618 KiB |
|
After Width: | Height: | Size: 923 KiB |
|
After Width: | Height: | Size: 1.0 MiB |
@@ -1,3 +0,0 @@
|
||||
pytest
|
||||
pytest-asyncio
|
||||
homeassistant
|
||||
@@ -0,0 +1,25 @@
|
||||
```
|
||||
ha-text-ai/
|
||||
│
|
||||
├── custom_components/
|
||||
├── ha_text_ai/
|
||||
│ ├── __init__.py
|
||||
│ ├── config_flow.py
|
||||
│ ├── coordinator.py
|
||||
│ ├── manifest.json
|
||||
│ ├── sensor.py
|
||||
│ ├── services.yaml
|
||||
│ ├── const.py
|
||||
│ └── api_client.py
|
||||
│
|
||||
├── translations/
|
||||
│ ├── en.json
|
||||
│ ├── de.json
|
||||
│ └── ru.json
|
||||
│
|
||||
└── icons/
|
||||
├── icon.png
|
||||
├── icon@2x.png
|
||||
├── logo.png
|
||||
└── logo@2x.png
|
||||
```
|
||||