Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43cbac2d04 | ||
|
|
986c78dd90 | ||
|
|
0859c35aec | ||
|
|
922fefbd43 | ||
|
|
a5ac100b06 | ||
|
|
ef579af7c1 | ||
|
|
3097106e93 | ||
|
|
35073960b8 | ||
|
|
8d0e0b5e44 | ||
|
|
e91c3701c5 | ||
|
|
7f62101b3e | ||
|
|
3729c3736f | ||
|
|
f5ce5e459a | ||
|
|
4064486b1e | ||
|
|
185778dbd0 | ||
|
|
83a255dee0 | ||
|
|
6b66dd6a4d | ||
|
|
bd82f23120 | ||
|
|
eee9754033 | ||
|
|
517b1f11ae | ||
|
|
ed8f19bfa9 | ||
|
|
7e3daf611b | ||
|
|
37919be70f | ||
|
|
e427254584 | ||
|
|
76c5629fa0 | ||
|
|
7958bd010b | ||
|
|
8cd876195a | ||
|
|
376753e001 | ||
|
|
b6e73e847d | ||
|
|
440c734214 | ||
|
|
73788373cd | ||
|
|
4bfc96019b | ||
|
|
2138fc7654 | ||
|
|
95bd2ebb41 | ||
|
|
cad0fd7031 | ||
|
|
c003b258f6 | ||
|
|
65a10c77f4 | ||
|
|
e1463828c9 | ||
|
|
5ebb9c9c66 | ||
|
|
f17c631a79 | ||
|
|
0e06794384 | ||
|
|
d8a924909b | ||
|
|
29f1659a02 | ||
|
|
5b7905de80 | ||
|
|
cf9ac6dcea | ||
|
|
568eb3e16c | ||
|
|
53fb150389 | ||
|
|
acbb53d2af | ||
|
|
e19db29441 | ||
|
|
bfd64d1122 | ||
|
|
82e1f0c4f9 | ||
|
|
5c16eee6e4 | ||
|
|
e988d445a4 | ||
|
|
f9bfb9ab7f | ||
|
|
92dd1bc110 | ||
|
|
17d547325a | ||
|
|
b8cb70217c | ||
|
|
530d04f25d | ||
|
|
b71083b9bf | ||
|
|
f9f7d10f7f | ||
|
|
9f7cb20621 | ||
|
|
6fc3b23365 | ||
|
|
15c717fcb0 | ||
|
|
be06fddce1 | ||
|
|
5f0bd861a7 | ||
|
|
428aee46c8 | ||
|
|
561bcf0b1d | ||
|
|
2b1e42c665 | ||
|
|
2d68f29ab5 | ||
|
|
19d4a93bca | ||
|
|
fb75c5f44e | ||
|
|
52af987985 | ||
|
|
162a30acdd | ||
|
|
898a6fc638 | ||
|
|
38e2362be4 | ||
|
|
cea912d0b5 | ||
|
|
5ec00040c2 | ||
|
|
8d28fc4a0d | ||
|
|
7cc6587724 | ||
|
|
bacf76e0a9 | ||
|
|
f86c7bfd57 | ||
|
|
2aaf340575 | ||
|
|
bae11ba85c | ||
|
|
9eb7d8912c | ||
|
|
d29535245f | ||
|
|
ca3ae982b0 | ||
|
|
0c4399b46c | ||
|
|
c13ef1921d | ||
|
|
0fb9acfa8f | ||
|
|
2ac4389e1a | ||
|
|
de194e425c | ||
|
|
95f3d6506e | ||
|
|
3e877243b9 | ||
|
|
fd795c9e90 | ||
|
|
5f5dc041b9 | ||
|
|
3d3885d43d | ||
|
|
b059744716 | ||
|
|
f2a41aaa2c | ||
|
|
1fcf751d0d | ||
|
|
a45c9407fd | ||
|
|
21fdf108cf | ||
|
|
c7ec2b3ea4 | ||
|
|
6c4da6cea5 | ||
|
|
3029c5dd26 | ||
|
|
3e97028094 | ||
|
|
1194c87134 | ||
|
|
e03b5315c2 | ||
|
|
fad887492f | ||
|
|
f26df29937 | ||
|
|
69b54a08ba | ||
|
|
7ce77eb18e | ||
|
|
1480669dc8 | ||
|
|
f397bbffe7 | ||
|
|
5709bce1ae | ||
|
|
d549a36c3a | ||
|
|
e9ba480e95 | ||
|
|
8ac7154399 | ||
|
|
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 | ||
|
|
f6bfbd4a07 | ||
|
|
4ddb0dc977 | ||
|
|
24dc4ac4d4 | ||
|
|
976f4f16a3 | ||
|
|
2bdef2b494 | ||
|
|
42324a793b | ||
|
|
30aa894634 | ||
|
|
398b2550a9 | ||
|
|
f1deaa2014 | ||
|
|
f4b0ce902e | ||
|
|
d899144149 | ||
|
|
5d49b4a40b | ||
|
|
1a84727cf1 | ||
|
|
d3c7e25202 |
@@ -1,5 +1,6 @@
|
|||||||
name: Validate with hassfest
|
name: Validate with hassfest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
name: Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
release:
|
||||||
|
types: [created]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
name: Build and upload release asset
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: ${{ github.event.release.tag_name }}
|
||||||
|
|
||||||
|
- name: Create zip archive
|
||||||
|
run: |
|
||||||
|
cd custom_components
|
||||||
|
zip -r ../ha_text_ai.zip ha_text_ai \
|
||||||
|
-x "ha_text_ai/__pycache__/*" \
|
||||||
|
-x "*.pyc" \
|
||||||
|
-x "*.pyo" \
|
||||||
|
-x "*/__pycache__/*" \
|
||||||
|
-x "*.DS_Store"
|
||||||
|
|
||||||
|
- name: Upload release asset
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
tag_name: ${{ github.event.release.tag_name }}
|
||||||
|
files: ha_text_ai.zip
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
name: Validate
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
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 +0,0 @@
|
|||||||
__pycache__/
|
|
||||||
*.py[cod]
|
|
||||||
*$py.class
|
|
||||||
.DS_Store
|
|
||||||
.env
|
|
||||||
.venv
|
|
||||||
venv/
|
|
||||||
ENV/
|
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
# Contributor Covenant Code of Conduct
|
||||||
|
|
||||||
|
## Our Pledge
|
||||||
|
|
||||||
|
We as members, contributors, and leaders pledge to make participation in our
|
||||||
|
community a harassment-free experience for everyone, regardless of age, body
|
||||||
|
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||||
|
identity and expression, level of experience, education, socio-economic status,
|
||||||
|
nationality, personal appearance, race, religion, or sexual identity
|
||||||
|
and orientation.
|
||||||
|
|
||||||
|
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||||
|
diverse, inclusive, and healthy community.
|
||||||
|
|
||||||
|
## Our Standards
|
||||||
|
|
||||||
|
Examples of behavior that contributes to a positive environment for our
|
||||||
|
community include:
|
||||||
|
|
||||||
|
* Demonstrating empathy and kindness toward other people
|
||||||
|
* Being respectful of differing opinions, viewpoints, and experiences
|
||||||
|
* Giving and gracefully accepting constructive feedback
|
||||||
|
* Accepting responsibility and apologizing to those affected by our mistakes,
|
||||||
|
and learning from the experience
|
||||||
|
* Focusing on what is best not just for us as individuals, but for the
|
||||||
|
overall community
|
||||||
|
|
||||||
|
Examples of unacceptable behavior include:
|
||||||
|
|
||||||
|
* The use of sexualized language or imagery, and sexual attention or
|
||||||
|
advances of any kind
|
||||||
|
* Trolling, insulting or derogatory comments, and personal or political attacks
|
||||||
|
* Public or private harassment
|
||||||
|
* Publishing others' private information, such as a physical or email
|
||||||
|
address, without their explicit permission
|
||||||
|
* Other conduct which could reasonably be considered inappropriate in a
|
||||||
|
professional setting
|
||||||
|
|
||||||
|
## Enforcement Responsibilities
|
||||||
|
|
||||||
|
Community leaders are responsible for clarifying and enforcing our standards of
|
||||||
|
acceptable behavior and will take appropriate and fair corrective action in
|
||||||
|
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||||
|
or harmful.
|
||||||
|
|
||||||
|
Community leaders have the right and responsibility to remove, edit, or reject
|
||||||
|
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||||
|
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||||
|
decisions when appropriate.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
This Code of Conduct applies within all community spaces, and also applies when
|
||||||
|
an individual is officially representing the community in public spaces.
|
||||||
|
Examples of representing our community include using an official e-mail address,
|
||||||
|
posting via an official social media account, or acting as an appointed
|
||||||
|
representative at an online or offline event.
|
||||||
|
|
||||||
|
## Enforcement
|
||||||
|
|
||||||
|
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||||
|
reported to the community leaders responsible for enforcement at
|
||||||
|
issue tracker.
|
||||||
|
All complaints will be reviewed and investigated promptly and fairly.
|
||||||
|
|
||||||
|
All community leaders are obligated to respect the privacy and security of the
|
||||||
|
reporter of any incident.
|
||||||
|
|
||||||
|
## Enforcement Guidelines
|
||||||
|
|
||||||
|
Community leaders will follow these Community Impact Guidelines in determining
|
||||||
|
the consequences for any action they deem in violation of this Code of Conduct:
|
||||||
|
|
||||||
|
### 1. Correction
|
||||||
|
|
||||||
|
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||||
|
unprofessional or unwelcome in the community.
|
||||||
|
|
||||||
|
**Consequence**: A private, written warning from community leaders, providing
|
||||||
|
clarity around the nature of the violation and an explanation of why the
|
||||||
|
behavior was inappropriate. A public apology may be requested.
|
||||||
|
|
||||||
|
### 2. Warning
|
||||||
|
|
||||||
|
**Community Impact**: A violation through a single incident or series
|
||||||
|
of actions.
|
||||||
|
|
||||||
|
**Consequence**: A warning with consequences for continued behavior. No
|
||||||
|
interaction with the people involved, including unsolicited interaction with
|
||||||
|
those enforcing the Code of Conduct, for a specified period of time. This
|
||||||
|
includes avoiding interactions in community spaces as well as external channels
|
||||||
|
like social media. Violating these terms may lead to a temporary or
|
||||||
|
permanent ban.
|
||||||
|
|
||||||
|
### 3. Temporary Ban
|
||||||
|
|
||||||
|
**Community Impact**: A serious violation of community standards, including
|
||||||
|
sustained inappropriate behavior.
|
||||||
|
|
||||||
|
**Consequence**: A temporary ban from any sort of interaction or public
|
||||||
|
communication with the community for a specified period of time. No public or
|
||||||
|
private interaction with the people involved, including unsolicited interaction
|
||||||
|
with those enforcing the Code of Conduct, is allowed during this period.
|
||||||
|
Violating these terms may lead to a permanent ban.
|
||||||
|
|
||||||
|
### 4. Permanent Ban
|
||||||
|
|
||||||
|
**Community Impact**: Demonstrating a pattern of violation of community
|
||||||
|
standards, including sustained inappropriate behavior, harassment of an
|
||||||
|
individual, or aggression toward or disparagement of classes of individuals.
|
||||||
|
|
||||||
|
**Consequence**: A permanent ban from any sort of public interaction within
|
||||||
|
the community.
|
||||||
|
|
||||||
|
## Attribution
|
||||||
|
|
||||||
|
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||||
|
version 2.0, available at
|
||||||
|
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||||
|
|
||||||
|
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||||
|
enforcement ladder](https://github.com/mozilla/diversity).
|
||||||
|
|
||||||
|
[homepage]: https://www.contributor-covenant.org
|
||||||
|
|
||||||
|
For answers to common questions about this code of conduct, see the FAQ at
|
||||||
|
https://www.contributor-covenant.org/faq. Translations are available at
|
||||||
|
https://www.contributor-covenant.org/translations.
|
||||||
@@ -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
|
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
does not provide legal services or legal advice. Distribution of
|
||||||
in the Software without restriction, including without limitation the rights
|
Creative Commons public licenses does not create a lawyer-client or
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
other relationship. Creative Commons makes its licenses and related
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
information available on an "as-is" basis. Creative Commons gives no
|
||||||
furnished to do so, subject to the following conditions:
|
warranties regarding its licenses, any material licensed under their
|
||||||
|
terms and conditions, or any related information. Creative Commons
|
||||||
|
disclaims all liability for damages resulting from their use to the
|
||||||
|
fullest extent possible.
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
Using Creative Commons Public Licenses
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
Creative Commons public licenses provide a standard set of terms and
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
conditions that creators and other rights holders may use to share
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
original works of authorship and other material subject to copyright
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
and certain other rights specified in the public license below. The
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
following considerations are for informational purposes only, are not
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
exhaustive, and do not form part of our licenses.
|
||||||
SOFTWARE.
|
|
||||||
|
Considerations for licensors: Our public licenses are
|
||||||
|
intended for use by those authorized to give the public
|
||||||
|
permission to use material in ways otherwise restricted by
|
||||||
|
copyright and certain other rights. Our licenses are
|
||||||
|
irrevocable. Licensors should read and understand the terms
|
||||||
|
and conditions of the license they choose before applying it.
|
||||||
|
Licensors should also secure all rights necessary before
|
||||||
|
applying our licenses so that the public can reuse the
|
||||||
|
material as expected. Licensors should clearly mark any
|
||||||
|
material not subject to the license. This includes other CC-
|
||||||
|
licensed material, or material used under an exception or
|
||||||
|
limitation to copyright. More considerations for licensors:
|
||||||
|
wiki.creativecommons.org/Considerations_for_licensors
|
||||||
|
|
||||||
|
Considerations for the public: By using one of our public
|
||||||
|
licenses, a licensor grants the public permission to use the
|
||||||
|
licensed material under specified terms and conditions. If
|
||||||
|
the licensor's permission is not necessary for any reason--for
|
||||||
|
example, because of any applicable exception or limitation to
|
||||||
|
copyright--then that use is not regulated by the license. Our
|
||||||
|
licenses grant only permissions under copyright and certain
|
||||||
|
other rights that a licensor has authority to grant. Use of
|
||||||
|
the licensed material may still be restricted for other
|
||||||
|
reasons, including because others have copyright or other
|
||||||
|
rights in the material. A licensor may make special requests,
|
||||||
|
such as asking that all changes be marked or described.
|
||||||
|
Although not required by our licenses, you are encouraged to
|
||||||
|
respect those requests where reasonable. More considerations
|
||||||
|
for the public:
|
||||||
|
wiki.creativecommons.org/Considerations_for_licensees
|
||||||
|
|
||||||
|
=======================================================================
|
||||||
|
|
||||||
|
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
|
||||||
|
Public License
|
||||||
|
|
||||||
|
By exercising the Licensed Rights (defined below), You accept and agree
|
||||||
|
to be bound by the terms and conditions of this Creative Commons
|
||||||
|
Attribution-NonCommercial-ShareAlike 4.0 International Public License
|
||||||
|
("Public License"). To the extent this Public License may be
|
||||||
|
interpreted as a contract, You are granted the Licensed Rights in
|
||||||
|
consideration of Your acceptance of these terms and conditions, and the
|
||||||
|
Licensor grants You such rights in consideration of benefits the
|
||||||
|
Licensor receives from making the Licensed Material available under
|
||||||
|
these terms and conditions.
|
||||||
|
|
||||||
|
|
||||||
|
Section 1 -- Definitions.
|
||||||
|
|
||||||
|
a. Adapted Material means material subject to Copyright and Similar
|
||||||
|
Rights that is derived from or based upon the Licensed Material
|
||||||
|
and in which the Licensed Material is translated, altered,
|
||||||
|
arranged, transformed, or otherwise modified in a manner requiring
|
||||||
|
permission under the Copyright and Similar Rights held by the
|
||||||
|
Licensor. For purposes of this Public License, where the Licensed
|
||||||
|
Material is a musical work, performance, or sound recording,
|
||||||
|
Adapted Material is always produced where the Licensed Material is
|
||||||
|
synched in timed relation with a moving image.
|
||||||
|
|
||||||
|
b. Adapter's License means the license You apply to Your Copyright
|
||||||
|
and Similar Rights in Your contributions to Adapted Material in
|
||||||
|
accordance with the terms and conditions of this Public License.
|
||||||
|
|
||||||
|
c. BY-NC-SA Compatible License means a license listed at
|
||||||
|
creativecommons.org/compatiblelicenses, approved by Creative
|
||||||
|
Commons as essentially the equivalent of this Public License.
|
||||||
|
|
||||||
|
d. Copyright and Similar Rights means copyright and/or similar rights
|
||||||
|
closely related to copyright including, without limitation,
|
||||||
|
performance, broadcast, sound recording, and Sui Generis Database
|
||||||
|
Rights, without regard to how the rights are labeled or
|
||||||
|
categorized. For purposes of this Public License, the rights
|
||||||
|
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
||||||
|
Rights.
|
||||||
|
|
||||||
|
e. Effective Technological Measures means those measures that, in the
|
||||||
|
absence of proper authority, may not be circumvented under laws
|
||||||
|
fulfilling obligations under Article 11 of the WIPO Copyright
|
||||||
|
Treaty adopted on December 20, 1996, and/or similar international
|
||||||
|
agreements.
|
||||||
|
|
||||||
|
f. Exceptions and Limitations means fair use, fair dealing, and/or
|
||||||
|
any other exception or limitation to Copyright and Similar Rights
|
||||||
|
that applies to Your use of the Licensed Material.
|
||||||
|
|
||||||
|
g. License Elements means the license attributes listed in the name
|
||||||
|
of a Creative Commons Public License. The License Elements of this
|
||||||
|
Public License are Attribution, NonCommercial, and ShareAlike.
|
||||||
|
|
||||||
|
h. Licensed Material means the artistic or literary work, database,
|
||||||
|
or other material to which the Licensor applied this Public
|
||||||
|
License.
|
||||||
|
|
||||||
|
i. Licensed Rights means the rights granted to You subject to the
|
||||||
|
terms and conditions of this Public License, which are limited to
|
||||||
|
all Copyright and Similar Rights that apply to Your use of the
|
||||||
|
Licensed Material and that the Licensor has authority to license.
|
||||||
|
|
||||||
|
j. Licensor means the individual(s) or entity(ies) granting rights
|
||||||
|
under this Public License.
|
||||||
|
|
||||||
|
k. NonCommercial means not primarily intended for or directed towards
|
||||||
|
commercial advantage or monetary compensation. For purposes of
|
||||||
|
this Public License, the exchange of the Licensed Material for
|
||||||
|
other material subject to Copyright and Similar Rights by digital
|
||||||
|
file-sharing or similar means is NonCommercial provided there is
|
||||||
|
no payment of monetary compensation in connection with the
|
||||||
|
exchange.
|
||||||
|
|
||||||
|
l. Share means to provide material to the public by any means or
|
||||||
|
process that requires permission under the Licensed Rights, such
|
||||||
|
as reproduction, public display, public performance, distribution,
|
||||||
|
dissemination, communication, or importation, and to make material
|
||||||
|
available to the public including in ways that members of the
|
||||||
|
public may access the material from a place and at a time
|
||||||
|
individually chosen by them.
|
||||||
|
|
||||||
|
m. Sui Generis Database Rights means rights other than copyright
|
||||||
|
resulting from Directive 96/9/EC of the European Parliament and of
|
||||||
|
the Council of 11 March 1996 on the legal protection of databases,
|
||||||
|
as amended and/or succeeded, as well as other essentially
|
||||||
|
equivalent rights anywhere in the world.
|
||||||
|
|
||||||
|
n. You means the individual or entity exercising the Licensed Rights
|
||||||
|
under this Public License. Your has a corresponding meaning.
|
||||||
|
|
||||||
|
|
||||||
|
Section 2 -- Scope.
|
||||||
|
|
||||||
|
a. License grant.
|
||||||
|
|
||||||
|
1. Subject to the terms and conditions of this Public License,
|
||||||
|
the Licensor hereby grants You a worldwide, royalty-free,
|
||||||
|
non-sublicensable, non-exclusive, irrevocable license to
|
||||||
|
exercise the Licensed Rights in the Licensed Material to:
|
||||||
|
|
||||||
|
a. reproduce and Share the Licensed Material, in whole or
|
||||||
|
in part, for NonCommercial purposes only; and
|
||||||
|
|
||||||
|
b. produce, reproduce, and Share Adapted Material for
|
||||||
|
NonCommercial purposes only.
|
||||||
|
|
||||||
|
2. Exceptions and Limitations. For the avoidance of doubt, where
|
||||||
|
Exceptions and Limitations apply to Your use, this Public
|
||||||
|
License does not apply, and You do not need to comply with
|
||||||
|
its terms and conditions.
|
||||||
|
|
||||||
|
3. Term. The term of this Public License is specified in Section
|
||||||
|
6(a).
|
||||||
|
|
||||||
|
4. Media and formats; technical modifications allowed. The
|
||||||
|
Licensor authorizes You to exercise the Licensed Rights in
|
||||||
|
all media and formats whether now known or hereafter created,
|
||||||
|
and to make technical modifications necessary to do so. The
|
||||||
|
Licensor waives and/or agrees not to assert any right or
|
||||||
|
authority to forbid You from making technical modifications
|
||||||
|
necessary to exercise the Licensed Rights, including
|
||||||
|
technical modifications necessary to circumvent Effective
|
||||||
|
Technological Measures. For purposes of this Public License,
|
||||||
|
simply making modifications authorized by this Section 2(a)
|
||||||
|
(4) never produces Adapted Material.
|
||||||
|
|
||||||
|
5. Downstream recipients.
|
||||||
|
|
||||||
|
a. Offer from the Licensor -- Licensed Material. Every
|
||||||
|
recipient of the Licensed Material automatically
|
||||||
|
receives an offer from the Licensor to exercise the
|
||||||
|
Licensed Rights under the terms and conditions of this
|
||||||
|
Public License.
|
||||||
|
|
||||||
|
b. Additional offer from the Licensor -- Adapted Material.
|
||||||
|
Every recipient of Adapted Material from You
|
||||||
|
automatically receives an offer from the Licensor to
|
||||||
|
exercise the Licensed Rights in the Adapted Material
|
||||||
|
under the conditions of the Adapter's License You apply.
|
||||||
|
|
||||||
|
c. No downstream restrictions. You may not offer or impose
|
||||||
|
any additional or different terms or conditions on, or
|
||||||
|
apply any Effective Technological Measures to, the
|
||||||
|
Licensed Material if doing so restricts exercise of the
|
||||||
|
Licensed Rights by any recipient of the Licensed
|
||||||
|
Material.
|
||||||
|
|
||||||
|
6. No endorsement. Nothing in this Public License constitutes or
|
||||||
|
may be construed as permission to assert or imply that You
|
||||||
|
are, or that Your use of the Licensed Material is, connected
|
||||||
|
with, or sponsored, endorsed, or granted official status by,
|
||||||
|
the Licensor or others designated to receive attribution as
|
||||||
|
provided in Section 3(a)(1)(A)(i).
|
||||||
|
|
||||||
|
b. Other rights.
|
||||||
|
|
||||||
|
1. Moral rights, such as the right of integrity, are not
|
||||||
|
licensed under this Public License, nor are publicity,
|
||||||
|
privacy, and/or other similar personality rights; however, to
|
||||||
|
the extent possible, the Licensor waives and/or agrees not to
|
||||||
|
assert any such rights held by the Licensor to the limited
|
||||||
|
extent necessary to allow You to exercise the Licensed
|
||||||
|
Rights, but not otherwise.
|
||||||
|
|
||||||
|
2. Patent and trademark rights are not licensed under this
|
||||||
|
Public License.
|
||||||
|
|
||||||
|
3. To the extent possible, the Licensor waives any right to
|
||||||
|
collect royalties from You for the exercise of the Licensed
|
||||||
|
Rights, whether directly or through a collecting society
|
||||||
|
under any voluntary or waivable statutory or compulsory
|
||||||
|
licensing scheme. In all other cases the Licensor expressly
|
||||||
|
reserves any right to collect such royalties, including when
|
||||||
|
the Licensed Material is used other than for NonCommercial
|
||||||
|
purposes.
|
||||||
|
|
||||||
|
|
||||||
|
Section 3 -- License Conditions.
|
||||||
|
|
||||||
|
Your exercise of the Licensed Rights is expressly made subject to the
|
||||||
|
following conditions.
|
||||||
|
|
||||||
|
a. Attribution.
|
||||||
|
|
||||||
|
1. If You Share the Licensed Material (including in modified
|
||||||
|
form), You must:
|
||||||
|
|
||||||
|
a. retain the following if it is supplied by the Licensor
|
||||||
|
with the Licensed Material:
|
||||||
|
|
||||||
|
i. identification of the creator(s) of the Licensed
|
||||||
|
Material and any others designated to receive
|
||||||
|
attribution, in any reasonable manner requested by
|
||||||
|
the Licensor (including by pseudonym if
|
||||||
|
designated);
|
||||||
|
|
||||||
|
ii. a copyright notice;
|
||||||
|
|
||||||
|
iii. a notice that refers to this Public License;
|
||||||
|
|
||||||
|
iv. a notice that refers to the disclaimer of
|
||||||
|
warranties;
|
||||||
|
|
||||||
|
v. a URI or hyperlink to the Licensed Material to the
|
||||||
|
extent reasonably practicable;
|
||||||
|
|
||||||
|
b. indicate if You modified the Licensed Material and
|
||||||
|
retain an indication of any previous modifications; and
|
||||||
|
|
||||||
|
c. indicate the Licensed Material is licensed under this
|
||||||
|
Public License, and include the text of, or the URI or
|
||||||
|
hyperlink to, this Public License.
|
||||||
|
|
||||||
|
2. You may satisfy the conditions in Section 3(a)(1) in any
|
||||||
|
reasonable manner based on the medium, means, and context in
|
||||||
|
which You Share the Licensed Material. For example, it may be
|
||||||
|
reasonable to satisfy the conditions by providing a URI or
|
||||||
|
hyperlink to a resource that includes the required
|
||||||
|
information.
|
||||||
|
3. If requested by the Licensor, You must remove any of the
|
||||||
|
information required by Section 3(a)(1)(A) to the extent
|
||||||
|
reasonably practicable.
|
||||||
|
|
||||||
|
b. ShareAlike.
|
||||||
|
|
||||||
|
In addition to the conditions in Section 3(a), if You Share
|
||||||
|
Adapted Material You produce, the following conditions also apply.
|
||||||
|
|
||||||
|
1. The Adapter's License You apply must be a Creative Commons
|
||||||
|
license with the same License Elements, this version or
|
||||||
|
later, or a BY-NC-SA Compatible License.
|
||||||
|
|
||||||
|
2. You must include the text of, or the URI or hyperlink to, the
|
||||||
|
Adapter's License You apply. You may satisfy this condition
|
||||||
|
in any reasonable manner based on the medium, means, and
|
||||||
|
context in which You Share Adapted Material.
|
||||||
|
|
||||||
|
3. You may not offer or impose any additional or different terms
|
||||||
|
or conditions on, or apply any Effective Technological
|
||||||
|
Measures to, Adapted Material that restrict exercise of the
|
||||||
|
rights granted under the Adapter's License You apply.
|
||||||
|
|
||||||
|
|
||||||
|
Section 4 -- Sui Generis Database Rights.
|
||||||
|
|
||||||
|
Where the Licensed Rights include Sui Generis Database Rights that
|
||||||
|
apply to Your use of the Licensed Material:
|
||||||
|
|
||||||
|
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
||||||
|
to extract, reuse, reproduce, and Share all or a substantial
|
||||||
|
portion of the contents of the database for NonCommercial purposes
|
||||||
|
only;
|
||||||
|
|
||||||
|
b. if You include all or a substantial portion of the database
|
||||||
|
contents in a database in which You have Sui Generis Database
|
||||||
|
Rights, then the database in which You have Sui Generis Database
|
||||||
|
Rights (but not its individual contents) is Adapted Material,
|
||||||
|
including for purposes of Section 3(b); and
|
||||||
|
|
||||||
|
c. You must comply with the conditions in Section 3(a) if You Share
|
||||||
|
all or a substantial portion of the contents of the database.
|
||||||
|
|
||||||
|
For the avoidance of doubt, this Section 4 supplements and does not
|
||||||
|
replace Your obligations under this Public License where the Licensed
|
||||||
|
Rights include other Copyright and Similar Rights.
|
||||||
|
|
||||||
|
|
||||||
|
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
||||||
|
|
||||||
|
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
||||||
|
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
||||||
|
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
||||||
|
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
||||||
|
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
||||||
|
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
||||||
|
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
||||||
|
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
||||||
|
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
||||||
|
|
||||||
|
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
||||||
|
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
||||||
|
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
||||||
|
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
||||||
|
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
||||||
|
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
||||||
|
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
||||||
|
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
||||||
|
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
||||||
|
|
||||||
|
c. The disclaimer of warranties and limitation of liability provided
|
||||||
|
above shall be interpreted in a manner that, to the extent
|
||||||
|
possible, most closely approximates an absolute disclaimer and
|
||||||
|
waiver of all liability.
|
||||||
|
|
||||||
|
|
||||||
|
Section 6 -- Term and Termination.
|
||||||
|
|
||||||
|
a. This Public License applies for the term of the Copyright and
|
||||||
|
Similar Rights licensed here. However, if You fail to comply with
|
||||||
|
this Public License, then Your rights under this Public License
|
||||||
|
terminate automatically.
|
||||||
|
|
||||||
|
b. Where Your right to use the Licensed Material has terminated under
|
||||||
|
Section 6(a), it reinstates:
|
||||||
|
|
||||||
|
1. automatically as of the date the violation is cured, provided
|
||||||
|
it is cured within 30 days of Your discovery of the
|
||||||
|
violation; or
|
||||||
|
|
||||||
|
2. upon express reinstatement by the Licensor.
|
||||||
|
|
||||||
|
For the avoidance of doubt, this Section 6(b) does not affect any
|
||||||
|
right the Licensor may have to seek remedies for Your violations
|
||||||
|
of this Public License.
|
||||||
|
|
||||||
|
c. For the avoidance of doubt, the Licensor may also offer the
|
||||||
|
Licensed Material under separate terms or conditions or stop
|
||||||
|
distributing the Licensed Material at any time; however, doing so
|
||||||
|
will not terminate this Public License.
|
||||||
|
|
||||||
|
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
||||||
|
License.
|
||||||
|
|
||||||
|
|
||||||
|
Section 7 -- Other Terms and Conditions.
|
||||||
|
|
||||||
|
a. The Licensor shall not be bound by any additional or different
|
||||||
|
terms or conditions communicated by You unless expressly agreed.
|
||||||
|
|
||||||
|
b. Any arrangements, understandings, or agreements regarding the
|
||||||
|
Licensed Material not stated herein are separate from and
|
||||||
|
independent of the terms and conditions of this Public License.
|
||||||
|
|
||||||
|
|
||||||
|
Section 8 -- Interpretation.
|
||||||
|
|
||||||
|
a. For the avoidance of doubt, this Public License does not, and
|
||||||
|
shall not be interpreted to, reduce, limit, restrict, or impose
|
||||||
|
conditions on any use of the Licensed Material that could lawfully
|
||||||
|
be made without permission under this Public License.
|
||||||
|
|
||||||
|
b. To the extent possible, if any provision of this Public License is
|
||||||
|
deemed unenforceable, it shall be automatically reformed to the
|
||||||
|
minimum extent necessary to make it enforceable. If the provision
|
||||||
|
cannot be reformed, it shall be severed from this Public License
|
||||||
|
without affecting the enforceability of the remaining terms and
|
||||||
|
conditions.
|
||||||
|
|
||||||
|
c. No term or condition of this Public License will be waived and no
|
||||||
|
failure to comply consented to unless expressly agreed to by the
|
||||||
|
Licensor.
|
||||||
|
|
||||||
|
d. Nothing in this Public License constitutes or may be interpreted
|
||||||
|
as a limitation upon, or waiver of, any privileges and immunities
|
||||||
|
that apply to the Licensor or You, including from the legal
|
||||||
|
processes of any jurisdiction or authority.
|
||||||
|
|
||||||
|
=======================================================================
|
||||||
|
|
||||||
|
Creative Commons is not a party to its public
|
||||||
|
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
||||||
|
its public licenses to material it publishes and in those instances
|
||||||
|
will be considered the “Licensor.” The text of the Creative Commons
|
||||||
|
public licenses is dedicated to the public domain under the CC0 Public
|
||||||
|
Domain Dedication. Except for the limited purpose of indicating that
|
||||||
|
material is shared under a Creative Commons public license or as
|
||||||
|
otherwise permitted by the Creative Commons policies published at
|
||||||
|
creativecommons.org/policies, Creative Commons does not authorize the
|
||||||
|
use of the trademark "Creative Commons" or any other trademark or logo
|
||||||
|
of Creative Commons without its prior written consent including,
|
||||||
|
without limitation, in connection with any unauthorized modifications
|
||||||
|
to any of its public licenses or any other arrangements,
|
||||||
|
understandings, or agreements concerning use of licensed material. For
|
||||||
|
the avoidance of doubt, this paragraph does not form part of the
|
||||||
|
public licenses.
|
||||||
|
|
||||||
|
Creative Commons may be contacted at creativecommons.org.
|
||||||
|
|||||||
@@ -2,164 +2,744 @@
|
|||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||

|
  [](https://creativecommons.org/licenses/by-nc-sa/4.0/) [](https://github.com/hacs/integration)
|
||||||

|
       
|
||||||

|
|
||||||

|
|
||||||
[](https://opensource.org/licenses/MIT)
|
|
||||||
|
|
||||||
|
|
||||||
|
<img src="https://github.com/smkrv/ha-text-ai/blob/main/custom_components/ha_text_ai/icons/logo%402x.png" alt="HA Text AI" style="width: 50%; max-width: 256px; max-height: 128px; aspect-ratio: 2/1; object-fit: contain;"/>
|
||||||
|
|
||||||
|
### Advanced AI Integration for [Home Assistant](https://www.home-assistant.io/) with LLM multi-provider support
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
Transform your smart home experience with powerful AI assistance powered by OpenAI's GPT models
|
Transform your smart home experience with powerful AI assistance powered by multiple AI providers including OpenAI GPT, DeepSeek and Anthropic Claude models. Get intelligent responses, automate complex scenarios, and enhance your home automation with advanced natural language processing.
|
||||||
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
> [!IMPORTANT]
|
||||||
|
> 🤝 Community Driven: for more details on the integration,
|
||||||
|
> check out the discussion on the **[Home Assistant Community forum](https://community.home-assistant.io/t/ha-text-ai-transforming-home-automation-through-multi-llm-integration/799741)**
|
||||||
|
>
|
||||||
|
> <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="210" height="auto"></a>
|
||||||
|
>
|
||||||
|
> [Screenshots](assets/images/screenshots/screenshot.jpg)
|
||||||
|
|
||||||
## 🌟 Features
|
## 🌟 Features
|
||||||
|
|
||||||
- 🧠 **Advanced AI Integration**: Leverage OpenAI's powerful models (GPT-3.5, GPT-4) for smart home interactions
|
- 🧠 **Multi-Provider AI Integration**: Support for OpenAI GPT, DeepSeek and Anthropic Claude models
|
||||||
- 💬 **Natural Language Control**: Control your home and get information using everyday language
|
- 💬 **Advanced Language Processing**: Context-aware, multi-turn conversations
|
||||||
- 📝 **Conversation Memory**: Maintain context with conversation history tracking
|
- 📝 **Enhanced Memory Management**: Secure file-based history storage
|
||||||
- ⚡ **Real-time Responses**: Get quick, contextual responses to your queries
|
- ⚡ **Performance Optimization**: Efficient token usage and smart rate limiting
|
||||||
- 🎯 **Customizable Behavior**: Fine-tune AI responses with adjustable parameters
|
- 🎯 **Advanced Customization**: Per-request model and parameter selection
|
||||||
- 🔒 **Secure Integration**: Your API key and data are handled securely
|
- 🔒 **Enhanced Security**: Secure API key management and usage monitoring
|
||||||
- 🎨 **Flexible Configuration**: Easy setup with multiple configuration options
|
- 🎨 **Improved User Experience**: Intuitive configuration and rich interfaces
|
||||||
- 🔄 **Automation Ready**: Integrate AI responses into your automations
|
- 🔄 **Automation Integration**: Event-driven responses and template compatibility
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>📦 Detailed Feature Breakdown</summary>
|
||||||
|
|
||||||
|
### 🧠 **Multi-Provider AI Integration**
|
||||||
|
- Support for OpenAI GPT models
|
||||||
|
- Anthropic Claude integration
|
||||||
|
- DeepSeek integration
|
||||||
|
- Custom API endpoints
|
||||||
|
- Flexible model selection
|
||||||
|
|
||||||
|
### 💬 **Advanced Language Processing**
|
||||||
|
- Context-aware responses
|
||||||
|
- Multi-turn conversations
|
||||||
|
- Custom system instructions
|
||||||
|
- Natural conversation flow
|
||||||
|
|
||||||
|
### 📝 **Enhanced Memory Management**
|
||||||
|
- File-based conversation history storage
|
||||||
|
- Automatic history rotation
|
||||||
|
- Configurable history size limits
|
||||||
|
- Secure storage in Home Assistant
|
||||||
|
|
||||||
|
### ⚡ **Performance Optimization**
|
||||||
|
- Efficient token usage
|
||||||
|
- Smart rate limiting
|
||||||
|
- Response caching
|
||||||
|
- Request interval control
|
||||||
|
|
||||||
|
### 🎯 **Advanced Customization**
|
||||||
|
- Per-request model selection
|
||||||
|
- Adjustable parameters
|
||||||
|
- Custom system prompts
|
||||||
|
- Temperature control
|
||||||
|
|
||||||
|
### 🔒 **Enhanced Security**
|
||||||
|
- Secure API key storage
|
||||||
|
- Rate limiting protection
|
||||||
|
- Error handling
|
||||||
|
- 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
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
#### 🌐 Translations
|
||||||
|
|
||||||
|
| Code | Language | Status |
|
||||||
|
|------|----------|--------|
|
||||||
|
| 🇩🇪 de | Deutsch | Full |
|
||||||
|
| 🇬🇧 en | English | Primary |
|
||||||
|
| 🇪🇸 es | Español | Full |
|
||||||
|
| 🇮🇳 hi | हिन्दी | Full |
|
||||||
|
| 🇮🇹 it | Italiano | Full |
|
||||||
|
| 🇷🇺 ru | Русский | Full |
|
||||||
|
| 🇷🇸 sr | Српски | Full |
|
||||||
|
| 🇨🇳 zh | 中文 | Full |
|
||||||
|
|
||||||
## 📋 Prerequisites
|
## 📋 Prerequisites
|
||||||
|
|
||||||
- Home Assistant installation (Core, OS, Container, or Supervised)
|
- Home Assistant 2024.12.0 or later (recommended for best compatibility)
|
||||||
- OpenAI API key ([Get one here](https://platform.openai.com/account/api-keys))
|
- Active API key from:
|
||||||
|
- OpenAI ([Get key](https://platform.openai.com/account/api-keys))
|
||||||
|
- Anthropic ([Get key](https://console.anthropic.com/))
|
||||||
|
- DeepSeek ([Get key](https://platform.deepseek.com/api_keys))
|
||||||
|
- OpenRouter ([Get key](https://openrouter.ai/keys))
|
||||||
|
- Google Gemini 🆕 ([Get key](https://ai.google.dev/gemini-api/docs/api-key)) thanks to ([@Azzedde](https://github.com/Azzedde))
|
||||||
|
- Any OpenAI-compatible API provider
|
||||||
- Python 3.9 or newer
|
- Python 3.9 or newer
|
||||||
|
- Stable internet connection
|
||||||
|
|
||||||
## ⚡ Quick Start
|
## Configuration Options
|
||||||
|
|
||||||
|
### 🔧 **Core Configuration Settings**
|
||||||
|
- 🌐 **API Provider**: OpenAI/Anthropic/DeepSeek/Gemini
|
||||||
|
- 🔑 **API Key**: Provider-specific authentication
|
||||||
|
- 🤖 **Model Selection**: Flexible, provider-specific models
|
||||||
|
- 🌡️ **Temperature**: Creativity control (0.0-2.0)
|
||||||
|
- 📏 **Max Tokens**: Response length limit (passed directly to the LLM API to control the maximum length of the response)
|
||||||
|
- ⏱️ **Request Interval**: API call throttling
|
||||||
|
- 💾 **History Size**: Number of messages to retain
|
||||||
|
- 🌍 **Custom API Endpoint**: Optional advanced configuration
|
||||||
|
|
||||||
|
### 🤖 **Recommended Models**
|
||||||
|
|
||||||
|
#### OpenAI Models
|
||||||
|
- **GPT-5** - The latest flagship model, best for complex reasoning
|
||||||
|
- **GPT-5 mini** - A cost-effective and fast model, suitable for most tasks
|
||||||
|
|
||||||
|
#### Anthropic Claude Models
|
||||||
|
- **Claude Opus 4.1** - The most capable model for handling complex tasks
|
||||||
|
- **Claude Sonnet 4** - Offers a balance between performance and cost
|
||||||
|
- **Claude Haiku 4** - The fastest and most economical option in the series
|
||||||
|
|
||||||
|
#### DeepSeek Models
|
||||||
|
- **DeepSeek-V3.1** - A general-purpose model for a wide range of tasks
|
||||||
|
- **DeepSeek-R1** - A specialized model focused on reasoning and coding
|
||||||
|
|
||||||
|
#### Google Gemini Models
|
||||||
|
- **Gemini 2.5 Pro & 2.5 Flash** - The newest and most advanced models available
|
||||||
|
- **Gemini 2.0 Pro & 2.0 Flash** - Previous generation models that are still powerful and efficient
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>🌐 Potentially Compatible Providers</summary>
|
||||||
|
|
||||||
|
#### Flexible Provider Ecosystem
|
||||||
|
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
|
||||||
|
|
||||||
|
#### 🚨 Compatibility 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
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
## ⚡ Installation
|
||||||
|
|
||||||
|
### HACS Installation (Recommended)
|
||||||
|
>[!TIP]
|
||||||
|
>HA Text AI is available in the default HACS repository. You can install it directly through HACS or click the button below to open it there.
|
||||||
|
|
||||||
|
<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 on "Integrations"
|
||||||
|
3. Search for "HA Text AI"
|
||||||
|
4. Click "Download"
|
||||||
|
5. Restart Home Assistant
|
||||||
|
|
||||||
|
**Alternative Method (Custom Repository):**
|
||||||
|
If the integration is not found in the default repository:
|
||||||
|
1. Click "..." in top right corner of HACS
|
||||||
|
2. Select "Custom repositories"
|
||||||
|
3. Add repository URL: `https://github.com/smkrv/ha-text-ai`
|
||||||
|
4. Choose "Integration" as category
|
||||||
|
5. Click "Download"
|
||||||
|
|
||||||
### Manual Installation
|
### Manual Installation
|
||||||
1. Download the repository
|
1. Download the latest release
|
||||||
2. Copy `custom_components/ha_text_ai` to your `custom_components` directory
|
2. Extract and copy `custom_components/ha_text_ai` to your `custom_components` directory
|
||||||
3. Restart Home Assistant
|
3. Restart Home Assistant
|
||||||
4. Add configuration to `configuration.yaml`:
|
4. Add configuration via UI or YAML
|
||||||
|
|
||||||
|
## ⚙️ Configuration
|
||||||
|
|
||||||
|
### Via UI (Recommended)
|
||||||
|
1. Go to Settings → Devices & Services
|
||||||
|
2. Click "Add Integration"
|
||||||
|
3. Search for "HA Text AI"
|
||||||
|
4. Follow the configuration steps
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>📦 Via YAML (Advanced)</summary>
|
||||||
|
|
||||||
|
### Platform Configuration (Global Settings)
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
ha_text_ai:
|
ha_text_ai:
|
||||||
api_key: !secret openai_api_key
|
api_provider: openai # Required
|
||||||
|
api_key: !secret ai_api_key # Required
|
||||||
|
model: gpt-4o # 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.
|
||||||
```
|
```
|
||||||
|
|
||||||
## ⚙️ Configuration Options
|
### Sensor Configuration
|
||||||
|
|
||||||
| Option | Type | Default | Description |
|
```yaml
|
||||||
|--------|------|---------|-------------|
|
sensor:
|
||||||
| `api_key` | string | Required | Your OpenAI API key |
|
- platform: ha_text_ai
|
||||||
| `model` | string | `gpt-3.5-turbo` | AI model to use |
|
name: "My AI Assistant" # Required, unique identifier
|
||||||
| `temperature` | float | `0.7` | Response creativity (0-2) |
|
api_provider: openai # Optional (inherits from platform)
|
||||||
| `max_tokens` | integer | `1000` | Maximum response length |
|
model: "gpt-4o" # Optional
|
||||||
| `request_interval` | float | `1.0` | Minimum seconds between requests |
|
temperature: 0.7 # Optional
|
||||||
| `api_endpoint` | string | OpenAI default | Custom API endpoint URL |
|
max_tokens: 1000 # Optional
|
||||||
|
```
|
||||||
|
|
||||||
|
### 📋 Configuration Parameters
|
||||||
|
|
||||||
|
#### Platform Configuration
|
||||||
|
|
||||||
|
| Parameter | Type | Required | Default | Description |
|
||||||
|
|-----------|------|----------|---------|-------------|
|
||||||
|
| `api_provider` | String | ✅ | - | AI service provider (openai, anthropic, deepseek, gemini) |
|
||||||
|
| `api_key` | String | ✅ | - | Authentication key for AI service |
|
||||||
|
| `model` | String | ⚠️ | gpt-4o-mini | Strongly recommended: Specific AI model to use. Default varies by provider |
|
||||||
|
| `temperature` | Float | ❌ | 0.1 | Response creativity level (0.0-2.0) |
|
||||||
|
| `max_tokens` | Integer | ❌ | 1000 | Maximum response length |
|
||||||
|
| `request_interval` | Float | ❌ | 1.0 | Delay between API requests |
|
||||||
|
| `api_endpoint` | URL | ⚠️ | Provider default | Custom API endpoint |
|
||||||
|
| `system_prompt` | String | ❌ | - | Default context for AI interactions |
|
||||||
|
| `max_history_size` | Integer | ❌ | 50 | Maximum number of conversation entries to store |
|
||||||
|
| `context_messages` | Integer | ❌ | 5 | Number of previous messages to include in context (1-20) |
|
||||||
|
|
||||||
|
#### 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 | ⚠️ | Provider default | Recommended: Override global model (gpt-4o-mini, deepseek-chat, gemini-2.0-flash) |
|
||||||
|
| `temperature` | Float | ❌ | 0.1 | Override global temperature |
|
||||||
|
| `max_tokens` | Integer | ❌ | 1000 | Override global max tokens |
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
## 🛠️ Available Services
|
## 🛠️ Available Services
|
||||||
|
|
||||||
|
### 🔄 Response Variables (New!)
|
||||||
|
|
||||||
|
**HA Text AI now supports response variables** - a powerful feature that returns AI responses directly from service calls, eliminating the need for separate text sensors and the 255-character limitation!
|
||||||
|
|
||||||
|
#### ✨ Key Benefits:
|
||||||
|
- **Unlimited response length** - No more 255-character truncation
|
||||||
|
- **Direct data access** - Get responses immediately in automations
|
||||||
|
- **Race condition prevention** - Eliminates conflicts in parallel automations
|
||||||
|
- **Simplified workflows** - No need to read from sensors
|
||||||
|
|
||||||
### ask_question
|
### ask_question
|
||||||
Ask the AI assistant a question:
|
|
||||||
```yaml
|
```yaml
|
||||||
service: ha_text_ai.ask_question
|
service: ha_text_ai.ask_question
|
||||||
data:
|
data:
|
||||||
question: "What's the optimal temperature for sleeping?"
|
question: "What's the optimal temperature for sleeping?"
|
||||||
model: "gpt-4" # optional
|
model: "claude-3.5-sonnet" # optional
|
||||||
temperature: 0.5 # optional
|
temperature: 0.5 # optional
|
||||||
max_tokens: 500 # optional
|
max_tokens: 500 # optional
|
||||||
|
context_messages: 10 #optional, number of previous messages to include in context, default: 5
|
||||||
|
system_prompt: "You are a sleep optimization expert" # optional
|
||||||
|
instance: sensor.ha_text_ai_gpt
|
||||||
|
response_variable: ai_response # NEW! Store response data directly
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 📊 Response Data Structure:
|
||||||
|
```yaml
|
||||||
|
# The service returns structured data:
|
||||||
|
response_text: "The optimal sleeping temperature is 65-68°F (18-20°C)..."
|
||||||
|
tokens_used: 150
|
||||||
|
prompt_tokens: 50
|
||||||
|
completion_tokens: 100
|
||||||
|
model_used: "claude-3.5-sonnet"
|
||||||
|
instance: "sensor.ha_text_ai_gpt"
|
||||||
|
question: "What's the optimal temperature for sleeping?"
|
||||||
|
timestamp: "2025-02-09T16:57:00.000Z"
|
||||||
|
success: true
|
||||||
|
# error: "Error message" (only present if success: false)
|
||||||
```
|
```
|
||||||
|
|
||||||
### set_system_prompt
|
### set_system_prompt
|
||||||
Configure AI behavior:
|
|
||||||
```yaml
|
```yaml
|
||||||
service: ha_text_ai.set_system_prompt
|
service: ha_text_ai.set_system_prompt
|
||||||
data:
|
data:
|
||||||
prompt: "You are a home automation expert focused on energy efficiency"
|
instance: sensor.ha_text_ai_gpt
|
||||||
|
prompt: |
|
||||||
|
You are a home automation expert focused on:
|
||||||
|
1. Energy efficiency
|
||||||
|
2. Comfort optimization
|
||||||
|
3. Security considerations
|
||||||
|
Provide practical, actionable advice.
|
||||||
```
|
```
|
||||||
|
|
||||||
### clear_history
|
### clear_history
|
||||||
Reset conversation history:
|
|
||||||
```yaml
|
```yaml
|
||||||
service: ha_text_ai.clear_history
|
service: ha_text_ai.clear_history
|
||||||
|
data:
|
||||||
|
instance: sensor.ha_text_ai_gpt
|
||||||
```
|
```
|
||||||
|
|
||||||
### get_history
|
### get_history
|
||||||
Retrieve conversation history:
|
|
||||||
```yaml
|
```yaml
|
||||||
service: ha_text_ai.get_history
|
service: ha_text_ai.get_history
|
||||||
data:
|
data:
|
||||||
limit: 5 # optional
|
limit: 5 # optional, number of conversations to return (1-100)
|
||||||
|
filter_model: "gpt-4o" # optional, filter by specific AI model
|
||||||
|
start_date: "2025-02-01" # optional, filter conversations from this date
|
||||||
|
include_metadata: false # optional, include tokens, response time, etc.
|
||||||
|
sort_order: "newest" # optional, sort order: "newest" or "oldest"
|
||||||
|
instance: sensor.ha_text_ai_gpt
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🔧 Practical Examples
|
## 🚀 Advanced Automation Examples with Response Variables
|
||||||
|
|
||||||
### Smart Temperature Management
|
### Example 1: Smart Home Advice with Direct Response
|
||||||
```yaml
|
```yaml
|
||||||
automation:
|
automation:
|
||||||
trigger:
|
- alias: "Get AI Home Advice"
|
||||||
platform: time_pattern
|
trigger:
|
||||||
hours: "/1"
|
- platform: state
|
||||||
action:
|
entity_id: input_button.ask_ai_advice
|
||||||
service: ha_text_ai.ask_question
|
action:
|
||||||
data:
|
- service: ha_text_ai.ask_question
|
||||||
question: >
|
data:
|
||||||
Current temperature is {{ states('sensor.living_room_temperature') }}°C.
|
question: "What's the best way to optimize energy usage in my home?"
|
||||||
Should I adjust the thermostat for optimal comfort and energy savings?
|
instance: sensor.ha_text_ai_gpt
|
||||||
|
response_variable: ai_advice
|
||||||
|
- service: notify.mobile_app
|
||||||
|
data:
|
||||||
|
title: "🏠 Smart Home Tip"
|
||||||
|
message: |
|
||||||
|
{{ ai_advice.response_text }}
|
||||||
|
|
||||||
|
📊 Tokens used: {{ ai_advice.tokens_used }}
|
||||||
|
🤖 Model: {{ ai_advice.model_used }}
|
||||||
```
|
```
|
||||||
|
|
||||||
### Smart Lighting Assistant
|
### Example 2: Weather-Based AI Recommendations
|
||||||
```yaml
|
```yaml
|
||||||
automation:
|
automation:
|
||||||
trigger:
|
- alias: "Weather-Based AI Suggestions"
|
||||||
platform: state
|
trigger:
|
||||||
entity_id: binary_sensor.living_room_motion
|
- platform: numeric_state
|
||||||
to: 'on'
|
entity_id: sensor.outdoor_temperature
|
||||||
condition:
|
below: 0
|
||||||
condition: template
|
action:
|
||||||
value_template: "{{ states('sensor.illuminance') | float < 10 }}"
|
- service: ha_text_ai.ask_question
|
||||||
action:
|
data:
|
||||||
service: ha_text_ai.ask_question
|
question: |
|
||||||
data:
|
The outdoor temperature is {{ states('sensor.outdoor_temperature') }}°C.
|
||||||
question: >
|
What should I do to prepare my home for freezing weather?
|
||||||
Motion detected in living room with low light levels.
|
system_prompt: "You are a home maintenance expert. Provide practical, actionable advice."
|
||||||
What's the best lighting scene to set based on the time of day?
|
instance: sensor.ha_text_ai_gpt
|
||||||
|
response_variable: winter_advice
|
||||||
|
- if:
|
||||||
|
- condition: template
|
||||||
|
value_template: "{{ winter_advice.success }}"
|
||||||
|
then:
|
||||||
|
- service: persistent_notification.create
|
||||||
|
data:
|
||||||
|
title: "❄️ Winter Preparation Advice"
|
||||||
|
message: |
|
||||||
|
{{ winter_advice.response_text }}
|
||||||
|
|
||||||
|
Generated at: {{ winter_advice.timestamp }}
|
||||||
|
else:
|
||||||
|
- service: persistent_notification.create
|
||||||
|
data:
|
||||||
|
title: "⚠️ AI Service Error"
|
||||||
|
message: "Failed to get winter advice: {{ winter_advice.error }}"
|
||||||
```
|
```
|
||||||
|
|
||||||
## ❗ Common Issues
|
### Example 3: Multi-Step AI Workflow
|
||||||
|
```yaml
|
||||||
|
automation:
|
||||||
|
- alias: "Multi-Step AI Analysis"
|
||||||
|
trigger:
|
||||||
|
- platform: state
|
||||||
|
entity_id: input_button.analyze_home_status
|
||||||
|
action:
|
||||||
|
# Step 1: Get current status analysis
|
||||||
|
- service: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
question: |
|
||||||
|
Current home status:
|
||||||
|
- Temperature: {{ states('sensor.indoor_temperature') }}°C
|
||||||
|
- Humidity: {{ states('sensor.indoor_humidity') }}%
|
||||||
|
- Energy usage: {{ states('sensor.power_consumption') }}W
|
||||||
|
|
||||||
### API Rate Limits
|
Analyze this data and provide insights.
|
||||||
- Increase `request_interval` if hitting rate limits
|
instance: sensor.ha_text_ai_gpt
|
||||||
- Consider upgrading your OpenAI plan
|
response_variable: status_analysis
|
||||||
- Use caching for frequent queries
|
|
||||||
|
|
||||||
### High Token Usage
|
# Step 2: Get recommendations based on analysis
|
||||||
- Reduce `max_tokens` parameter
|
- service: ha_text_ai.ask_question
|
||||||
- Clear conversation history regularly
|
data:
|
||||||
- Use focused system prompts
|
question: |
|
||||||
|
Based on this analysis: "{{ status_analysis.response_text[:500] }}"
|
||||||
|
|
||||||
### Connection Issues
|
Provide 3 specific actionable recommendations for improvement.
|
||||||
- Check internet connectivity
|
context_messages: 2 # Include previous conversation
|
||||||
- Verify API key validity
|
instance: sensor.ha_text_ai_gpt
|
||||||
- Ensure endpoint accessibility
|
response_variable: recommendations
|
||||||
|
|
||||||
|
# Step 3: Send comprehensive report
|
||||||
|
- service: notify.telegram
|
||||||
|
data:
|
||||||
|
title: "🏠 Home Analysis Report"
|
||||||
|
message: |
|
||||||
|
**Analysis:**
|
||||||
|
{{ status_analysis.response_text }}
|
||||||
|
|
||||||
|
**Recommendations:**
|
||||||
|
{{ recommendations.response_text }}
|
||||||
|
|
||||||
|
**Report Details:**
|
||||||
|
- Total tokens used: {{ status_analysis.tokens_used + recommendations.tokens_used }}
|
||||||
|
- Analysis model: {{ status_analysis.model_used }}
|
||||||
|
- Generated: {{ recommendations.timestamp }}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 💡 Migration from Sensors to Response Variables
|
||||||
|
|
||||||
|
#### Old Method (Limited):
|
||||||
|
```yaml
|
||||||
|
# ❌ Old way - limited to 255 characters, race conditions
|
||||||
|
automation:
|
||||||
|
- alias: "Old AI Response Method"
|
||||||
|
action:
|
||||||
|
- service: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
question: "Long question here..."
|
||||||
|
instance: sensor.ha_text_ai_gpt
|
||||||
|
- delay: "00:00:05" # Wait for sensor update
|
||||||
|
- service: notify.mobile
|
||||||
|
data:
|
||||||
|
message: "{{ state_attr('sensor.ha_text_ai_gpt', 'response')[:255] }}..." # Truncated!
|
||||||
|
```
|
||||||
|
|
||||||
|
#### New Method (Unlimited):
|
||||||
|
```yaml
|
||||||
|
# ✅ New way - unlimited length, immediate access, no race conditions
|
||||||
|
automation:
|
||||||
|
- alias: "New AI Response Method"
|
||||||
|
action:
|
||||||
|
- service: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
question: "Long question here..."
|
||||||
|
instance: sensor.ha_text_ai_gpt
|
||||||
|
response_variable: ai_response # Direct access!
|
||||||
|
- service: notify.mobile
|
||||||
|
data:
|
||||||
|
message: "{{ ai_response.response_text }}" # Full response, no truncation!
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🏷️ HA Text AI Sensor Naming Convention
|
||||||
|
|
||||||
|
#### Character Restrictions
|
||||||
|
- Only lowercase letters (a-z)
|
||||||
|
- Numbers (0-9)
|
||||||
|
- Underscore (_)
|
||||||
|
- Maximum length: 50 characters (including `ha_text_ai_`)
|
||||||
|
|
||||||
|
#### Sensor Name Structure
|
||||||
|
```yaml
|
||||||
|
# Always starts with 'sensor.ha_text_ai_'
|
||||||
|
# You define only the part after the underscore
|
||||||
|
sensor.ha_text_ai_YOUR_UNIQUE_SUFFIX
|
||||||
|
|
||||||
|
# Examples:
|
||||||
|
sensor.ha_text_ai_gpt # GPT-based sensor
|
||||||
|
sensor.ha_text_ai_claude # Claude-based sensor
|
||||||
|
sensor.ha_text_ai_abc # Custom suffix
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Response Retrieval
|
||||||
|
```yaml
|
||||||
|
# Use your specific sensor name
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'response') }}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Practical Usage
|
||||||
|
```yaml
|
||||||
|
automation:
|
||||||
|
- alias: "AI Response with Custom Sensor"
|
||||||
|
action:
|
||||||
|
- service: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
question: "Home automation advice"
|
||||||
|
instance: sensor.ha_text_ai_gpt
|
||||||
|
- service: notify.mobile
|
||||||
|
data:
|
||||||
|
message: >
|
||||||
|
AI Tip:
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'response') }}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 💡 Naming Rules
|
||||||
|
- Prefix is always `sensor.ha_text_ai_`
|
||||||
|
- Add your unique identifier after the underscore
|
||||||
|
- Use lowercase
|
||||||
|
- No spaces allowed
|
||||||
|
- Keep it descriptive but concise
|
||||||
|
|
||||||
|
### 🔍 HA Text AI Sensor Attributes
|
||||||
|
|
||||||
|
- 🤖 **Model and Provider Information**: Tracking current AI model and service provider
|
||||||
|
- 🚦 **System Status**: Real-time API and processing readiness
|
||||||
|
- 📊 **Performance Metrics**: Request success rates and response times
|
||||||
|
- 💬 **Conversation Tracking**: Token usage and interaction history are estimated using a heuristic method based on word count and specific word characteristics, which may differ from actual token usage.
|
||||||
|
- 🕒 **Last Interaction Details**: Recent query and response tracking
|
||||||
|
- ❤️ **System Health**: Error monitoring and service uptime
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>📦 Detailed Sensor Attributes</summary>
|
||||||
|
|
||||||
|
#### Model and Provider Information
|
||||||
|
```yaml
|
||||||
|
# Name of the AI model currently in use (e.g., latest version of GPT)
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Model') }} # gpt-4o
|
||||||
|
|
||||||
|
# Service provider for the AI model (determines API endpoint and authentication)
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Api provider') }} # openai
|
||||||
|
|
||||||
|
# Previous or alternative model configuration
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Last model') }} # gpt-4o
|
||||||
|
```
|
||||||
|
|
||||||
|
#### System Status
|
||||||
|
```yaml
|
||||||
|
# Current operational readiness of the AI service API
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Api status') }} # ready
|
||||||
|
|
||||||
|
# Indicates if a request is currently being processed
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Is processing') }} # false
|
||||||
|
|
||||||
|
# Shows if the API has hit its request rate limit
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Is rate limited') }} # false
|
||||||
|
|
||||||
|
# Status of the specific API endpoint being used
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Endpoint status') }} # ready
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Performance Metrics
|
||||||
|
```yaml
|
||||||
|
# Total number of successfully completed API requests
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Successful requests') }} # 0
|
||||||
|
|
||||||
|
# Number of API requests that encountered errors
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Failed requests') }} # 0
|
||||||
|
|
||||||
|
# Mean time taken to receive a response from the AI service
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Average latency') }} # 0
|
||||||
|
|
||||||
|
# Maximum time taken for a single request-response cycle
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Max latency') }} # 0
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Conversation and Token Usage
|
||||||
|
```yaml
|
||||||
|
# Number of previous interactions stored in conversation context
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'History size') }} # 0
|
||||||
|
|
||||||
|
# Total number of tokens used across all interactions
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Total tokens') }} # 0
|
||||||
|
|
||||||
|
# Tokens used in the input prompts
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Prompt tokens') }} # 0
|
||||||
|
|
||||||
|
# Tokens used in the AI's generated responses
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Completion tokens') }} # 0
|
||||||
|
|
||||||
|
# Number of entries in current history file
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'History size') }} # 0
|
||||||
|
|
||||||
|
# Last few conversation entries (limited to 1 for performance)
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'conversation_history') }} # [...]
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Last Interaction Details
|
||||||
|
```yaml
|
||||||
|
# Most recent complete response generated by the AI service
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Response') }} # Last AI response
|
||||||
|
|
||||||
|
# The most recently processed user query or prompt
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Question') }} # Last asked question
|
||||||
|
|
||||||
|
# Precise moment when the last interaction occurred (useful for tracking and logging)
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Last timestamp') }} # Timestamp
|
||||||
|
```
|
||||||
|
|
||||||
|
#### System Health
|
||||||
|
```yaml
|
||||||
|
# Cumulative count of all errors encountered during AI service interactions
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Total errors') }} # 0
|
||||||
|
|
||||||
|
# Indicates if the AI service is currently undergoing scheduled or emergency maintenance
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Is maintenance') }} # false
|
||||||
|
|
||||||
|
# Total continuous operational time of the AI service (in hours or days)
|
||||||
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Uptime') }} # 547,58
|
||||||
|
```
|
||||||
|
|
||||||
|
### History Storage
|
||||||
|
Conversation history stored in `.storage/ha_text_ai_history/` directory:
|
||||||
|
- Each instance has its own history file (JSON)
|
||||||
|
- Files are automatically rotated when size limit is reached
|
||||||
|
- Archived history files are timestamped
|
||||||
|
- Default maximum file size: 1MB
|
||||||
|
|
||||||
|
### 💡 Pro Tips
|
||||||
|
- Always check attribute existence
|
||||||
|
- Use these attributes for monitoring and automation
|
||||||
|
- Some values might be 0 or empty initially
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
## 📘 FAQ
|
||||||
|
|
||||||
|
**Q: Which AI providers are supported?**
|
||||||
|
A: OpenAI (GPT models), Anthropic (Claude models), DeepSeek, Google Gemini, and OpenRouter are officially supported, with many other OpenAI-compatible providers working as well.
|
||||||
|
|
||||||
|
**Q: How can I reduce API costs?**
|
||||||
|
A: Use gpt-4o-mini or claude-3.5-haiku for most queries, implement caching, and optimize token usage.
|
||||||
|
|
||||||
|
**Q: Are there limitations on the number of requests?**
|
||||||
|
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: What are the token limits for different models?**
|
||||||
|
A: Token limits vary by provider and model. OpenAI's gpt-4o supports up to 128K tokens, Claude 3.5 Sonnet supports up to 200K tokens, while smaller models typically have 8K-32K limits. Check your provider's documentation for specific limits.
|
||||||
|
|
||||||
|
**Q: How do I monitor token usage?**
|
||||||
|
A: Use the sensor attributes like `Total tokens`, `Prompt tokens`, and `Completion tokens` to track usage. You can also create automations to alert you when usage exceeds certain thresholds.
|
||||||
|
|
||||||
|
**Q: Is my data secure?**
|
||||||
|
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: 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.
|
||||||
|
|
||||||
|
**Q: Where is conversation history stored?**
|
||||||
|
A: History is stored in files under the `.storage/ha_text_ai_history/` directory, with automatic rotation and size management.
|
||||||
|
|
||||||
|
**Q: Can I access old conversation history?**
|
||||||
|
A: Yes, archived history files are stored with timestamps and can be accessed manually if needed.
|
||||||
|
|
||||||
|
**Q: How much history is kept?**
|
||||||
|
A: By default, up to 100 conversations are stored, but this can be configured. Files are automatically rotated when they reach 1MB.
|
||||||
|
|
||||||
## 🤝 Contributing
|
## 🤝 Contributing
|
||||||
|
|
||||||
Contributions are welcome! Please feel free to submit a Pull Request.
|
Contributions welcome! Please read our [Contributing Guide](CONTRIBUTING.md).
|
||||||
|
|
||||||
1. Fork the repository
|
1. Fork the repository
|
||||||
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
|
2. Create feature branch (`git checkout -b feature/Enhancement`)
|
||||||
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
|
3. Commit changes (`git commit -m 'Add Enhancement'`)
|
||||||
4. Push to the branch (`git push origin feature/AmazingFeature`)
|
4. Push branch (`git push origin feature/Enhancement`)
|
||||||
5. Open a Pull Request
|
5. Open Pull Request
|
||||||
|
|
||||||
|
## Legal Disclaimer and Limitation of Liability
|
||||||
|
|
||||||
|
### Software Disclaimer
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
||||||
|
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||||
|
|
||||||
|
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
|
||||||
|
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||||
|
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||||
|
DEALINGS IN THE SOFTWARE.
|
||||||
|
|
||||||
## 📝 License
|
## 📝 License
|
||||||
|
|
||||||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file 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"><img src="https://github.com/smkrv/ha-text-ai/blob/2aaf3405759eb2d97624834594e24ace896131df/assets/images/icons/footer_icon.png" alt="HA Text AI" style="width: 128px; height: auto;"/></div>
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
Made with ❤️ for the Home Assistant Community
|
Made with ❤️ for the Home Assistant Community
|
||||||
|
|
||||||
|
[Report Bug](https://github.com/smkrv/ha-text-ai/issues) · [Request Feature](https://github.com/smkrv/ha-text-ai/issues)
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
# Using response_variable with HA Text AI
|
||||||
|
|
||||||
|
After updating the HA Text AI integration, it now supports using the `response_variable` parameter in Home Assistant scripts and automations.
|
||||||
|
|
||||||
|
## What Changed
|
||||||
|
|
||||||
|
- Added response schema support in the `ha_text_ai.ask_question` service
|
||||||
|
- Service is now correctly registered with `supports_response=True` flag
|
||||||
|
- You can now use `response_variable` to capture AI response in a variable
|
||||||
|
|
||||||
|
## Example Usage in Script
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
action: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
context_messages: 0
|
||||||
|
temperature: 0.7
|
||||||
|
max_tokens: 1000
|
||||||
|
instance: sensor.ha_text_ai_gemini
|
||||||
|
question: "What time is it?"
|
||||||
|
response_variable: ai_response
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example Usage in Automation
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
alias: "Get AI Response"
|
||||||
|
trigger:
|
||||||
|
- platform: state
|
||||||
|
entity_id: input_boolean.ask_ai
|
||||||
|
to: "on"
|
||||||
|
action:
|
||||||
|
- action: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
instance: sensor.ha_text_ai_gemini
|
||||||
|
question: "What's the current weather?"
|
||||||
|
temperature: 0.7
|
||||||
|
max_tokens: 500
|
||||||
|
response_variable: weather_response
|
||||||
|
|
||||||
|
- action: notify.persistent_notification
|
||||||
|
data:
|
||||||
|
title: "AI Response"
|
||||||
|
message: "{{ weather_response.response_text }}"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Available Fields in response_variable
|
||||||
|
|
||||||
|
When you use `response_variable`, you will receive an object with the following fields:
|
||||||
|
|
||||||
|
- `response_text` (string) - The AI response text
|
||||||
|
- `tokens_used` (integer) - Total number of tokens used
|
||||||
|
- `prompt_tokens` (integer) - Number of tokens in the prompt
|
||||||
|
- `completion_tokens` (integer) - Number of tokens in the completion
|
||||||
|
- `model_used` (string) - The AI model that was used for the response
|
||||||
|
- `instance` (string) - The instance name that was used
|
||||||
|
- `question` (string) - The original question that was asked
|
||||||
|
- `timestamp` (string) - ISO timestamp when the response was generated
|
||||||
|
- `success` (boolean) - Whether the request was successful
|
||||||
|
- `error` (string) - Error message if the request failed
|
||||||
|
|
||||||
|
## Example Using Response Fields
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
action:
|
||||||
|
- action: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
instance: sensor.ha_text_ai_gemini
|
||||||
|
question: "Tell me a joke"
|
||||||
|
response_variable: joke_response
|
||||||
|
|
||||||
|
- condition: template
|
||||||
|
value_template: "{{ joke_response.success }}"
|
||||||
|
|
||||||
|
- action: input_text.set_value
|
||||||
|
target:
|
||||||
|
entity_id: input_text.last_ai_response
|
||||||
|
data:
|
||||||
|
value: "{{ joke_response.response_text }}"
|
||||||
|
|
||||||
|
- action: input_number.set_value
|
||||||
|
target:
|
||||||
|
entity_id: input_number.tokens_used
|
||||||
|
data:
|
||||||
|
value: "{{ joke_response.tokens_used }}"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
action:
|
||||||
|
- action: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
instance: sensor.ha_text_ai_gemini
|
||||||
|
question: "Test question"
|
||||||
|
response_variable: ai_result
|
||||||
|
|
||||||
|
- choose:
|
||||||
|
- conditions:
|
||||||
|
- condition: template
|
||||||
|
value_template: "{{ ai_result.success }}"
|
||||||
|
sequence:
|
||||||
|
- action: notify.mobile_app_phone
|
||||||
|
data:
|
||||||
|
title: "AI Response"
|
||||||
|
message: "{{ ai_result.response_text }}"
|
||||||
|
- conditions:
|
||||||
|
- condition: template
|
||||||
|
value_template: "{{ not ai_result.success }}"
|
||||||
|
sequence:
|
||||||
|
- action: notify.mobile_app_phone
|
||||||
|
data:
|
||||||
|
title: "AI Error"
|
||||||
|
message: "Error: {{ ai_result.error }}"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Migration from Old Approach
|
||||||
|
|
||||||
|
**Old method (without response_variable):**
|
||||||
|
```yaml
|
||||||
|
# Ask question
|
||||||
|
- action: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
instance: sensor.ha_text_ai_gemini
|
||||||
|
question: "Hello!"
|
||||||
|
|
||||||
|
# Wait and read response from sensor
|
||||||
|
- delay: 00:00:05
|
||||||
|
- action: notify.mobile_app_phone
|
||||||
|
data:
|
||||||
|
message: "{{ states('sensor.ha_text_ai_gemini') }}"
|
||||||
|
```
|
||||||
|
|
||||||
|
**New method (with response_variable):**
|
||||||
|
```yaml
|
||||||
|
# Ask question and get response immediately
|
||||||
|
- action: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
instance: sensor.ha_text_ai_gemini
|
||||||
|
question: "Hello!"
|
||||||
|
response_variable: greeting_response
|
||||||
|
|
||||||
|
- action: notify.mobile_app_phone
|
||||||
|
data:
|
||||||
|
message: "{{ greeting_response.response_text }}"
|
||||||
|
```
|
||||||
|
|
||||||
|
The new approach is more reliable as it doesn't require waiting and reading from the sensor.
|
||||||
|
After Width: | Height: | Size: 102 KiB |
|
After Width: | Height: | Size: 618 KiB |
|
After Width: | Height: | Size: 923 KiB |
|
After Width: | Height: | Size: 339 KiB |
|
After Width: | Height: | Size: 1.0 MiB |
@@ -1,205 +1,436 @@
|
|||||||
"""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
|
import logging
|
||||||
from typing import Any
|
import os
|
||||||
|
import shutil
|
||||||
|
import hashlib
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Any, Dict, TypeVar
|
||||||
|
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
|
from async_timeout import timeout
|
||||||
|
|
||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
from homeassistant.const import CONF_API_KEY
|
from homeassistant.const import CONF_API_KEY, CONF_NAME, Platform
|
||||||
from homeassistant.core import HomeAssistant, ServiceCall
|
from homeassistant.core import HomeAssistant, ServiceCall
|
||||||
import homeassistant.helpers.config_validation as cv
|
from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError
|
||||||
from homeassistant.exceptions import HomeAssistantError, ConfigEntryNotReady
|
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 (
|
from .const import (
|
||||||
DOMAIN,
|
DOMAIN,
|
||||||
PLATFORMS,
|
PLATFORMS,
|
||||||
SERVICE_ASK_QUESTION,
|
|
||||||
SERVICE_CLEAR_HISTORY,
|
|
||||||
SERVICE_GET_HISTORY,
|
|
||||||
SERVICE_SET_SYSTEM_PROMPT,
|
|
||||||
CONF_MODEL,
|
CONF_MODEL,
|
||||||
CONF_TEMPERATURE,
|
CONF_TEMPERATURE,
|
||||||
CONF_MAX_TOKENS,
|
CONF_MAX_TOKENS,
|
||||||
CONF_API_ENDPOINT,
|
CONF_API_ENDPOINT,
|
||||||
CONF_REQUEST_INTERVAL,
|
CONF_REQUEST_INTERVAL,
|
||||||
|
CONF_API_TIMEOUT,
|
||||||
|
CONF_API_PROVIDER,
|
||||||
|
CONF_CONTEXT_MESSAGES,
|
||||||
|
API_PROVIDER_OPENAI,
|
||||||
|
API_PROVIDER_ANTHROPIC,
|
||||||
|
API_PROVIDER_DEEPSEEK,
|
||||||
|
API_PROVIDER_GEMINI,
|
||||||
|
DEFAULT_MODEL,
|
||||||
|
DEFAULT_DEEPSEEK_MODEL,
|
||||||
|
DEFAULT_GEMINI_MODEL,
|
||||||
|
DEFAULT_TEMPERATURE,
|
||||||
|
DEFAULT_MAX_TOKENS,
|
||||||
|
DEFAULT_OPENAI_ENDPOINT,
|
||||||
|
DEFAULT_ANTHROPIC_ENDPOINT,
|
||||||
|
DEFAULT_DEEPSEEK_ENDPOINT,
|
||||||
|
DEFAULT_GEMINI_ENDPOINT,
|
||||||
|
DEFAULT_REQUEST_INTERVAL,
|
||||||
|
DEFAULT_API_TIMEOUT,
|
||||||
|
DEFAULT_CONTEXT_MESSAGES,
|
||||||
|
SERVICE_ASK_QUESTION,
|
||||||
|
SERVICE_CLEAR_HISTORY,
|
||||||
|
SERVICE_GET_HISTORY,
|
||||||
|
SERVICE_SET_SYSTEM_PROMPT,
|
||||||
|
DEFAULT_MAX_HISTORY,
|
||||||
|
CONF_MAX_HISTORY_SIZE,
|
||||||
|
ICONS_SUBDOMAIN,
|
||||||
)
|
)
|
||||||
from .coordinator import HATextAICoordinator
|
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
|
||||||
|
ConfigType = TypeVar("ConfigType", bound=Dict[str, Any])
|
||||||
|
|
||||||
CONFIG_SCHEMA = vol.Schema(
|
SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
|
||||||
{
|
vol.Required("instance"): cv.string,
|
||||||
DOMAIN: vol.Schema(
|
vol.Required("question"): cv.string,
|
||||||
{
|
vol.Optional("system_prompt"): cv.string,
|
||||||
vol.Required(CONF_API_KEY): cv.string,
|
vol.Optional("model"): cv.string,
|
||||||
vol.Optional(CONF_MODEL, default="gpt-3.5-turbo"): cv.string,
|
vol.Optional("temperature"): cv.positive_float,
|
||||||
vol.Optional(CONF_TEMPERATURE, default=0.7): vol.Coerce(float),
|
vol.Optional("max_tokens"): cv.positive_int,
|
||||||
vol.Optional(CONF_MAX_TOKENS, default=1000): vol.Coerce(int),
|
vol.Optional("context_messages"): cv.positive_int,
|
||||||
vol.Optional(CONF_REQUEST_INTERVAL, default=1.0): vol.Coerce(float),
|
vol.Optional("structured_output", default=False): cv.boolean,
|
||||||
vol.Optional(CONF_API_ENDPOINT): cv.string,
|
vol.Optional("json_schema"): cv.string,
|
||||||
}
|
})
|
||||||
)
|
|
||||||
},
|
|
||||||
extra=vol.ALLOW_EXTRA,
|
|
||||||
)
|
|
||||||
|
|
||||||
async def async_setup(hass: HomeAssistant, config: dict[str, Any]) -> bool:
|
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
|
||||||
"""Set up the HA text AI component."""
|
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,
|
||||||
|
vol.Optional("start_date"): cv.string,
|
||||||
|
vol.Optional("include_metadata"): cv.boolean,
|
||||||
|
vol.Optional("sort_order"): vol.In(["newest", "oldest"]),
|
||||||
|
})
|
||||||
|
|
||||||
|
def get_coordinator_by_instance(hass: HomeAssistant, instance: str) -> HATextAICoordinator:
|
||||||
|
"""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")
|
||||||
|
|
||||||
|
def get_file_hash(file_path: str) -> str:
|
||||||
|
"""Calculate SHA256 hash of file."""
|
||||||
|
sha256_hash = hashlib.sha256()
|
||||||
|
with open(file_path, "rb") as f:
|
||||||
|
for byte_block in iter(lambda: f.read(4096), b""):
|
||||||
|
sha256_hash.update(byte_block)
|
||||||
|
return sha256_hash.hexdigest()
|
||||||
|
|
||||||
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||||
|
"""Set up the Home Assistant Text AI component."""
|
||||||
|
# Initialize domain data storage
|
||||||
hass.data.setdefault(DOMAIN, {})
|
hass.data.setdefault(DOMAIN, {})
|
||||||
|
|
||||||
async def async_ask_question(call: ServiceCall) -> None:
|
async def async_ask_question(call: ServiceCall) -> dict:
|
||||||
"""Handle the ask_question service call."""
|
"""Handle ask_question service with response data."""
|
||||||
if not hass.data[DOMAIN]:
|
|
||||||
raise HomeAssistantError("No AI Text integration configured")
|
|
||||||
|
|
||||||
coordinator = next(iter(hass.data[DOMAIN].values()))
|
|
||||||
question = call.data["question"]
|
|
||||||
|
|
||||||
|
|
||||||
original_params = {
|
|
||||||
"model": coordinator.model,
|
|
||||||
"temperature": coordinator.temperature,
|
|
||||||
"max_tokens": coordinator.max_tokens
|
|
||||||
}
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
|
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||||
|
response = 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"),
|
||||||
|
structured_output=call.data.get("structured_output", False),
|
||||||
|
json_schema=call.data.get("json_schema"),
|
||||||
|
)
|
||||||
|
|
||||||
if "model" in call.data:
|
# Return structured response data
|
||||||
coordinator.model = call.data["model"]
|
return {
|
||||||
if "temperature" in call.data:
|
"response_text": response.get("content", ""),
|
||||||
coordinator.temperature = call.data["temperature"]
|
"tokens_used": response.get("tokens", {}).get("total", 0),
|
||||||
if "max_tokens" in call.data:
|
"prompt_tokens": response.get("tokens", {}).get("prompt", 0),
|
||||||
coordinator.max_tokens = call.data["max_tokens"]
|
"completion_tokens": response.get("tokens", {}).get("completion", 0),
|
||||||
|
"model_used": response.get("model", call.data.get("model", coordinator.model)),
|
||||||
await coordinator.async_ask_question(question)
|
"instance": call.data["instance"],
|
||||||
except Exception as ex:
|
"question": call.data["question"],
|
||||||
_LOGGER.error("Error asking question: %s", str(ex))
|
"timestamp": response.get("timestamp"),
|
||||||
raise HomeAssistantError(f"Failed to ask question: {str(ex)}") from ex
|
"success": True
|
||||||
finally:
|
}
|
||||||
|
except Exception as err:
|
||||||
coordinator.model = original_params["model"]
|
_LOGGER.error("Error asking question: %s", str(err))
|
||||||
coordinator.temperature = original_params["temperature"]
|
# Return error response
|
||||||
coordinator.max_tokens = original_params["max_tokens"]
|
return {
|
||||||
|
"response_text": "",
|
||||||
|
"tokens_used": 0,
|
||||||
|
"prompt_tokens": 0,
|
||||||
|
"completion_tokens": 0,
|
||||||
|
"model_used": call.data.get("model", ""),
|
||||||
|
"instance": call.data["instance"],
|
||||||
|
"question": call.data["question"],
|
||||||
|
"timestamp": datetime.now().isoformat(),
|
||||||
|
"success": False,
|
||||||
|
"error": str(err)
|
||||||
|
}
|
||||||
|
|
||||||
async def async_clear_history(call: ServiceCall) -> None:
|
async def async_clear_history(call: ServiceCall) -> None:
|
||||||
"""Handle the clear_history service call."""
|
"""Handle clear_history service."""
|
||||||
if not hass.data[DOMAIN]:
|
try:
|
||||||
raise HomeAssistantError("No AI Text integration configured")
|
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)}")
|
||||||
|
|
||||||
coordinator = next(iter(hass.data[DOMAIN].values()))
|
async def async_get_history(call: ServiceCall) -> list:
|
||||||
coordinator._responses.clear()
|
"""Handle get_history service."""
|
||||||
await coordinator.async_refresh()
|
try:
|
||||||
|
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||||
async def async_get_history(call: ServiceCall) -> dict[str, list]:
|
return await coordinator.async_get_history(
|
||||||
"""Handle the get_history service call."""
|
limit=call.data.get("limit"),
|
||||||
if not hass.data[DOMAIN]:
|
filter_model=call.data.get("filter_model"),
|
||||||
raise HomeAssistantError("No AI Text integration configured")
|
start_date=call.data.get("start_date"),
|
||||||
|
include_metadata=call.data.get("include_metadata", False),
|
||||||
coordinator = next(iter(hass.data[DOMAIN].values()))
|
sort_order=call.data.get("sort_order", "newest")
|
||||||
if not coordinator._responses:
|
)
|
||||||
return {"history": []}
|
except Exception as err:
|
||||||
|
_LOGGER.error("Error getting history: %s", str(err))
|
||||||
limit = call.data.get("limit", 10)
|
raise HomeAssistantError(f"Failed to get history: {str(err)}")
|
||||||
history = list(coordinator._responses.items())
|
|
||||||
limited_history = history[-limit:] if len(history) > limit else history
|
|
||||||
|
|
||||||
return {
|
|
||||||
"history": [
|
|
||||||
{"question": q, "response": r} for q, r in limited_history
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
async def async_set_system_prompt(call: ServiceCall) -> None:
|
async def async_set_system_prompt(call: ServiceCall) -> None:
|
||||||
"""Handle the set_system_prompt service call."""
|
"""Handle set_system_prompt service."""
|
||||||
if not hass.data[DOMAIN]:
|
try:
|
||||||
raise HomeAssistantError("No AI Text integration configured")
|
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||||
|
await coordinator.async_set_system_prompt(call.data["prompt"])
|
||||||
coordinator = next(iter(hass.data[DOMAIN].values()))
|
except Exception as err:
|
||||||
coordinator.system_prompt = call.data["prompt"]
|
_LOGGER.error("Error setting system prompt: %s", str(err))
|
||||||
|
raise HomeAssistantError(f"Failed to set system prompt: {str(err)}")
|
||||||
|
|
||||||
|
# Register services
|
||||||
hass.services.async_register(
|
hass.services.async_register(
|
||||||
DOMAIN,
|
DOMAIN,
|
||||||
SERVICE_ASK_QUESTION,
|
SERVICE_ASK_QUESTION,
|
||||||
async_ask_question,
|
async_ask_question,
|
||||||
schema=vol.Schema({
|
schema=SERVICE_SCHEMA_ASK_QUESTION,
|
||||||
vol.Required("question"): cv.string,
|
supports_response=True
|
||||||
vol.Optional("model"): cv.string,
|
|
||||||
vol.Optional("temperature"): vol.All(
|
|
||||||
vol.Coerce(float), vol.Range(min=0, max=2)
|
|
||||||
),
|
|
||||||
vol.Optional("max_tokens"): vol.All(
|
|
||||||
vol.Coerce(int), vol.Range(min=1, max=4096)
|
|
||||||
),
|
|
||||||
})
|
|
||||||
)
|
)
|
||||||
|
|
||||||
hass.services.async_register(
|
hass.services.async_register(
|
||||||
DOMAIN,
|
DOMAIN,
|
||||||
SERVICE_CLEAR_HISTORY,
|
SERVICE_CLEAR_HISTORY,
|
||||||
async_clear_history,
|
async_clear_history,
|
||||||
schema=vol.Schema({})
|
schema=vol.Schema({vol.Required("instance"): cv.string})
|
||||||
)
|
)
|
||||||
|
|
||||||
hass.services.async_register(
|
hass.services.async_register(
|
||||||
DOMAIN,
|
DOMAIN,
|
||||||
SERVICE_GET_HISTORY,
|
SERVICE_GET_HISTORY,
|
||||||
async_get_history,
|
async_get_history,
|
||||||
schema=vol.Schema({
|
schema=SERVICE_SCHEMA_GET_HISTORY
|
||||||
vol.Optional("limit", default=10): vol.All(
|
|
||||||
vol.Coerce(int), vol.Range(min=1)
|
|
||||||
),
|
|
||||||
})
|
|
||||||
)
|
)
|
||||||
|
|
||||||
hass.services.async_register(
|
hass.services.async_register(
|
||||||
DOMAIN,
|
DOMAIN,
|
||||||
SERVICE_SET_SYSTEM_PROMPT,
|
SERVICE_SET_SYSTEM_PROMPT,
|
||||||
async_set_system_prompt,
|
async_set_system_prompt,
|
||||||
schema=vol.Schema({
|
schema=SERVICE_SCHEMA_SET_SYSTEM_PROMPT
|
||||||
vol.Required("prompt"): cv.string,
|
|
||||||
})
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Handle icons
|
||||||
|
try:
|
||||||
|
source_icon_path = os.path.join(
|
||||||
|
os.path.dirname(__file__),
|
||||||
|
ICONS_SUBDOMAIN,
|
||||||
|
'icon@2x.png'
|
||||||
|
)
|
||||||
|
|
||||||
|
destination_directory = os.path.join(
|
||||||
|
hass.config.path('www'),
|
||||||
|
DOMAIN,
|
||||||
|
ICONS_SUBDOMAIN
|
||||||
|
)
|
||||||
|
|
||||||
|
destination_icon_path = os.path.join(
|
||||||
|
destination_directory,
|
||||||
|
'icon.png'
|
||||||
|
)
|
||||||
|
|
||||||
|
if not os.path.exists(source_icon_path):
|
||||||
|
_LOGGER.error("Source icon not found: %s", source_icon_path)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def create_directory():
|
||||||
|
os.makedirs(destination_directory, exist_ok=True)
|
||||||
|
|
||||||
|
await hass.async_add_executor_job(create_directory)
|
||||||
|
|
||||||
|
should_copy = True
|
||||||
|
|
||||||
|
if os.path.exists(destination_icon_path):
|
||||||
|
source_hash = await hass.async_add_executor_job(get_file_hash, source_icon_path)
|
||||||
|
dest_hash = await hass.async_add_executor_job(get_file_hash, destination_icon_path)
|
||||||
|
should_copy = source_hash != dest_hash
|
||||||
|
|
||||||
|
if should_copy:
|
||||||
|
def copy_file():
|
||||||
|
shutil.copyfile(source_icon_path, destination_icon_path)
|
||||||
|
|
||||||
|
await hass.async_add_executor_job(copy_file)
|
||||||
|
_LOGGER.debug("Icon updated: %s", destination_icon_path)
|
||||||
|
|
||||||
|
except PermissionError as e:
|
||||||
|
_LOGGER.error("Permission denied when managing icons: %s", str(e))
|
||||||
|
except Exception as e:
|
||||||
|
_LOGGER.error("Failed to manage icons: %s", str(e))
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
async def async_check_api(session, endpoint: str, headers: dict, provider: str, api_timeout: int = DEFAULT_API_TIMEOUT) -> bool:
|
||||||
"""Set up HA text AI from a config entry."""
|
"""Check API availability for different providers."""
|
||||||
try:
|
try:
|
||||||
coordinator = HATextAICoordinator(
|
if provider == API_PROVIDER_GEMINI:
|
||||||
hass,
|
# Gemini API does not support GET /models for validation, just check key presence
|
||||||
api_key=entry.data[CONF_API_KEY],
|
if headers.get("Authorization", "").replace("Bearer ", ""):
|
||||||
endpoint=entry.data.get(CONF_API_ENDPOINT),
|
return True
|
||||||
model=entry.data.get(CONF_MODEL),
|
else:
|
||||||
temperature=entry.data.get(CONF_TEMPERATURE),
|
_LOGGER.error("Gemini API key is missing or empty")
|
||||||
max_tokens=entry.data.get(CONF_MAX_TOKENS),
|
return False
|
||||||
request_interval=entry.data.get(CONF_REQUEST_INTERVAL),
|
elif provider == API_PROVIDER_ANTHROPIC:
|
||||||
|
check_url = f"{endpoint}/v1/models"
|
||||||
|
elif provider == API_PROVIDER_DEEPSEEK:
|
||||||
|
check_url = f"{endpoint}/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:
|
||||||
|
_LOGGER.error("Invalid API key")
|
||||||
|
return False
|
||||||
|
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:
|
||||||
|
# Get provider from data or options (options takes precedence)
|
||||||
|
config = {**entry.data, **entry.options}
|
||||||
|
api_provider = config.get(CONF_API_PROVIDER)
|
||||||
|
|
||||||
|
if not api_provider:
|
||||||
|
_LOGGER.error("API provider not specified")
|
||||||
|
raise ConfigEntryNotReady("API provider is required")
|
||||||
|
|
||||||
|
session = aiohttp_client.async_get_clientsession(hass)
|
||||||
|
|
||||||
|
# Get default endpoint based on provider
|
||||||
|
default_endpoint = {
|
||||||
|
API_PROVIDER_OPENAI: DEFAULT_OPENAI_ENDPOINT,
|
||||||
|
API_PROVIDER_ANTHROPIC: DEFAULT_ANTHROPIC_ENDPOINT,
|
||||||
|
API_PROVIDER_DEEPSEEK: DEFAULT_DEEPSEEK_ENDPOINT,
|
||||||
|
API_PROVIDER_GEMINI: DEFAULT_GEMINI_ENDPOINT,
|
||||||
|
}.get(api_provider, DEFAULT_OPENAI_ENDPOINT)
|
||||||
|
|
||||||
|
# Get default model based on provider
|
||||||
|
default_model = (
|
||||||
|
DEFAULT_DEEPSEEK_MODEL if api_provider == API_PROVIDER_DEEPSEEK else
|
||||||
|
DEFAULT_GEMINI_MODEL if api_provider == API_PROVIDER_GEMINI else
|
||||||
|
DEFAULT_MODEL
|
||||||
)
|
)
|
||||||
|
|
||||||
await coordinator.async_config_entry_first_refresh()
|
model = config.get(CONF_MODEL, default_model)
|
||||||
|
endpoint = config.get(CONF_API_ENDPOINT, default_endpoint).rstrip('/')
|
||||||
|
# API key can now be updated via options
|
||||||
|
api_key = config.get(CONF_API_KEY, entry.data.get(CONF_API_KEY))
|
||||||
|
instance_name = entry.data.get(CONF_NAME, entry.entry_id)
|
||||||
|
request_interval = config.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
||||||
|
api_timeout = config.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)
|
||||||
|
max_tokens = config.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
||||||
|
temperature = config.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
||||||
|
max_history_size = config.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
|
||||||
|
context_messages = config.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
|
||||||
|
is_anthropic = api_provider == API_PROVIDER_ANTHROPIC
|
||||||
|
|
||||||
|
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, api_timeout):
|
||||||
|
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,
|
||||||
|
api_timeout=api_timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
coordinator = HATextAICoordinator(
|
||||||
|
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,
|
||||||
|
api_timeout=api_timeout,
|
||||||
|
)
|
||||||
|
|
||||||
|
_LOGGER.debug(f"Created coordinator for {instance_name}")
|
||||||
|
|
||||||
|
# Store coordinator
|
||||||
|
hass.data.setdefault(DOMAIN, {})
|
||||||
hass.data[DOMAIN][entry.entry_id] = coordinator
|
hass.data[DOMAIN][entry.entry_id] = coordinator
|
||||||
|
|
||||||
return await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
_LOGGER.debug(f"Stored coordinator in hass.data[{DOMAIN}][{entry.entry_id}]")
|
||||||
except Exception as ex:
|
|
||||||
raise ConfigEntryNotReady(f"Failed to setup entry: {str(ex)}") from ex
|
# Set up platforms
|
||||||
|
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||||
|
|
||||||
|
# Register update listener for options changes
|
||||||
|
entry.async_on_unload(entry.add_update_listener(async_update_options))
|
||||||
|
|
||||||
|
_LOGGER.debug(f"Setup completed for {instance_name}")
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as err:
|
||||||
|
_LOGGER.exception(f"Error setting up HA Text AI: {err}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
async def async_update_options(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||||
|
"""Handle options update - reload the config entry."""
|
||||||
|
_LOGGER.info("Options updated for %s, reloading integration", entry.title)
|
||||||
|
await hass.config_entries.async_reload(entry.entry_id)
|
||||||
|
|
||||||
|
|
||||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||||
"""Unload a config entry."""
|
"""Unload a config entry."""
|
||||||
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
try:
|
||||||
if unload_ok:
|
if entry.entry_id in hass.data[DOMAIN]:
|
||||||
hass.data[DOMAIN].pop(entry.entry_id)
|
coordinator = hass.data[DOMAIN][entry.entry_id]
|
||||||
|
|
||||||
|
if hasattr(coordinator.client, 'shutdown'):
|
||||||
|
await coordinator.client.shutdown()
|
||||||
|
|
||||||
if not hass.data[DOMAIN]:
|
await coordinator.async_shutdown()
|
||||||
services = [
|
hass.data[DOMAIN].pop(entry.entry_id)
|
||||||
SERVICE_ASK_QUESTION,
|
|
||||||
SERVICE_CLEAR_HISTORY,
|
|
||||||
SERVICE_GET_HISTORY,
|
|
||||||
SERVICE_SET_SYSTEM_PROMPT
|
|
||||||
]
|
|
||||||
for service in services:
|
|
||||||
if service in hass.services.async_services().get(DOMAIN, {}):
|
|
||||||
hass.services.async_remove(DOMAIN, service)
|
|
||||||
|
|
||||||
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
|
||||||
|
|||||||
@@ -0,0 +1,492 @@
|
|||||||
|
"""
|
||||||
|
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 datetime import datetime, timedelta
|
||||||
|
|
||||||
|
from homeassistant.core import HomeAssistant
|
||||||
|
from homeassistant.exceptions import HomeAssistantError
|
||||||
|
from .const import (
|
||||||
|
DEFAULT_API_TIMEOUT,
|
||||||
|
API_RETRY_COUNT,
|
||||||
|
API_PROVIDER_ANTHROPIC,
|
||||||
|
API_PROVIDER_DEEPSEEK,
|
||||||
|
API_PROVIDER_OPENAI,
|
||||||
|
API_PROVIDER_GEMINI,
|
||||||
|
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,
|
||||||
|
api_timeout: int = DEFAULT_API_TIMEOUT,
|
||||||
|
) -> None:
|
||||||
|
"""Initialize API client."""
|
||||||
|
self.session = session
|
||||||
|
self.endpoint = endpoint
|
||||||
|
self.headers = headers
|
||||||
|
self.api_provider = api_provider
|
||||||
|
self.model = model
|
||||||
|
self.api_timeout = api_timeout
|
||||||
|
self.timeout = ClientTimeout(total=api_timeout)
|
||||||
|
self._closed = False
|
||||||
|
|
||||||
|
async def __aenter__(self):
|
||||||
|
"""Async context manager entry."""
|
||||||
|
return self
|
||||||
|
|
||||||
|
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||||
|
"""Async context manager exit."""
|
||||||
|
await self.shutdown()
|
||||||
|
|
||||||
|
def _validate_parameters(
|
||||||
|
self,
|
||||||
|
temperature: float,
|
||||||
|
max_tokens: int,
|
||||||
|
) -> None:
|
||||||
|
"""Validate API parameters with enhanced type checking."""
|
||||||
|
# Type validation
|
||||||
|
if not isinstance(temperature, (int, float)):
|
||||||
|
raise TypeError(f"Temperature must be a number, got {type(temperature)}")
|
||||||
|
if not isinstance(max_tokens, int):
|
||||||
|
raise TypeError(f"Max tokens must be an integer, got {type(max_tokens)}")
|
||||||
|
|
||||||
|
# Range validation
|
||||||
|
if not MIN_TEMPERATURE <= temperature <= MAX_TEMPERATURE:
|
||||||
|
raise ValueError(
|
||||||
|
f"Temperature must be between {MIN_TEMPERATURE} and {MAX_TEMPERATURE}, got {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}, got {max_tokens}"
|
||||||
|
)
|
||||||
|
|
||||||
|
async def _make_request(
|
||||||
|
self,
|
||||||
|
url: str,
|
||||||
|
payload: Dict[str, Any],
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""Make API request with retry logic."""
|
||||||
|
# Log request without sensitive data
|
||||||
|
safe_payload = {k: v for k, v in payload.items() if k not in ['messages', 'system']}
|
||||||
|
_LOGGER.debug(f"API Request: URL={url}, Safe payload: {safe_payload}")
|
||||||
|
|
||||||
|
for attempt in range(API_RETRY_COUNT):
|
||||||
|
try:
|
||||||
|
async with timeout(self.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()
|
||||||
|
# Log error without sensitive data
|
||||||
|
safe_error = {k: v for k, v in error_data.items() if k not in ['message', 'details']}
|
||||||
|
_LOGGER.error(f"API error (status {response.status}): {safe_error}")
|
||||||
|
raise HomeAssistantError(f"API error: status {response.status}")
|
||||||
|
return await response.json()
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
_LOGGER.warning(f"Timeout on attempt {attempt + 1}/{API_RETRY_COUNT}")
|
||||||
|
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}/{API_RETRY_COUNT}: {type(e).__name__}")
|
||||||
|
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,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
|
) -> 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,
|
||||||
|
structured_output, json_schema
|
||||||
|
)
|
||||||
|
elif self.api_provider == API_PROVIDER_DEEPSEEK:
|
||||||
|
return await self._create_deepseek_completion(
|
||||||
|
model, messages, temperature, max_tokens,
|
||||||
|
structured_output, json_schema
|
||||||
|
)
|
||||||
|
elif self.api_provider == API_PROVIDER_GEMINI:
|
||||||
|
return await self._create_gemini_completion(
|
||||||
|
model, messages, temperature, max_tokens,
|
||||||
|
structured_output, json_schema
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
return await self._create_openai_completion(
|
||||||
|
model, messages, temperature, max_tokens,
|
||||||
|
structured_output, json_schema
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
_LOGGER.error("API request failed: %s", str(e))
|
||||||
|
raise HomeAssistantError(f"API request failed: {str(e)}")
|
||||||
|
|
||||||
|
async def _create_deepseek_completion(
|
||||||
|
self,
|
||||||
|
model: str,
|
||||||
|
messages: List[Dict[str, str]],
|
||||||
|
temperature: float,
|
||||||
|
max_tokens: int,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""Create completion using DeepSeek API."""
|
||||||
|
url = f"{self.endpoint}/chat/completions"
|
||||||
|
payload = {
|
||||||
|
"model": model,
|
||||||
|
"messages": messages,
|
||||||
|
"temperature": temperature,
|
||||||
|
"max_tokens": max_tokens,
|
||||||
|
"stream": False
|
||||||
|
}
|
||||||
|
|
||||||
|
# Add structured output format if enabled (DeepSeek is OpenAI-compatible)
|
||||||
|
if structured_output and json_schema:
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
schema = json.loads(json_schema)
|
||||||
|
payload["response_format"] = {
|
||||||
|
"type": "json_schema",
|
||||||
|
"json_schema": {
|
||||||
|
"name": "structured_response",
|
||||||
|
"strict": True,
|
||||||
|
"schema": schema
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_LOGGER.debug("DeepSeek structured output enabled with schema")
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
_LOGGER.warning(f"Invalid JSON schema provided: {e}. Falling back to json_object mode.")
|
||||||
|
payload["response_format"] = {"type": "json_object"}
|
||||||
|
|
||||||
|
data = await self._make_request(url, payload)
|
||||||
|
return {
|
||||||
|
"choices": [
|
||||||
|
{
|
||||||
|
"message": {"content": data["choices"][0]["message"]["content"]},
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"usage": {
|
||||||
|
"prompt_tokens": data["usage"]["prompt_tokens"],
|
||||||
|
"completion_tokens": data["usage"]["completion_tokens"],
|
||||||
|
"total_tokens": data["usage"]["total_tokens"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
async def _create_openai_completion(
|
||||||
|
self,
|
||||||
|
model: str,
|
||||||
|
messages: List[Dict[str, str]],
|
||||||
|
temperature: float,
|
||||||
|
max_tokens: int,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
|
) -> 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,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Add structured output format if enabled
|
||||||
|
if structured_output and json_schema:
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
schema = json.loads(json_schema)
|
||||||
|
payload["response_format"] = {
|
||||||
|
"type": "json_schema",
|
||||||
|
"json_schema": {
|
||||||
|
"name": "structured_response",
|
||||||
|
"strict": True,
|
||||||
|
"schema": schema
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_LOGGER.debug("OpenAI structured output enabled with schema")
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
_LOGGER.warning(f"Invalid JSON schema provided: {e}. Falling back to json_object mode.")
|
||||||
|
payload["response_format"] = {"type": "json_object"}
|
||||||
|
|
||||||
|
data = await self._make_request(url, payload)
|
||||||
|
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,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
|
) -> 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)
|
||||||
|
|
||||||
|
# For Anthropic, add structured output instruction to system prompt
|
||||||
|
if structured_output and json_schema:
|
||||||
|
schema_instruction = (
|
||||||
|
f"\n\nIMPORTANT: You MUST respond ONLY with valid JSON that matches "
|
||||||
|
f"this JSON Schema:\n{json_schema}\n"
|
||||||
|
f"Do not include any text before or after the JSON. "
|
||||||
|
f"Do not wrap the JSON in markdown code blocks."
|
||||||
|
)
|
||||||
|
if system_prompt:
|
||||||
|
system_prompt += schema_instruction
|
||||||
|
else:
|
||||||
|
system_prompt = schema_instruction.strip()
|
||||||
|
_LOGGER.debug("Anthropic structured output enabled via system prompt")
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"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 _create_gemini_completion(
|
||||||
|
self,
|
||||||
|
model: str,
|
||||||
|
messages: List[Dict[str, str]],
|
||||||
|
temperature: float,
|
||||||
|
max_tokens: int,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""Create completion using Gemini API with google-genai library.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
model: The model name to use
|
||||||
|
messages: List of message dictionaries with role and content
|
||||||
|
temperature: Sampling temperature between 0.0 and 2.0
|
||||||
|
max_tokens: Maximum number of tokens to generate
|
||||||
|
structured_output: Enable JSON structured output mode
|
||||||
|
json_schema: JSON Schema for structured output validation
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dictionary with response content and token usage
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
def import_genai():
|
||||||
|
from google import genai
|
||||||
|
return genai
|
||||||
|
|
||||||
|
genai = await asyncio.to_thread(import_genai)
|
||||||
|
|
||||||
|
# Extract API key from headers (Bearer token)
|
||||||
|
api_key = self.headers.get("Authorization", "").replace("Bearer ", "")
|
||||||
|
|
||||||
|
def create_client():
|
||||||
|
if self.endpoint and self.endpoint != "https://generativelanguage.googleapis.com/v1beta":
|
||||||
|
return genai.Client(api_key=api_key, transport="rest",
|
||||||
|
client_options={"api_endpoint": self.endpoint})
|
||||||
|
else:
|
||||||
|
return genai.Client(api_key=api_key)
|
||||||
|
|
||||||
|
client = await asyncio.to_thread(create_client)
|
||||||
|
|
||||||
|
# Process messages to extract system instruction and chat history
|
||||||
|
system_instruction = ""
|
||||||
|
contents = []
|
||||||
|
|
||||||
|
for msg in messages:
|
||||||
|
if msg['role'] == 'system':
|
||||||
|
system_instruction += msg['content'] + "\n"
|
||||||
|
else:
|
||||||
|
# For chat history, we need to convert to the format Gemini expects
|
||||||
|
role = "user" if msg['role'] == 'user' else "model"
|
||||||
|
contents.append({
|
||||||
|
"role": role,
|
||||||
|
"parts": [{"text": msg['content']}]
|
||||||
|
})
|
||||||
|
|
||||||
|
# Parse JSON schema if structured output is enabled
|
||||||
|
parsed_schema = None
|
||||||
|
if structured_output and json_schema:
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
parsed_schema = json.loads(json_schema)
|
||||||
|
_LOGGER.debug("Gemini structured output enabled with schema")
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
_LOGGER.warning(f"Invalid JSON schema provided: {e}. Structured output disabled.")
|
||||||
|
|
||||||
|
# Create configuration
|
||||||
|
def create_config():
|
||||||
|
from google.genai import types
|
||||||
|
config = types.GenerateContentConfig(
|
||||||
|
temperature=temperature,
|
||||||
|
max_output_tokens=max_tokens,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Add system instruction if present
|
||||||
|
if system_instruction:
|
||||||
|
config.system_instruction = system_instruction.strip()
|
||||||
|
|
||||||
|
# Add structured output configuration for Gemini
|
||||||
|
if structured_output and parsed_schema:
|
||||||
|
config.response_mime_type = "application/json"
|
||||||
|
config.response_schema = parsed_schema
|
||||||
|
|
||||||
|
return config
|
||||||
|
|
||||||
|
config = await asyncio.to_thread(create_config)
|
||||||
|
|
||||||
|
def generate_content():
|
||||||
|
# For single message without history, use generate_content
|
||||||
|
if len(contents) <= 1:
|
||||||
|
# If we have no content yet, create a simple prompt
|
||||||
|
if not contents:
|
||||||
|
prompt = "I need your assistance."
|
||||||
|
else:
|
||||||
|
prompt = contents[0]["parts"][0]["text"]
|
||||||
|
|
||||||
|
return client.models.generate_content(
|
||||||
|
model=model,
|
||||||
|
contents=prompt,
|
||||||
|
config=config
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# For multi-turn conversations, use chat
|
||||||
|
chat = client.chats.create(model=model, config=config)
|
||||||
|
|
||||||
|
# Send all messages in sequence
|
||||||
|
for content in contents:
|
||||||
|
if content["role"] == "user":
|
||||||
|
response = chat.send_message(content["parts"][0]["text"])
|
||||||
|
# We don't send assistant messages as they're already part of the history
|
||||||
|
|
||||||
|
return response
|
||||||
|
|
||||||
|
response = await asyncio.to_thread(generate_content)
|
||||||
|
|
||||||
|
# Extract response text
|
||||||
|
def extract_response():
|
||||||
|
response_text = response.text if hasattr(response, 'text') else ""
|
||||||
|
|
||||||
|
# Try to get token usage if available
|
||||||
|
usage = {}
|
||||||
|
if hasattr(response, 'usage_metadata'):
|
||||||
|
usage = {
|
||||||
|
"prompt_tokens": getattr(response.usage_metadata, 'prompt_token_count', 0),
|
||||||
|
"completion_tokens": getattr(response.usage_metadata, 'candidates_token_count', 0),
|
||||||
|
"total_tokens": getattr(response.usage_metadata, 'total_token_count', 0)
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
# Estimate token count as fallback
|
||||||
|
usage = {
|
||||||
|
"prompt_tokens": len(" ".join([m["content"] for m in messages]).split()) // 3,
|
||||||
|
"completion_tokens": len(response_text.split()) // 3,
|
||||||
|
"total_tokens": 0 # Will be calculated below
|
||||||
|
}
|
||||||
|
usage["total_tokens"] = usage["prompt_tokens"] + usage["completion_tokens"]
|
||||||
|
|
||||||
|
return response_text, usage
|
||||||
|
|
||||||
|
response_text, usage = await asyncio.to_thread(extract_response)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"choices": [{
|
||||||
|
"message": {
|
||||||
|
"content": response_text
|
||||||
|
}
|
||||||
|
}],
|
||||||
|
"usage": usage
|
||||||
|
}
|
||||||
|
|
||||||
|
except ImportError as e:
|
||||||
|
_LOGGER.error(f"Google Gemini library not installed: {str(e)}")
|
||||||
|
raise HomeAssistantError(f"Missing dependency: {str(e)}. Please install google-genai.")
|
||||||
|
except Exception as e:
|
||||||
|
_LOGGER.error(f"Gemini API error: {str(e)}")
|
||||||
|
raise HomeAssistantError(f"Gemini API error: {str(e)}")
|
||||||
|
|
||||||
|
async def shutdown(self) -> None:
|
||||||
|
"""Shutdown API client."""
|
||||||
|
_LOGGER.debug("Shutting down API client")
|
||||||
|
self._closed = True
|
||||||
|
# Do NOT close the shared Home Assistant session
|
||||||
@@ -1,12 +1,22 @@
|
|||||||
"""Config flow for HA text AI integration."""
|
"""
|
||||||
from typing import Any, Dict, Optional
|
Config flow for HA text AI integration.
|
||||||
import voluptuous as vol
|
|
||||||
|
|
||||||
|
@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
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
|
import voluptuous as vol
|
||||||
from homeassistant import config_entries
|
from homeassistant import config_entries
|
||||||
from homeassistant.const import CONF_API_KEY
|
from homeassistant.const import CONF_API_KEY, CONF_NAME
|
||||||
import homeassistant.helpers.config_validation as cv
|
|
||||||
from homeassistant.core import callback
|
from homeassistant.core import callback
|
||||||
import openai
|
from homeassistant.data_entry_flow import FlowResult
|
||||||
|
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||||
|
from homeassistant.helpers import selector
|
||||||
|
|
||||||
from .const import (
|
from .const import (
|
||||||
DOMAIN,
|
DOMAIN,
|
||||||
@@ -15,124 +25,677 @@ from .const import (
|
|||||||
CONF_MAX_TOKENS,
|
CONF_MAX_TOKENS,
|
||||||
CONF_API_ENDPOINT,
|
CONF_API_ENDPOINT,
|
||||||
CONF_REQUEST_INTERVAL,
|
CONF_REQUEST_INTERVAL,
|
||||||
|
CONF_API_TIMEOUT,
|
||||||
|
CONF_API_PROVIDER,
|
||||||
|
CONF_CONTEXT_MESSAGES,
|
||||||
|
API_PROVIDER_OPENAI,
|
||||||
|
API_PROVIDER_ANTHROPIC,
|
||||||
|
API_PROVIDER_DEEPSEEK,
|
||||||
|
API_PROVIDER_GEMINI,
|
||||||
|
API_PROVIDERS,
|
||||||
DEFAULT_MODEL,
|
DEFAULT_MODEL,
|
||||||
|
DEFAULT_DEEPSEEK_MODEL,
|
||||||
|
DEFAULT_GEMINI_MODEL,
|
||||||
DEFAULT_TEMPERATURE,
|
DEFAULT_TEMPERATURE,
|
||||||
DEFAULT_MAX_TOKENS,
|
DEFAULT_MAX_TOKENS,
|
||||||
DEFAULT_API_ENDPOINT,
|
|
||||||
DEFAULT_REQUEST_INTERVAL,
|
DEFAULT_REQUEST_INTERVAL,
|
||||||
|
DEFAULT_API_TIMEOUT,
|
||||||
|
DEFAULT_OPENAI_ENDPOINT,
|
||||||
|
DEFAULT_ANTHROPIC_ENDPOINT,
|
||||||
|
DEFAULT_DEEPSEEK_ENDPOINT,
|
||||||
|
DEFAULT_GEMINI_ENDPOINT,
|
||||||
|
DEFAULT_CONTEXT_MESSAGES,
|
||||||
|
MIN_TEMPERATURE,
|
||||||
|
MAX_TEMPERATURE,
|
||||||
|
MIN_MAX_TOKENS,
|
||||||
|
MAX_MAX_TOKENS,
|
||||||
|
MIN_REQUEST_INTERVAL,
|
||||||
|
MIN_API_TIMEOUT,
|
||||||
|
MAX_API_TIMEOUT,
|
||||||
|
DEFAULT_NAME_PREFIX,
|
||||||
|
DEFAULT_MAX_HISTORY,
|
||||||
|
CONF_MAX_HISTORY_SIZE,
|
||||||
)
|
)
|
||||||
|
|
||||||
STEP_USER_DATA_SCHEMA = vol.Schema({
|
_LOGGER = logging.getLogger(__name__)
|
||||||
vol.Required(CONF_API_KEY): str,
|
|
||||||
vol.Optional(CONF_MODEL, default=DEFAULT_MODEL): str,
|
|
||||||
vol.Optional(
|
def normalize_name(name: str) -> str:
|
||||||
CONF_TEMPERATURE,
|
"""Normalize name to conform to HA naming convention using underscores."""
|
||||||
default=DEFAULT_TEMPERATURE
|
normalized = ''.join(c if c.isalnum() or c == '_' else '_' for c in name)
|
||||||
): vol.All(vol.Coerce(float), vol.Range(min=0, max=2)),
|
normalized = '_'.join(filter(None, normalized.split('_')))
|
||||||
vol.Optional(
|
return normalized.lower()
|
||||||
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)),
|
|
||||||
})
|
|
||||||
|
|
||||||
class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||||
"""Handle a config flow for HA text AI."""
|
"""Handle a config flow for HA text AI."""
|
||||||
|
|
||||||
VERSION = 1
|
VERSION = 1
|
||||||
|
|
||||||
async def async_step_user(
|
def __init__(self) -> None:
|
||||||
self,
|
"""Initialize flow."""
|
||||||
user_input: Optional[Dict[str, Any]] = None
|
self._errors = {}
|
||||||
) -> Dict[str, Any]:
|
self._data = {}
|
||||||
|
self._provider = None
|
||||||
|
|
||||||
|
async def async_step_user(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
||||||
"""Handle the initial step."""
|
"""Handle the initial step."""
|
||||||
errors: Dict[str, str] = {}
|
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"
|
||||||
|
)
|
||||||
|
),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
if user_input is not None:
|
self._provider = user_input[CONF_API_PROVIDER]
|
||||||
try:
|
return await self.async_step_provider()
|
||||||
|
|
||||||
client = openai.OpenAI(
|
async def async_step_provider(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
||||||
api_key=user_input[CONF_API_KEY],
|
"""Handle provider configuration step."""
|
||||||
base_url=user_input.get(CONF_API_ENDPOINT, DEFAULT_API_ENDPOINT)
|
self._errors = {}
|
||||||
)
|
|
||||||
await self.hass.async_add_executor_job(
|
if user_input is None:
|
||||||
client.models.list
|
# Selecting an endpoint by provider
|
||||||
|
default_endpoint = {
|
||||||
|
API_PROVIDER_OPENAI: DEFAULT_OPENAI_ENDPOINT,
|
||||||
|
API_PROVIDER_ANTHROPIC: DEFAULT_ANTHROPIC_ENDPOINT,
|
||||||
|
API_PROVIDER_DEEPSEEK: DEFAULT_DEEPSEEK_ENDPOINT,
|
||||||
|
API_PROVIDER_GEMINI: DEFAULT_GEMINI_ENDPOINT,
|
||||||
|
}.get(self._provider, DEFAULT_OPENAI_ENDPOINT)
|
||||||
|
|
||||||
|
# Selecting the default model by provider
|
||||||
|
default_model = (
|
||||||
|
DEFAULT_DEEPSEEK_MODEL if self._provider == API_PROVIDER_DEEPSEEK else
|
||||||
|
DEFAULT_GEMINI_MODEL if self._provider == API_PROVIDER_GEMINI else
|
||||||
|
DEFAULT_MODEL
|
||||||
|
)
|
||||||
|
|
||||||
|
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_API_TIMEOUT, default=DEFAULT_API_TIMEOUT): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
|
||||||
|
),
|
||||||
|
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)
|
||||||
|
),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
# Debug log to identify what's in the input
|
||||||
|
_LOGGER.debug(f"Provider step input data: {user_input}")
|
||||||
|
|
||||||
|
input_copy = user_input.copy()
|
||||||
|
|
||||||
|
# Check if CONF_NAME exists in input_copy and ensure it's not empty
|
||||||
|
if CONF_NAME not in input_copy or not input_copy[CONF_NAME]:
|
||||||
|
_LOGGER.warning(f"Missing name in configuration input: {input_copy}")
|
||||||
|
input_copy[CONF_NAME] = f"gemini_assistant_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
|
||||||
|
_LOGGER.info(f"Auto-generated name: {input_copy[CONF_NAME]}")
|
||||||
|
|
||||||
|
# Ensure API key is present
|
||||||
|
if CONF_API_KEY not in input_copy or not input_copy[CONF_API_KEY]:
|
||||||
|
self._errors["base"] = "invalid_auth"
|
||||||
|
_LOGGER.error("API validation error: 'api_key'")
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="provider",
|
||||||
|
data_schema=vol.Schema({
|
||||||
|
vol.Required(CONF_NAME, default=input_copy.get(CONF_NAME, "my_assistant")): str,
|
||||||
|
vol.Required(CONF_API_KEY): str,
|
||||||
|
vol.Required(CONF_MODEL, default=input_copy.get(CONF_MODEL, DEFAULT_GEMINI_MODEL if self._provider == API_PROVIDER_GEMINI else DEFAULT_MODEL)): str,
|
||||||
|
vol.Required(CONF_API_ENDPOINT, default=input_copy.get(CONF_API_ENDPOINT, DEFAULT_GEMINI_ENDPOINT if self._provider == API_PROVIDER_GEMINI else DEFAULT_OPENAI_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)
|
||||||
|
),
|
||||||
|
vol.Optional(CONF_MAX_TOKENS, default=input_copy.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=input_copy.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)): vol.All(
|
||||||
|
vol.Coerce(float),
|
||||||
|
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||||
|
),
|
||||||
|
vol.Optional(CONF_API_TIMEOUT, default=input_copy.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
|
||||||
|
),
|
||||||
|
vol.Optional(
|
||||||
|
CONF_CONTEXT_MESSAGES,
|
||||||
|
default=input_copy.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=input_copy.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=1, max=100)
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
errors=self._errors
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Validate and normalize the name
|
||||||
|
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.get(CONF_NAME, "my_assistant")): str,
|
||||||
|
vol.Required(CONF_API_KEY, default=input_copy.get(CONF_API_KEY, "")): str,
|
||||||
|
vol.Required(CONF_MODEL, default=input_copy.get(CONF_MODEL, DEFAULT_GEMINI_MODEL if self._provider == API_PROVIDER_GEMINI else DEFAULT_MODEL)): str,
|
||||||
|
vol.Required(CONF_API_ENDPOINT, default=input_copy.get(CONF_API_ENDPOINT, DEFAULT_GEMINI_ENDPOINT if self._provider == API_PROVIDER_GEMINI else DEFAULT_OPENAI_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)
|
||||||
|
),
|
||||||
|
vol.Optional(CONF_MAX_TOKENS, default=input_copy.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=input_copy.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)): vol.All(
|
||||||
|
vol.Coerce(float),
|
||||||
|
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||||
|
),
|
||||||
|
vol.Optional(CONF_API_TIMEOUT, default=input_copy.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
|
||||||
|
),
|
||||||
|
vol.Optional(
|
||||||
|
CONF_CONTEXT_MESSAGES,
|
||||||
|
default=input_copy.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=input_copy.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=1, max=100)
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
errors={"name": str(e)}
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Special handling for Gemini API validation
|
||||||
|
if self._provider == API_PROVIDER_GEMINI:
|
||||||
|
# For Gemini, we just check if API key is present as there's no simple endpoint to validate
|
||||||
|
if not input_copy.get(CONF_API_KEY):
|
||||||
|
self._errors["base"] = "invalid_auth"
|
||||||
|
_LOGGER.error("API validation error: 'api_key'")
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="provider",
|
||||||
|
data_schema=vol.Schema({
|
||||||
|
vol.Required(CONF_NAME, default=input_copy.get(CONF_NAME, "my_assistant")): str,
|
||||||
|
vol.Required(CONF_API_KEY): str,
|
||||||
|
vol.Required(CONF_MODEL, default=input_copy.get(CONF_MODEL, DEFAULT_GEMINI_MODEL)): str,
|
||||||
|
vol.Required(CONF_API_ENDPOINT, default=input_copy.get(CONF_API_ENDPOINT, DEFAULT_GEMINI_ENDPOINT)): str,
|
||||||
|
# Other fields remain the same
|
||||||
|
}),
|
||||||
|
errors=self._errors
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
# For other providers, validate API connection
|
||||||
|
if not await self._async_validate_api(input_copy):
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="provider",
|
||||||
|
data_schema=vol.Schema({
|
||||||
|
vol.Required(CONF_NAME, default=input_copy.get(CONF_NAME, "my_assistant")): str,
|
||||||
|
vol.Required(CONF_API_KEY, default=input_copy.get(CONF_API_KEY, "")): str,
|
||||||
|
vol.Required(CONF_MODEL, default=input_copy.get(CONF_MODEL, DEFAULT_MODEL)): str,
|
||||||
|
vol.Required(CONF_API_ENDPOINT, default=input_copy.get(CONF_API_ENDPOINT, DEFAULT_OPENAI_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)
|
||||||
|
),
|
||||||
|
vol.Optional(CONF_MAX_TOKENS, default=input_copy.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=input_copy.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)): vol.All(
|
||||||
|
vol.Coerce(float),
|
||||||
|
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||||
|
),
|
||||||
|
vol.Optional(CONF_API_TIMEOUT, default=input_copy.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
|
||||||
|
),
|
||||||
|
vol.Optional(
|
||||||
|
CONF_CONTEXT_MESSAGES,
|
||||||
|
default=input_copy.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=input_copy.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=1, max=100)
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
errors=self._errors
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
# Handle any unexpected exceptions during validation
|
||||||
|
_LOGGER.exception("Unexpected error during API validation")
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="provider",
|
||||||
|
data_schema=vol.Schema({
|
||||||
|
vol.Required(CONF_NAME, default=input_copy.get(CONF_NAME, "my_assistant")): str,
|
||||||
|
vol.Required(CONF_API_KEY, default=input_copy.get(CONF_API_KEY, "")): str,
|
||||||
|
vol.Required(CONF_MODEL, default=input_copy.get(CONF_MODEL, DEFAULT_GEMINI_MODEL if self._provider == API_PROVIDER_GEMINI else DEFAULT_MODEL)): str,
|
||||||
|
vol.Required(CONF_API_ENDPOINT, default=input_copy.get(CONF_API_ENDPOINT, DEFAULT_GEMINI_ENDPOINT if self._provider == API_PROVIDER_GEMINI else DEFAULT_OPENAI_ENDPOINT)): str,
|
||||||
|
# Other fields remain the same
|
||||||
|
}),
|
||||||
|
errors={"base": str(e)}
|
||||||
|
)
|
||||||
|
|
||||||
|
# All validation passed, create the entry
|
||||||
|
return await self._create_entry(input_copy)
|
||||||
|
|
||||||
|
def _validate_and_normalize_name(self, name: str) -> str:
|
||||||
|
"""
|
||||||
|
Validate and normalize name with detailed error handling.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If name is invalid
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Normalized name
|
||||||
|
"""
|
||||||
|
if not name:
|
||||||
|
raise ValueError("empty")
|
||||||
|
|
||||||
|
name = name.strip()
|
||||||
|
normalized = ''.join(
|
||||||
|
c if c.isalnum() or c in ' _' else '_' # Only allow underscores
|
||||||
|
for c in name
|
||||||
|
)
|
||||||
|
|
||||||
|
normalized = normalized.replace(' ', '_').lower()
|
||||||
|
|
||||||
|
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:
|
||||||
|
if CONF_API_KEY not in user_input:
|
||||||
|
_LOGGER.error("API validation error: 'api_key'")
|
||||||
|
self._errors["base"] = "invalid_auth"
|
||||||
|
return False
|
||||||
|
|
||||||
|
session = async_get_clientsession(self.hass)
|
||||||
|
headers = self._get_api_headers(user_input)
|
||||||
|
endpoint = user_input[CONF_API_ENDPOINT].rstrip('/')
|
||||||
|
|
||||||
|
if self._provider == API_PROVIDER_GEMINI:
|
||||||
|
if not user_input[CONF_API_KEY]:
|
||||||
|
self._errors["base"] = "invalid_auth"
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
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
|
||||||
|
|
||||||
await self.async_set_unique_id(user_input[CONF_API_KEY])
|
except Exception as err:
|
||||||
self._abort_if_unique_id_configured()
|
_LOGGER.error("API validation error: %s", str(err))
|
||||||
|
self._errors["base"] = "cannot_connect"
|
||||||
|
return False
|
||||||
|
|
||||||
return self.async_create_entry(
|
def _get_api_headers(self, user_input: Dict[str, Any]) -> Dict[str, str]:
|
||||||
title="HA text AI",
|
"""Get API headers based on provider."""
|
||||||
data=user_input
|
if CONF_API_KEY not in user_input:
|
||||||
)
|
return {"Content-Type": "application/json"}
|
||||||
|
|
||||||
except openai.AuthenticationError:
|
api_key = user_input[CONF_API_KEY]
|
||||||
errors["base"] = "invalid_auth"
|
|
||||||
except openai.APIError:
|
|
||||||
errors["base"] = "cannot_connect"
|
|
||||||
except Exception: # pylint: disable=broad-except
|
|
||||||
errors["base"] = "unknown"
|
|
||||||
|
|
||||||
return self.async_show_form(
|
if self._provider == API_PROVIDER_ANTHROPIC:
|
||||||
step_id="user",
|
return {
|
||||||
data_schema=STEP_USER_DATA_SCHEMA,
|
"x-api-key": api_key,
|
||||||
errors=errors,
|
"anthropic-version": "2023-06-01",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
elif self._provider == API_PROVIDER_GEMINI:
|
||||||
|
return {
|
||||||
|
"Authorization": f"Bearer {api_key}",
|
||||||
|
"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()
|
||||||
|
|
||||||
|
default_model = (
|
||||||
|
DEFAULT_DEEPSEEK_MODEL if self._provider == API_PROVIDER_DEEPSEEK else
|
||||||
|
DEFAULT_GEMINI_MODEL if self._provider == API_PROVIDER_GEMINI else
|
||||||
|
DEFAULT_MODEL
|
||||||
|
)
|
||||||
|
|
||||||
|
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_API_TIMEOUT: user_input.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT),
|
||||||
|
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
|
@staticmethod
|
||||||
@callback
|
@callback
|
||||||
def async_get_options_flow(
|
def async_get_options_flow(config_entry: config_entries.ConfigEntry) -> config_entries.OptionsFlow:
|
||||||
config_entry: config_entries.ConfigEntry,
|
|
||||||
) -> config_entries.OptionsFlow:
|
|
||||||
"""Get the options flow for this handler."""
|
"""Get the options flow for this handler."""
|
||||||
return OptionsFlowHandler(config_entry)
|
return OptionsFlowHandler()
|
||||||
|
|
||||||
|
|
||||||
class OptionsFlowHandler(config_entries.OptionsFlow):
|
class OptionsFlowHandler(config_entries.OptionsFlow):
|
||||||
"""Handle options flow for HA text AI."""
|
"""Handle options flow."""
|
||||||
|
|
||||||
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
|
def __init__(self) -> None:
|
||||||
"""Initialize options flow."""
|
"""Initialize options flow."""
|
||||||
self.config_entry = config_entry
|
self._errors = {}
|
||||||
|
self._selected_provider = None
|
||||||
|
|
||||||
|
def _get_default_endpoint(self, provider: str) -> str:
|
||||||
|
"""Get default endpoint for provider."""
|
||||||
|
return {
|
||||||
|
API_PROVIDER_OPENAI: DEFAULT_OPENAI_ENDPOINT,
|
||||||
|
API_PROVIDER_ANTHROPIC: DEFAULT_ANTHROPIC_ENDPOINT,
|
||||||
|
API_PROVIDER_DEEPSEEK: DEFAULT_DEEPSEEK_ENDPOINT,
|
||||||
|
API_PROVIDER_GEMINI: DEFAULT_GEMINI_ENDPOINT,
|
||||||
|
}.get(provider, DEFAULT_OPENAI_ENDPOINT)
|
||||||
|
|
||||||
|
def _get_default_model(self, provider: str) -> str:
|
||||||
|
"""Get default model for provider."""
|
||||||
|
return (
|
||||||
|
DEFAULT_DEEPSEEK_MODEL if provider == API_PROVIDER_DEEPSEEK else
|
||||||
|
DEFAULT_GEMINI_MODEL if provider == API_PROVIDER_GEMINI else
|
||||||
|
DEFAULT_MODEL
|
||||||
|
)
|
||||||
|
|
||||||
|
def _get_api_headers(self, api_key: str, provider: str) -> Dict[str, str]:
|
||||||
|
"""Get API headers based on provider."""
|
||||||
|
if provider == API_PROVIDER_ANTHROPIC:
|
||||||
|
return {
|
||||||
|
"x-api-key": api_key,
|
||||||
|
"anthropic-version": "2023-06-01",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"Authorization": f"Bearer {api_key}",
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
|
||||||
|
async def _async_validate_api(self, provider: str, api_key: str, endpoint: str) -> bool:
|
||||||
|
"""Validate API connection."""
|
||||||
|
try:
|
||||||
|
if not api_key:
|
||||||
|
self._errors["base"] = "invalid_auth"
|
||||||
|
return False
|
||||||
|
|
||||||
|
# For Gemini, just check if API key is present
|
||||||
|
if provider == API_PROVIDER_GEMINI:
|
||||||
|
return True
|
||||||
|
|
||||||
|
session = async_get_clientsession(self.hass)
|
||||||
|
headers = self._get_api_headers(api_key, provider)
|
||||||
|
endpoint = endpoint.rstrip('/')
|
||||||
|
|
||||||
|
check_url = (
|
||||||
|
f"{endpoint}/v1/models" if provider == API_PROVIDER_ANTHROPIC
|
||||||
|
else f"{endpoint}/models"
|
||||||
|
)
|
||||||
|
|
||||||
|
async with session.get(check_url, headers=headers) as response:
|
||||||
|
if response.status == 401:
|
||||||
|
self._errors["base"] = "invalid_auth"
|
||||||
|
return False
|
||||||
|
elif response.status not in [200, 404]:
|
||||||
|
self._errors["base"] = "cannot_connect"
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as err:
|
||||||
|
_LOGGER.error("API validation error: %s", str(err))
|
||||||
|
self._errors["base"] = "cannot_connect"
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def async_step_init(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
||||||
|
"""Handle provider selection step."""
|
||||||
|
current_data = {**self.config_entry.data, **self.config_entry.options}
|
||||||
|
current_provider = current_data.get(CONF_API_PROVIDER, API_PROVIDER_OPENAI)
|
||||||
|
|
||||||
async def async_step_init(
|
|
||||||
self,
|
|
||||||
user_input: Optional[Dict[str, Any]] = None
|
|
||||||
) -> Dict[str, Any]:
|
|
||||||
"""Handle options flow."""
|
|
||||||
if user_input is not None:
|
if user_input is not None:
|
||||||
return self.async_create_entry(title="", data=user_input)
|
self._selected_provider = user_input.get(CONF_API_PROVIDER, current_provider)
|
||||||
|
return await self.async_step_settings()
|
||||||
options_schema = vol.Schema({
|
|
||||||
vol.Optional(
|
|
||||||
CONF_TEMPERATURE,
|
|
||||||
default=self.config_entry.options.get(
|
|
||||||
CONF_TEMPERATURE, DEFAULT_TEMPERATURE
|
|
||||||
),
|
|
||||||
description="Temperature for response generation (0-2)",
|
|
||||||
): 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="Maximum tokens in response (1-4096)",
|
|
||||||
): 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="Minimum time between API requests (seconds)",
|
|
||||||
): vol.All(vol.Coerce(float), vol.Range(min=0.1)),
|
|
||||||
})
|
|
||||||
|
|
||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
step_id="init",
|
step_id="init",
|
||||||
data_schema=options_schema,
|
data_schema=vol.Schema({
|
||||||
|
vol.Required(
|
||||||
|
CONF_API_PROVIDER,
|
||||||
|
default=current_provider
|
||||||
|
): selector.SelectSelector(
|
||||||
|
selector.SelectSelectorConfig(
|
||||||
|
options=API_PROVIDERS,
|
||||||
|
translation_key="api_provider"
|
||||||
|
)
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
description_placeholders={
|
||||||
|
"current_provider": current_provider
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def async_step_settings(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
||||||
|
"""Handle settings configuration step."""
|
||||||
|
self._errors = {}
|
||||||
|
current_data = {**self.config_entry.data, **self.config_entry.options}
|
||||||
|
provider = self._selected_provider or current_data.get(CONF_API_PROVIDER, API_PROVIDER_OPENAI)
|
||||||
|
|
||||||
|
# Determine if provider changed to show appropriate defaults
|
||||||
|
provider_changed = provider != current_data.get(CONF_API_PROVIDER)
|
||||||
|
|
||||||
|
# Use new defaults if provider changed, otherwise use current values
|
||||||
|
if provider_changed:
|
||||||
|
default_endpoint = self._get_default_endpoint(provider)
|
||||||
|
default_model = self._get_default_model(provider)
|
||||||
|
else:
|
||||||
|
default_endpoint = current_data.get(CONF_API_ENDPOINT, self._get_default_endpoint(provider))
|
||||||
|
default_model = current_data.get(CONF_MODEL, self._get_default_model(provider))
|
||||||
|
|
||||||
|
if user_input is not None:
|
||||||
|
# Validate API connection
|
||||||
|
api_key = user_input.get(CONF_API_KEY, current_data.get(CONF_API_KEY, ""))
|
||||||
|
endpoint = user_input.get(CONF_API_ENDPOINT, default_endpoint)
|
||||||
|
|
||||||
|
if await self._async_validate_api(provider, api_key, endpoint):
|
||||||
|
# Merge with provider selection
|
||||||
|
final_data = {
|
||||||
|
CONF_API_PROVIDER: provider,
|
||||||
|
**user_input
|
||||||
|
}
|
||||||
|
return self.async_create_entry(title="", data=final_data)
|
||||||
|
|
||||||
|
# Show form again with errors
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="settings",
|
||||||
|
data_schema=self._get_settings_schema(
|
||||||
|
provider=provider,
|
||||||
|
current_data=current_data,
|
||||||
|
user_input=user_input,
|
||||||
|
default_endpoint=default_endpoint,
|
||||||
|
default_model=default_model,
|
||||||
|
),
|
||||||
|
errors=self._errors
|
||||||
|
)
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="settings",
|
||||||
|
data_schema=self._get_settings_schema(
|
||||||
|
provider=provider,
|
||||||
|
current_data=current_data,
|
||||||
|
user_input=None,
|
||||||
|
default_endpoint=default_endpoint,
|
||||||
|
default_model=default_model,
|
||||||
|
),
|
||||||
|
description_placeholders={
|
||||||
|
"provider": provider
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
def _get_settings_schema(
|
||||||
|
self,
|
||||||
|
provider: str,
|
||||||
|
current_data: Dict[str, Any],
|
||||||
|
user_input: Optional[Dict[str, Any]],
|
||||||
|
default_endpoint: str,
|
||||||
|
default_model: str,
|
||||||
|
) -> vol.Schema:
|
||||||
|
"""Build settings schema."""
|
||||||
|
data = user_input or current_data
|
||||||
|
|
||||||
|
return vol.Schema({
|
||||||
|
vol.Required(
|
||||||
|
CONF_API_KEY,
|
||||||
|
default=data.get(CONF_API_KEY, "")
|
||||||
|
): str,
|
||||||
|
vol.Required(
|
||||||
|
CONF_API_ENDPOINT,
|
||||||
|
default=data.get(CONF_API_ENDPOINT, default_endpoint)
|
||||||
|
): str,
|
||||||
|
vol.Required(
|
||||||
|
CONF_MODEL,
|
||||||
|
default=data.get(CONF_MODEL, default_model)
|
||||||
|
): str,
|
||||||
|
vol.Optional(
|
||||||
|
CONF_TEMPERATURE,
|
||||||
|
default=data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(float),
|
||||||
|
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
||||||
|
),
|
||||||
|
vol.Optional(
|
||||||
|
CONF_MAX_TOKENS,
|
||||||
|
default=data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
|
||||||
|
),
|
||||||
|
vol.Optional(
|
||||||
|
CONF_REQUEST_INTERVAL,
|
||||||
|
default=data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(float),
|
||||||
|
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||||
|
),
|
||||||
|
vol.Optional(
|
||||||
|
CONF_API_TIMEOUT,
|
||||||
|
default=data.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
|
||||||
|
),
|
||||||
|
vol.Optional(
|
||||||
|
CONF_CONTEXT_MESSAGES,
|
||||||
|
default=data.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=1, max=20)
|
||||||
|
),
|
||||||
|
vol.Optional(
|
||||||
|
CONF_MAX_HISTORY_SIZE,
|
||||||
|
default=data.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
|
||||||
|
): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=1, max=100)
|
||||||
|
),
|
||||||
|
})
|
||||||
|
|||||||
@@ -1,10 +1,59 @@
|
|||||||
"""Constants for the HA text AI integration."""
|
"""
|
||||||
from typing import Final
|
Constants for the HA text AI integration.
|
||||||
from homeassistant.const import Platform
|
|
||||||
|
|
||||||
# Domain
|
@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 os
|
||||||
|
import json
|
||||||
|
from typing import Final
|
||||||
|
import voluptuous as vol
|
||||||
|
from homeassistant.const import Platform, CONF_API_KEY, CONF_NAME
|
||||||
|
from homeassistant.helpers import config_validation as cv
|
||||||
|
import logging
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Domain and platforms
|
||||||
DOMAIN: Final = "ha_text_ai"
|
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_PROVIDER_DEEPSEEK: Final = "deepseek"
|
||||||
|
API_PROVIDER_GEMINI: Final = "gemini"
|
||||||
|
|
||||||
|
API_PROVIDERS: Final = [
|
||||||
|
API_PROVIDER_OPENAI,
|
||||||
|
API_PROVIDER_ANTHROPIC,
|
||||||
|
API_PROVIDER_DEEPSEEK,
|
||||||
|
API_PROVIDER_GEMINI
|
||||||
|
]
|
||||||
|
|
||||||
|
# Read version from manifest.json
|
||||||
|
MANIFEST_PATH = os.path.join(os.path.dirname(__file__), "manifest.json")
|
||||||
|
try:
|
||||||
|
with open(MANIFEST_PATH) as manifest_file:
|
||||||
|
manifest = json.load(manifest_file)
|
||||||
|
VERSION = manifest.get("version", "unknown")
|
||||||
|
except FileNotFoundError:
|
||||||
|
VERSION = "unknown"
|
||||||
|
_LOGGER.warning("manifest.json not found at %s", MANIFEST_PATH)
|
||||||
|
except json.JSONDecodeError as err:
|
||||||
|
VERSION = "unknown"
|
||||||
|
_LOGGER.error("Error decoding JSON from manifest.json: %s", err)
|
||||||
|
except Exception as err:
|
||||||
|
VERSION = "unknown"
|
||||||
|
_LOGGER.error("Error reading manifest.json: %s", err)
|
||||||
|
|
||||||
|
# Default endpoints
|
||||||
|
DEFAULT_OPENAI_ENDPOINT: Final = "https://api.openai.com/v1"
|
||||||
|
DEFAULT_ANTHROPIC_ENDPOINT: Final = "https://api.anthropic.com"
|
||||||
|
DEFAULT_DEEPSEEK_ENDPOINT: Final = "https://api.deepseek.com"
|
||||||
|
DEFAULT_GEMINI_ENDPOINT: Final = "https://generativelanguage.googleapis.com/v1beta"
|
||||||
|
|
||||||
# Configuration constants
|
# Configuration constants
|
||||||
CONF_MODEL: Final = "model"
|
CONF_MODEL: Final = "model"
|
||||||
@@ -12,20 +61,48 @@ CONF_TEMPERATURE: Final = "temperature"
|
|||||||
CONF_MAX_TOKENS: Final = "max_tokens"
|
CONF_MAX_TOKENS: Final = "max_tokens"
|
||||||
CONF_API_ENDPOINT: Final = "api_endpoint"
|
CONF_API_ENDPOINT: Final = "api_endpoint"
|
||||||
CONF_REQUEST_INTERVAL: Final = "request_interval"
|
CONF_REQUEST_INTERVAL: Final = "request_interval"
|
||||||
|
CONF_API_TIMEOUT: Final = "api_timeout"
|
||||||
|
CONF_INSTANCE: Final = "instance"
|
||||||
|
CONF_MAX_HISTORY_SIZE: Final = "max_history_size" # Correct constant name
|
||||||
|
CONF_IS_ANTHROPIC: Final = "is_anthropic"
|
||||||
|
CONF_CONTEXT_MESSAGES: Final = "context_messages"
|
||||||
|
CONF_STRUCTURED_OUTPUT: Final = "structured_output"
|
||||||
|
CONF_JSON_SCHEMA: Final = "json_schema"
|
||||||
|
|
||||||
|
ABSOLUTE_MAX_HISTORY_SIZE = 500
|
||||||
|
MAX_ATTRIBUTE_SIZE = 4 * 1024
|
||||||
|
MAX_HISTORY_FILE_SIZE = 1 * 1024 * 1024
|
||||||
|
ICONS_SUBDOMAIN = "icons"
|
||||||
|
|
||||||
# Default values
|
# Default values
|
||||||
DEFAULT_MODEL: Final = "gpt-3.5-turbo"
|
DEFAULT_MODEL: Final = "gpt-4o-mini"
|
||||||
DEFAULT_TEMPERATURE: Final = 0.7
|
DEFAULT_DEEPSEEK_MODEL: Final = "deepseek-chat"
|
||||||
|
DEFAULT_GEMINI_MODEL: Final = "gemini-2.0-flash"
|
||||||
|
DEFAULT_TEMPERATURE: Final = 0.1
|
||||||
DEFAULT_MAX_TOKENS: Final = 1000
|
DEFAULT_MAX_TOKENS: Final = 1000
|
||||||
DEFAULT_API_ENDPOINT: Final = "https://api.openai.com/v1"
|
|
||||||
DEFAULT_REQUEST_INTERVAL: Final = 1.0
|
DEFAULT_REQUEST_INTERVAL: Final = 1.0
|
||||||
|
DEFAULT_TIMEOUT: Final = 30
|
||||||
|
DEFAULT_API_TIMEOUT: Final = 30
|
||||||
|
DEFAULT_MAX_HISTORY: Final = 50
|
||||||
|
DEFAULT_NAME: Final = "HA Text AI"
|
||||||
|
DEFAULT_NAME_PREFIX = "ha_text_ai"
|
||||||
|
DEFAULT_CONTEXT_MESSAGES: Final = 5
|
||||||
|
|
||||||
|
TRUNCATION_INDICATOR = " ... "
|
||||||
|
|
||||||
# Parameter constraints
|
# Parameter constraints
|
||||||
MIN_TEMPERATURE: Final = 0.0
|
MIN_TEMPERATURE: Final = 0.0
|
||||||
MAX_TEMPERATURE: Final = 2.0
|
MAX_TEMPERATURE: Final = 2.0
|
||||||
MIN_MAX_TOKENS: Final = 1
|
MIN_MAX_TOKENS: Final = 1
|
||||||
MAX_MAX_TOKENS: Final = 4096
|
MAX_MAX_TOKENS: Final = 100000
|
||||||
MIN_REQUEST_INTERVAL: Final = 0.1
|
MIN_REQUEST_INTERVAL: Final = 0.1
|
||||||
|
MAX_REQUEST_INTERVAL: Final = 60.0
|
||||||
|
MIN_API_TIMEOUT: Final = 5
|
||||||
|
MAX_API_TIMEOUT: Final = 600
|
||||||
|
|
||||||
|
# API constants
|
||||||
|
API_TIMEOUT: Final = 30 # Legacy constant, use CONF_API_TIMEOUT from config
|
||||||
|
API_RETRY_COUNT: Final = 3
|
||||||
|
|
||||||
# Service names
|
# Service names
|
||||||
SERVICE_ASK_QUESTION: Final = "ask_question"
|
SERVICE_ASK_QUESTION: Final = "ask_question"
|
||||||
@@ -33,29 +110,147 @@ SERVICE_CLEAR_HISTORY: Final = "clear_history"
|
|||||||
SERVICE_GET_HISTORY: Final = "get_history"
|
SERVICE_GET_HISTORY: Final = "get_history"
|
||||||
SERVICE_SET_SYSTEM_PROMPT: Final = "set_system_prompt"
|
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
|
# Attribute keys
|
||||||
ATTR_QUESTION: Final = "question"
|
ATTR_QUESTION: Final = "question"
|
||||||
ATTR_RESPONSE: Final = "response"
|
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_SYSTEM_PROMPT: Final = "system_prompt"
|
||||||
|
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 messages
|
||||||
ERROR_INVALID_API_KEY: Final = "invalid_api_key"
|
ERROR_INVALID_API_KEY: Final = "invalid_api_key"
|
||||||
ERROR_CANNOT_CONNECT: Final = "cannot_connect"
|
ERROR_CANNOT_CONNECT: Final = "cannot_connect"
|
||||||
ERROR_UNKNOWN: Final = "unknown_error"
|
ERROR_UNKNOWN: Final = "unknown_error"
|
||||||
|
ERROR_INVALID_MODEL: Final = "invalid_model"
|
||||||
# Configuration descriptions
|
ERROR_RATE_LIMIT: Final = "rate_limit_exceeded"
|
||||||
CONF_MODEL_DESCRIPTION: Final = "AI model to use for responses"
|
ERROR_CONTEXT_LENGTH: Final = "context_length_exceeded"
|
||||||
CONF_TEMPERATURE_DESCRIPTION: Final = "Temperature for response generation (0-2)"
|
ERROR_API_ERROR: Final = "api_error"
|
||||||
CONF_MAX_TOKENS_DESCRIPTION: Final = "Maximum tokens in response (1-4096)"
|
ERROR_TIMEOUT: Final = "timeout_error"
|
||||||
CONF_API_ENDPOINT_DESCRIPTION: Final = "API endpoint URL"
|
ERROR_INVALID_INSTANCE: Final = "invalid_instance"
|
||||||
CONF_REQUEST_INTERVAL_DESCRIPTION: Final = "Minimum time between API requests (seconds)"
|
ERROR_NAME_EXISTS: Final = "name_exists"
|
||||||
|
|
||||||
# Entity attributes
|
# Entity attributes
|
||||||
ENTITY_NAME: Final = "HA Text AI"
|
|
||||||
ENTITY_ICON: Final = "mdi:robot"
|
ENTITY_ICON: Final = "mdi:robot"
|
||||||
|
ENTITY_ICON_ERROR: Final = "mdi:robot-dead"
|
||||||
|
ENTITY_ICON_PROCESSING: Final = "mdi:robot-excited"
|
||||||
|
|
||||||
|
# State attributes
|
||||||
|
STATE_READY: Final = "ready"
|
||||||
|
STATE_PROCESSING: Final = "processing"
|
||||||
|
STATE_ERROR: Final = "error"
|
||||||
|
STATE_INITIALIZING: Final = "initializing"
|
||||||
|
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)
|
||||||
|
),
|
||||||
|
vol.Optional(CONF_STRUCTURED_OUTPUT, default=False): cv.boolean,
|
||||||
|
vol.Optional(CONF_JSON_SCHEMA): cv.string,
|
||||||
|
})
|
||||||
|
|
||||||
|
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_API_TIMEOUT, default=DEFAULT_API_TIMEOUT): vol.All(
|
||||||
|
vol.Coerce(int),
|
||||||
|
vol.Range(min=MIN_API_TIMEOUT, max=MAX_API_TIMEOUT)
|
||||||
|
),
|
||||||
|
vol.Optional(CONF_MAX_HISTORY_SIZE, default=DEFAULT_MAX_HISTORY): vol.All( # Correct usage
|
||||||
|
vol.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)
|
||||||
|
|||||||
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 351 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 257 KiB |
|
After Width: | Height: | Size: 117 KiB |
|
After Width: | Height: | Size: 325 KiB |
|
After Width: | Height: | Size: 86 KiB |
|
After Width: | Height: | Size: 259 KiB |
@@ -1,14 +1,30 @@
|
|||||||
{
|
{
|
||||||
"domain": "ha_text_ai",
|
"domain": "ha_text_ai",
|
||||||
"name": "HA Text AI",
|
"name": "HA Text AI",
|
||||||
|
"after_dependencies": ["http"],
|
||||||
|
"bluetooth": [],
|
||||||
|
"codeowners": ["@smkrv"],
|
||||||
"config_flow": true,
|
"config_flow": true,
|
||||||
"documentation": "https://github.com/smkrv/ha-text-ai/wiki",
|
|
||||||
"issue_tracker": "https://github.com/smkrv/ha-text-ai/issues",
|
|
||||||
"requirements": ["openai>=1.0.0"],
|
|
||||||
"ssdp": [],
|
|
||||||
"zeroconf": [],
|
|
||||||
"dependencies": [],
|
"dependencies": [],
|
||||||
"version": "1.0.1c",
|
"documentation": "https://github.com/smkrv/ha-text-ai",
|
||||||
|
"integration_type": "service",
|
||||||
"iot_class": "cloud_polling",
|
"iot_class": "cloud_polling",
|
||||||
"codeowners": ["@smkrv"]
|
"issue_tracker": "https://github.com/smkrv/ha-text-ai/issues",
|
||||||
|
"loggers": ["custom_components.ha_text_ai"],
|
||||||
|
"mqtt": [],
|
||||||
|
"quality_scale": "silver",
|
||||||
|
"requirements": [
|
||||||
|
"aiofiles>=23.0.0",
|
||||||
|
"aiohttp>=3.8.0",
|
||||||
|
"anthropic>=0.8.0",
|
||||||
|
"async-timeout>=4.0.0",
|
||||||
|
"certifi>=2024.2.2",
|
||||||
|
"google-genai>=1.16.0",
|
||||||
|
"openai>=1.12.0"
|
||||||
|
],
|
||||||
|
"single_config_entry": false,
|
||||||
|
"ssdp": [],
|
||||||
|
"usb": [],
|
||||||
|
"version": "2.3.0",
|
||||||
|
"zeroconf": []
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,40 +1,111 @@
|
|||||||
"""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
|
import logging
|
||||||
from typing import Any, Callable, Dict, Optional
|
import math
|
||||||
|
from typing import Any, Dict
|
||||||
|
from datetime import datetime, timedelta
|
||||||
|
|
||||||
from homeassistant.components.sensor import (
|
from homeassistant.components.sensor import (
|
||||||
SensorEntity,
|
SensorEntity,
|
||||||
SensorStateClass,
|
SensorEntityDescription,
|
||||||
SensorDeviceClass,
|
|
||||||
)
|
)
|
||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
|
from homeassistant.helpers.device_registry import DeviceInfo
|
||||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||||
from homeassistant.helpers.typing import StateType
|
from homeassistant.helpers.typing import StateType
|
||||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||||
|
from homeassistant.util import dt as dt_util
|
||||||
|
from homeassistant.util import slugify
|
||||||
|
|
||||||
|
from .const import (
|
||||||
|
DOMAIN,
|
||||||
|
CONF_MODEL,
|
||||||
|
CONF_API_PROVIDER,
|
||||||
|
ATTR_TOTAL_RESPONSES,
|
||||||
|
ATTR_TOTAL_ERRORS,
|
||||||
|
ATTR_AVG_RESPONSE_TIME,
|
||||||
|
ATTR_LAST_REQUEST_TIME,
|
||||||
|
ATTR_LAST_ERROR,
|
||||||
|
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_INITIALIZING,
|
||||||
|
STATE_MAINTENANCE,
|
||||||
|
STATE_RATE_LIMITED,
|
||||||
|
STATE_DISCONNECTED,
|
||||||
|
ENTITY_ICON,
|
||||||
|
ENTITY_ICON_ERROR,
|
||||||
|
ENTITY_ICON_PROCESSING,
|
||||||
|
DEFAULT_NAME_PREFIX,
|
||||||
|
CONF_MAX_HISTORY_SIZE,
|
||||||
|
MAX_ATTRIBUTE_SIZE,
|
||||||
|
VERSION,
|
||||||
|
)
|
||||||
|
|
||||||
from .const import DOMAIN, ATTR_QUESTION, ATTR_RESPONSE, ATTR_LAST_UPDATED
|
|
||||||
from .coordinator import HATextAICoordinator
|
from .coordinator import HATextAICoordinator
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
async def async_setup_entry(
|
async def async_setup_entry(
|
||||||
hass: HomeAssistant,
|
hass: HomeAssistant,
|
||||||
entry: ConfigEntry,
|
entry: ConfigEntry,
|
||||||
async_add_entities: AddEntitiesCallback,
|
async_add_entities: AddEntitiesCallback,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Set up the HA text AI sensor."""
|
"""Set up the HA Text AI sensor."""
|
||||||
coordinator = hass.data[DOMAIN][entry.entry_id]
|
_LOGGER.debug(f"Starting sensor setup for entry: {entry.entry_id}")
|
||||||
async_add_entities([HATextAISensor(coordinator, entry)], True)
|
|
||||||
|
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):
|
class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||||
"""HA text AI Sensor."""
|
"""HA Text AI Sensor."""
|
||||||
|
|
||||||
_attr_has_entity_name = True
|
coordinator: HATextAICoordinator
|
||||||
_attr_state_class = SensorStateClass.MEASUREMENT
|
|
||||||
_attr_device_class = SensorDeviceClass.TIMESTAMP
|
|
||||||
_attr_icon = "mdi:robot"
|
|
||||||
|
|
||||||
def __init__(
|
def __init__(
|
||||||
self,
|
self,
|
||||||
@@ -42,53 +113,250 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
|||||||
config_entry: ConfigEntry,
|
config_entry: ConfigEntry,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Initialize the sensor."""
|
"""Initialize the sensor."""
|
||||||
|
_LOGGER.debug(f"Initializing sensor with config entry: {config_entry.data}")
|
||||||
|
|
||||||
super().__init__(coordinator)
|
super().__init__(coordinator)
|
||||||
|
|
||||||
self._config_entry = config_entry
|
self._config_entry = config_entry
|
||||||
|
self._instance_name = coordinator.instance_name
|
||||||
|
self._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_unique_id = f"{config_entry.entry_id}"
|
||||||
self._attr_name = "Last Response"
|
|
||||||
|
|
||||||
@property
|
_LOGGER.debug(f"Created sensor with entity_id: {self.entity_id}")
|
||||||
def state(self) -> StateType:
|
_LOGGER.debug(f"Sensor name: {self._attr_name}")
|
||||||
"""Return the state of the sensor."""
|
_LOGGER.debug(f"Unique ID: {self._attr_unique_id}")
|
||||||
if not self.coordinator.data:
|
|
||||||
return None
|
|
||||||
return self.coordinator.last_update_success_time
|
|
||||||
|
|
||||||
@property
|
self.entity_description = SensorEntityDescription(
|
||||||
def extra_state_attributes(self) -> Optional[Dict[str, Any]]:
|
key=f"ha_text_ai_{self._normalized_name.lower()}",
|
||||||
"""Return entity specific state attributes."""
|
entity_registry_enabled_default=True,
|
||||||
if not self.coordinator.data:
|
)
|
||||||
return None
|
|
||||||
|
|
||||||
try:
|
self._current_state = STATE_INITIALIZING
|
||||||
|
self._error_count = 0
|
||||||
|
self._last_error = None
|
||||||
|
self._last_update = None
|
||||||
|
self._is_processing = False
|
||||||
|
self._last_response = {}
|
||||||
|
self._metrics = {}
|
||||||
|
|
||||||
history = list(self.coordinator.data.items())
|
model = config_entry.data.get(CONF_MODEL, "Unknown")
|
||||||
if not history:
|
api_provider = config_entry.data.get(CONF_API_PROVIDER, "Unknown")
|
||||||
return None
|
|
||||||
|
|
||||||
last_question, last_data = history[-1]
|
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=VERSION,
|
||||||
|
)
|
||||||
|
|
||||||
|
_LOGGER.debug(
|
||||||
if isinstance(last_data, dict):
|
f"Initialized sensor: {self.entity_id} for instance: {self._instance_name}"
|
||||||
last_response = last_data.get("response", "")
|
)
|
||||||
else:
|
|
||||||
last_response = str(last_data)
|
|
||||||
|
|
||||||
return {
|
|
||||||
ATTR_QUESTION: last_question,
|
|
||||||
ATTR_RESPONSE: last_response,
|
|
||||||
ATTR_LAST_UPDATED: self.coordinator.last_update_success_time,
|
|
||||||
}
|
|
||||||
except (IndexError, KeyError, AttributeError) as err:
|
|
||||||
_LOGGER.warning("Error getting attributes: %s", err)
|
|
||||||
return None
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def available(self) -> bool:
|
def available(self) -> bool:
|
||||||
"""Return if entity is available."""
|
"""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."""
|
||||||
|
sanitized = {
|
||||||
|
key: self._sanitize_value(value)
|
||||||
|
for key, value in attributes.items()
|
||||||
|
if value is not None
|
||||||
|
}
|
||||||
|
|
||||||
|
# Log metrics for debugging
|
||||||
|
metrics_keys = [
|
||||||
|
METRIC_TOTAL_TOKENS,
|
||||||
|
METRIC_PROMPT_TOKENS,
|
||||||
|
METRIC_COMPLETION_TOKENS,
|
||||||
|
METRIC_SUCCESSFUL_REQUESTS,
|
||||||
|
METRIC_FAILED_REQUESTS,
|
||||||
|
METRIC_AVERAGE_LATENCY,
|
||||||
|
METRIC_MAX_LATENCY,
|
||||||
|
METRIC_MIN_LATENCY,
|
||||||
|
]
|
||||||
|
|
||||||
|
metrics_values = {k: sanitized.get(k) for k in metrics_keys if k in sanitized}
|
||||||
|
_LOGGER.debug(f"Metrics for {self.entity_id}: {metrics_values}")
|
||||||
|
|
||||||
|
return sanitized
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def should_poll(self) -> bool:
|
def native_value(self) -> StateType:
|
||||||
"""No need to poll. Coordinator notifies entity of updates."""
|
"""Return the native value of the sensor."""
|
||||||
return False
|
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
|
||||||
|
metrics = data.get("metrics", {})
|
||||||
|
|
||||||
|
# Base attributes
|
||||||
|
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: metrics.get("total_errors", 0),
|
||||||
|
"instance_name": self._instance_name,
|
||||||
|
"normalized_name": self._normalized_name,
|
||||||
|
ATTR_SYSTEM_PROMPT: (data.get("system_prompt", "")[:MAX_ATTRIBUTE_SIZE]
|
||||||
|
if data.get("system_prompt") else None),
|
||||||
|
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: round(data.get("uptime", 0), 2),
|
||||||
|
ATTR_HISTORY_SIZE: data.get("history_size", 0),
|
||||||
|
}
|
||||||
|
|
||||||
|
# History limit
|
||||||
|
conversation_history = data.get("conversation_history", [])
|
||||||
|
if conversation_history:
|
||||||
|
limited_history = []
|
||||||
|
for entry in conversation_history:
|
||||||
|
limited_entry = {
|
||||||
|
"timestamp": entry["timestamp"],
|
||||||
|
"question": entry["question"][:MAX_ATTRIBUTE_SIZE],
|
||||||
|
"response": entry["response"][:MAX_ATTRIBUTE_SIZE]
|
||||||
|
}
|
||||||
|
limited_history.append(limited_entry)
|
||||||
|
attributes[ATTR_CONVERSATION_HISTORY] = limited_history
|
||||||
|
|
||||||
|
# Metrics
|
||||||
|
if isinstance(metrics, dict):
|
||||||
|
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: round(metrics.get("average_latency", 0), 2),
|
||||||
|
METRIC_MAX_LATENCY: round(metrics.get("max_latency", 0), 2),
|
||||||
|
METRIC_MIN_LATENCY: (metrics.get("min_latency")
|
||||||
|
if metrics.get("min_latency") != float("inf")
|
||||||
|
else None),
|
||||||
|
})
|
||||||
|
|
||||||
|
# Last response handling
|
||||||
|
last_response = data.get("last_response", {})
|
||||||
|
if isinstance(last_response, dict):
|
||||||
|
attributes.update({
|
||||||
|
ATTR_RESPONSE: last_response.get("response", "")[:MAX_ATTRIBUTE_SIZE],
|
||||||
|
ATTR_QUESTION: last_response.get("question", "")[:MAX_ATTRIBUTE_SIZE],
|
||||||
|
"last_model": last_response.get("model", ""),
|
||||||
|
"last_timestamp": last_response.get("timestamp", ""),
|
||||||
|
"last_error": (last_response.get("error", "")[:MAX_ATTRIBUTE_SIZE]
|
||||||
|
if last_response.get("error") else None),
|
||||||
|
})
|
||||||
|
|
||||||
|
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()
|
||||||
|
_LOGGER.debug(f"Entity {self.entity_id} added to Home Assistant")
|
||||||
|
|
||||||
|
def _handle_coordinator_update(self) -> None:
|
||||||
|
"""Handle updated data from the coordinator."""
|
||||||
|
try:
|
||||||
|
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 metrics
|
||||||
|
metrics = data.get("metrics", {})
|
||||||
|
if isinstance(metrics, dict):
|
||||||
|
self._metrics.update(metrics)
|
||||||
|
_LOGGER.debug(f"Updated metrics for {self.entity_id}: {self._metrics}")
|
||||||
|
|
||||||
|
# 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._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:
|
||||||
|
self._current_state = STATE_ERROR
|
||||||
|
self._last_error = str(err)
|
||||||
|
self._error_count += 1
|
||||||
|
_LOGGER.error(
|
||||||
|
"Error handling update for %s: %s",
|
||||||
|
self.entity_id,
|
||||||
|
err,
|
||||||
|
exc_info=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
self.async_write_ha_state()
|
||||||
|
|||||||
@@ -1,35 +1,58 @@
|
|||||||
ask_question:
|
ask_question:
|
||||||
name: Ask Question
|
name: Ask Question
|
||||||
description: Send a question to the AI model and receive a detailed response
|
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.
|
||||||
|
This service now returns response data directly, eliminating the need to read from sensors.
|
||||||
fields:
|
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:
|
question:
|
||||||
name: Question
|
name: Question
|
||||||
description: Your question or prompt for the AI assistant
|
description: Your question or prompt for the AI assistant
|
||||||
required: true
|
required: true
|
||||||
example: "What automations would you recommend for a smart kitchen?"
|
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:
|
selector:
|
||||||
text:
|
text:
|
||||||
multiline: true
|
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:
|
model:
|
||||||
name: Model
|
name: Model
|
||||||
description: Select an AI model to use (optional, overrides default setting)
|
description: "Select AI model to use (optional, overrides default setting)"
|
||||||
required: false
|
required: false
|
||||||
example: "gpt-3.5-turbo"
|
|
||||||
default: "gpt-3.5-turbo"
|
|
||||||
selector:
|
selector:
|
||||||
select:
|
text: {}
|
||||||
options:
|
|
||||||
- label: "GPT-3.5 Turbo"
|
|
||||||
value: "gpt-3.5-turbo"
|
|
||||||
- label: "GPT-4"
|
|
||||||
value: "gpt-4"
|
|
||||||
- label: "GPT-4 32K"
|
|
||||||
value: "gpt-4-32k"
|
|
||||||
|
|
||||||
temperature:
|
temperature:
|
||||||
name: Temperature
|
name: Temperature
|
||||||
description: "Controls response creativity (0-2): Lower values for focused responses, higher for creative ones"
|
description: Controls response creativity (0.0-2.0)
|
||||||
required: false
|
required: false
|
||||||
default: 0.7
|
default: 0.7
|
||||||
selector:
|
selector:
|
||||||
@@ -41,28 +64,64 @@ ask_question:
|
|||||||
|
|
||||||
max_tokens:
|
max_tokens:
|
||||||
name: Max Tokens
|
name: Max Tokens
|
||||||
description: Maximum length of the response
|
description: Maximum length of the response (tokens)
|
||||||
required: false
|
required: false
|
||||||
default: 1000
|
default: 1000
|
||||||
selector:
|
selector:
|
||||||
number:
|
number:
|
||||||
min: 1
|
min: 1
|
||||||
max: 4096
|
max: 100000
|
||||||
step: 1
|
step: 1
|
||||||
mode: box
|
mode: box
|
||||||
|
|
||||||
|
structured_output:
|
||||||
|
name: Structured Output
|
||||||
|
description: Enable JSON structured output mode. When enabled, the AI will respond with valid JSON matching the provided schema.
|
||||||
|
required: false
|
||||||
|
default: false
|
||||||
|
selector:
|
||||||
|
boolean: {}
|
||||||
|
|
||||||
|
json_schema:
|
||||||
|
name: JSON Schema
|
||||||
|
description: >-
|
||||||
|
JSON Schema defining the structure of the expected response.
|
||||||
|
Required when structured_output is enabled.
|
||||||
|
required: false
|
||||||
|
selector:
|
||||||
|
text:
|
||||||
|
multiline: true
|
||||||
|
|
||||||
clear_history:
|
clear_history:
|
||||||
name: Clear History
|
name: Clear History
|
||||||
description: Delete all stored questions and responses
|
description: >-
|
||||||
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:
|
get_history:
|
||||||
name: Get History
|
name: Get History
|
||||||
description: Retrieve recent conversation history
|
description: Retrieve conversation history with optional filtering and sorting
|
||||||
fields:
|
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:
|
limit:
|
||||||
name: Limit
|
name: Limit
|
||||||
description: Number of most recent conversations to return
|
description: Number of conversations to return (1-100)
|
||||||
required: false
|
required: false
|
||||||
default: 10
|
default: 10
|
||||||
selector:
|
selector:
|
||||||
@@ -72,15 +131,58 @@ get_history:
|
|||||||
step: 1
|
step: 1
|
||||||
mode: box
|
mode: box
|
||||||
|
|
||||||
|
filter_model:
|
||||||
|
name: Filter Model
|
||||||
|
description: Filter conversations by specific AI model
|
||||||
|
required: false
|
||||||
|
selector:
|
||||||
|
text:
|
||||||
|
multiline: false
|
||||||
|
|
||||||
|
start_date:
|
||||||
|
name: Start Date
|
||||||
|
description: Filter conversations starting from this date/time
|
||||||
|
required: false
|
||||||
|
selector:
|
||||||
|
text:
|
||||||
|
multiline: false
|
||||||
|
|
||||||
|
include_metadata:
|
||||||
|
name: Include Metadata
|
||||||
|
description: Include additional information like tokens used, response time, etc.
|
||||||
|
required: false
|
||||||
|
default: false
|
||||||
|
selector:
|
||||||
|
boolean: {}
|
||||||
|
|
||||||
|
sort_order:
|
||||||
|
name: Sort Order
|
||||||
|
description: Sort order for results (newest or oldest first)
|
||||||
|
required: false
|
||||||
|
default: newest
|
||||||
|
selector:
|
||||||
|
select:
|
||||||
|
options:
|
||||||
|
- newest
|
||||||
|
- oldest
|
||||||
|
|
||||||
set_system_prompt:
|
set_system_prompt:
|
||||||
name: Set System Prompt
|
name: Set System Prompt
|
||||||
description: Configure the AI's behavior by setting a system prompt
|
description: Set default system behavior instructions for all future conversations
|
||||||
fields:
|
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:
|
prompt:
|
||||||
name: System Prompt
|
name: System Prompt
|
||||||
description: Instructions that define how the AI should behave and respond
|
description: Instructions that define how the AI should behave and respond
|
||||||
required: true
|
required: true
|
||||||
example: "You are a home automation expert assistant. Provide practical advice focused on smart home technology."
|
|
||||||
selector:
|
selector:
|
||||||
text:
|
text:
|
||||||
multiline: true
|
multiline: true
|
||||||
|
|||||||
@@ -0,0 +1,318 @@
|
|||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"step": {
|
||||||
|
"provider": {
|
||||||
|
"title": "Wählen Sie AI-Anbieter",
|
||||||
|
"description": "Wählen Sie, welchen AI-Dienstanbieter Sie für diese Instanz verwenden möchten.",
|
||||||
|
"data": {
|
||||||
|
"api_provider": "API-Anbieter",
|
||||||
|
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
|
||||||
|
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"provider": {
|
||||||
|
"title": "Anbieter-Einstellungen",
|
||||||
|
"description": "Geben Sie die Verbindungsdetails für Ihren gewählten AI-Anbieter an.",
|
||||||
|
"data": {
|
||||||
|
"name": "Instanzname (z. B. 'GPT Assistant', 'Claude Helper')",
|
||||||
|
"api_key": "API-Schlüssel zur Authentifizierung",
|
||||||
|
"model": "Zu verwendendes AI-Modell",
|
||||||
|
"api_endpoint": "Benutzerdefinierte API-Endpunkt-URL (optional)",
|
||||||
|
"temperature": "Kreativität der Antwort (0-2, niedriger = fokussierter)",
|
||||||
|
"max_tokens": "Maximale Länge der Antwort (1-100000 Token)",
|
||||||
|
"request_interval": "Minimale Zeit zwischen Anfragen (0,1-60 Sekunden)",
|
||||||
|
"api_timeout": "API-Anfrage Timeout in Sekunden (5-600)",
|
||||||
|
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
|
||||||
|
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"title": "HA Text AI Instanz konfigurieren",
|
||||||
|
"description": "Richten Sie eine neue AI-Assistenteninstanz mit Ihrem ausgewählten Anbieter ein.",
|
||||||
|
"data": {
|
||||||
|
"name": "Instanzname (z. B. 'GPT Assistant', 'Claude Helper')",
|
||||||
|
"api_key": "API-Schlüssel zur Authentifizierung",
|
||||||
|
"model": "Zu verwendendes AI-Modell",
|
||||||
|
"temperature": "Kreativität der Antwort (0-2, niedriger = fokussierter)",
|
||||||
|
"max_tokens": "Maximale Länge der Antwort (1-100000 Token)",
|
||||||
|
"api_endpoint": "Benutzerdefinierte API-Endpunkt-URL (optional)",
|
||||||
|
"api_provider": "API-Anbieter",
|
||||||
|
"request_interval": "Minimale Zeit zwischen Anfragen (0,1-60 Sekunden)",
|
||||||
|
"api_timeout": "API-Anfrage Timeout in Sekunden (5-600)",
|
||||||
|
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
|
||||||
|
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"history_storage_error": "Fehler beim Initialisieren des Verlaufspeichers. Überprüfen Sie die Berechtigungen.",
|
||||||
|
"history_rotation_error": "Fehler beim Drehen der Verlaufsdatei.",
|
||||||
|
"history_file_access_error": "Zugriff auf das Verzeichnis für den Verlaufsspeicher nicht möglich.",
|
||||||
|
"name_exists": "Eine Instanz mit diesem Namen existiert bereits",
|
||||||
|
"invalid_name": "Ungültiger Instanzname",
|
||||||
|
"invalid_auth": "Authentifizierung fehlgeschlagen - überprüfen Sie Ihren API-Schlüssel",
|
||||||
|
"invalid_api_key": "Ungültiger API-Schlüssel - bitte überprüfen Sie Ihre Anmeldeinformationen",
|
||||||
|
"cannot_connect": "Verbindung zum API-Dienst fehlgeschlagen",
|
||||||
|
"invalid_model": "Ausgewähltes Modell ist nicht verfügbar",
|
||||||
|
"rate_limit": "Rate-Limit überschritten",
|
||||||
|
"context_length": "Kontextlänge überschritten",
|
||||||
|
"rate_limit_exceeded": "API-Rate-Limit überschritten",
|
||||||
|
"maintenance": "Dienst ist in Wartung",
|
||||||
|
"invalid_response": "Ungültige API-Antwort erhalten",
|
||||||
|
"api_error": "Ein Fehler im API-Dienst ist aufgetreten",
|
||||||
|
"timeout": "Zeitüberschreitung bei der Anfrage",
|
||||||
|
"invalid_instance": "Ungültige Instanz angegeben",
|
||||||
|
"unknown": "Unerwarteter Fehler aufgetreten",
|
||||||
|
"empty": "Name darf nicht leer sein",
|
||||||
|
"invalid_characters": "Name darf nur Buchstaben, Zahlen, Leerzeichen, Unterstriche und Bindestriche enthalten",
|
||||||
|
"name_too_long": "Name darf höchstens 50 Zeichen lang sein"
|
||||||
|
},
|
||||||
|
"abort": {
|
||||||
|
"already_configured": "Instanz bereits konfiguriert"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"step": {
|
||||||
|
"init": {
|
||||||
|
"title": "Anbieter auswählen",
|
||||||
|
"description": "Wählen Sie den AI-Anbieter für diese Instanz. Die Integration wird nach dem Speichern der Änderungen neu geladen.",
|
||||||
|
"data": {
|
||||||
|
"api_provider": "API-Anbieter"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Verbindungs- und Modelleinstellungen",
|
||||||
|
"description": "Konfigurieren Sie API-Anmeldeinformationen und Modellparameter. Änderungen werden nach dem Neuladen der Integration wirksam.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API-Schlüssel",
|
||||||
|
"api_endpoint": "API-Endpunkt-URL",
|
||||||
|
"model": "AI-Modell",
|
||||||
|
"temperature": "Kreativität der Antwort (0-2)",
|
||||||
|
"max_tokens": "Maximale Länge der Antwort (1-100000)",
|
||||||
|
"request_interval": "Minimales Anfrageintervall (0,1-60 Sekunden)",
|
||||||
|
"api_timeout": "API-Anfrage Timeout in Sekunden (5-600)",
|
||||||
|
"context_messages": "Anzahl der vorherigen Nachrichten, die im Kontext enthalten sein sollen (1-20)",
|
||||||
|
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"selector": {
|
||||||
|
"api_provider": {
|
||||||
|
"options": {
|
||||||
|
"openai": "OpenAI (compatible)",
|
||||||
|
"anthropic": "Anthropic (compatible)",
|
||||||
|
"deepseek": "DeepSeek",
|
||||||
|
"gemini": "Google Gemini"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"services": {
|
||||||
|
"ask_question": {
|
||||||
|
"name": "Frage stellen (HA Text AI)",
|
||||||
|
"description": "Stellen Sie eine Frage an das AI-Modell und erhalten Sie eine detaillierte Antwort. Dieser Service gibt jetzt Antwortdaten direkt zurück, wodurch separate Textsensoren und die 255-Zeichen-Begrenzung überflüssig werden. Die Antwort wird auch im Gesprächsverlauf gespeichert.",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Instanz",
|
||||||
|
"description": "Name der zu verwendenden HA Text AI-Instanz"
|
||||||
|
},
|
||||||
|
"question": {
|
||||||
|
"name": "Frage",
|
||||||
|
"description": "Ihre Frage oder Aufforderung für den AI-Assistenten"
|
||||||
|
},
|
||||||
|
"context_messages": {
|
||||||
|
"name": "Kontextnachrichten",
|
||||||
|
"description": "Anzahl der vorherigen Nachrichten, die im Kontext enthalten sein sollen (1-20)"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "Systemaufforderung",
|
||||||
|
"description": "Optionale Systemaufforderung zur Festlegung des Kontexts für diese spezifische Frage"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "Modell",
|
||||||
|
"description": "Wählen Sie das zu verwendende AI-Modell (optional, überschreibt die Standardeinstellung)"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "Temperatur",
|
||||||
|
"description": "Steuert die Kreativität der Antwort (0,0-2,0)"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "Max Tokens",
|
||||||
|
"description": "Maximale Länge der Antwort (1-100000 Token)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Strukturierte Ausgabe",
|
||||||
|
"description": "JSON-Strukturausgabemodus aktivieren. Bei Aktivierung antwortet die KI mit gültigem JSON, das dem angegebenen Schema entspricht."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON-Schema",
|
||||||
|
"description": "JSON-Schema, das die Struktur der erwarteten Antwort definiert. Erforderlich wenn structured_output aktiviert ist."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"clear_history": {
|
||||||
|
"name": "Verlauf löschen",
|
||||||
|
"description": "Löschen Sie alle gespeicherten Fragen und Antworten aus dem Gesprächsverlauf",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Instanz",
|
||||||
|
"description": "Name der HA Text AI-Instanz, für die der Verlauf gelöscht werden soll"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"get_history": {
|
||||||
|
"name": "Verlauf abrufen",
|
||||||
|
"description": "Rufen Sie den Gesprächsverlauf mit optionaler Filterung und Sortierung ab",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Instanz",
|
||||||
|
"description": "Name der HA Text AI-Instanz, von der der Verlauf abgerufen werden soll"
|
||||||
|
},
|
||||||
|
"limit": {
|
||||||
|
"name": "Limit",
|
||||||
|
"description": "Anzahl der zurückzugebenden Gespräche (1-100)"
|
||||||
|
},
|
||||||
|
"filter_model": {
|
||||||
|
"name": "Modell filtern",
|
||||||
|
"description": "Gespräche nach spezifischem AI-Modell filtern"
|
||||||
|
},
|
||||||
|
"start_date": {
|
||||||
|
"name": "Startdatum",
|
||||||
|
"description": "Gespräche ab diesem Datum/Zeit filtern"
|
||||||
|
},
|
||||||
|
"include_metadata": {
|
||||||
|
"name": "Metadaten einbeziehen",
|
||||||
|
"description": "Zusätzliche Informationen wie verwendete Tokens, Antwortzeit usw. einbeziehen"
|
||||||
|
},
|
||||||
|
"sort_order": {
|
||||||
|
"name": "Sortierreihenfolge",
|
||||||
|
"description": "Sortierreihenfolge für die Ergebnisse (neueste oder älteste zuerst)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"set_system_prompt": {
|
||||||
|
"name": "Systemaufforderung festlegen",
|
||||||
|
"description": "Standardverhaltensanweisungen für alle zukünftigen Gespräche festlegen",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Instanz",
|
||||||
|
"description": "Name der HA Text AI-Instanz, für die die Systemaufforderung festgelegt werden soll"
|
||||||
|
},
|
||||||
|
"prompt": {
|
||||||
|
"name": "Systemaufforderung",
|
||||||
|
"description": "Anweisungen, die definieren, wie die AI sich verhalten und antworten soll"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"entity": {
|
||||||
|
"sensor": {
|
||||||
|
"ha_text_ai": {
|
||||||
|
"name": "{name}",
|
||||||
|
"state": {
|
||||||
|
"ready": "Bereit",
|
||||||
|
"processing": "Verarbeitung",
|
||||||
|
"error": "Fehler",
|
||||||
|
"disconnected": "Getrennt",
|
||||||
|
"rate_limited": "Rate limitiert",
|
||||||
|
"maintenance": "Wartung",
|
||||||
|
"initializing": "Initialisierung",
|
||||||
|
"retrying": "Wiederholen",
|
||||||
|
"queued": "In der Warteschlange"
|
||||||
|
},
|
||||||
|
"state_attributes": {
|
||||||
|
"question": {
|
||||||
|
"name": "Letzte Frage"
|
||||||
|
},
|
||||||
|
"response": {
|
||||||
|
"name": "Letzte Antwort"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "Aktuelles Modell"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "Temperatur"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "Max Tokens"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "Systemaufforderung"
|
||||||
|
},
|
||||||
|
"response_time": {
|
||||||
|
"name": "Letzte Antwortzeit"
|
||||||
|
},
|
||||||
|
"total_responses": {
|
||||||
|
"name": "Gesamtantworten"
|
||||||
|
},
|
||||||
|
"error_count": {
|
||||||
|
"name": "Fehleranzahl"
|
||||||
|
},
|
||||||
|
"last_error": {
|
||||||
|
"name": "Letzter Fehler"
|
||||||
|
},
|
||||||
|
"api_status": {
|
||||||
|
"name": "API-Status"
|
||||||
|
},
|
||||||
|
"tokens_used": {
|
||||||
|
"name": "Gesamte verwendete Tokens"
|
||||||
|
},
|
||||||
|
"average_response_time": {
|
||||||
|
"name": "Durchschnittliche Antwortzeit"
|
||||||
|
},
|
||||||
|
"last_request_time": {
|
||||||
|
"name": "Letzte Anfragezeit"
|
||||||
|
},
|
||||||
|
"is_processing": {
|
||||||
|
"name": "Verarbeitungsstatus"
|
||||||
|
},
|
||||||
|
"is_rate_limited": {
|
||||||
|
"name": "Rate-limitiert Status"
|
||||||
|
},
|
||||||
|
"is_maintenance": {
|
||||||
|
"name": "Wartungsstatus"
|
||||||
|
},
|
||||||
|
"api_version": {
|
||||||
|
"name": "API-Version"
|
||||||
|
},
|
||||||
|
"endpoint_status": {
|
||||||
|
"name": "Endpunktstatus"
|
||||||
|
},
|
||||||
|
"performance_metrics": {
|
||||||
|
"name": "Leistungskennzahlen"
|
||||||
|
},
|
||||||
|
"history_size": {
|
||||||
|
"name": "Größe des Verlaufs"
|
||||||
|
},
|
||||||
|
"uptime": {
|
||||||
|
"name": "Betriebszeit"
|
||||||
|
},
|
||||||
|
"total_tokens": {
|
||||||
|
"name": "Gesamte Tokens"
|
||||||
|
},
|
||||||
|
"prompt_tokens": {
|
||||||
|
"name": "Eingabe Tokens"
|
||||||
|
},
|
||||||
|
"completion_tokens": {
|
||||||
|
"name": "Vervollständigungs Tokens"
|
||||||
|
},
|
||||||
|
"successful_requests": {
|
||||||
|
"name": "Erfolgreiche Anfragen"
|
||||||
|
},
|
||||||
|
"failed_requests": {
|
||||||
|
"name": "Fehlgeschlagene Anfragen"
|
||||||
|
},
|
||||||
|
"average_latency": {
|
||||||
|
"name": "Durchschnittliche Latenz"
|
||||||
|
},
|
||||||
|
"max_latency": {
|
||||||
|
"name": "Maximale Latenz"
|
||||||
|
},
|
||||||
|
"min_latency": {
|
||||||
|
"name": "Minimale Latenz"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,56 +1,315 @@
|
|||||||
{
|
{
|
||||||
"config": {
|
"config": {
|
||||||
"step": {
|
"step": {
|
||||||
"user": {
|
"provider": {
|
||||||
"title": "Set up HA text AI",
|
"title": "Select AI Provider",
|
||||||
"description": "Configure your OpenAI integration for smart home interactions",
|
"description": "Choose which AI service provider to use for this instance.",
|
||||||
"data": {
|
"data": {
|
||||||
"api_key": "OpenAI API Key",
|
"api_provider": "API Provider",
|
||||||
"model": "AI Model",
|
"context_messages": "Number of context messages to retain (1-20)",
|
||||||
"temperature": "Temperature",
|
"max_history_size": "Maximum conversation history size (1-100)"
|
||||||
"max_tokens": "Max Tokens",
|
}
|
||||||
"api_endpoint": "API Endpoint",
|
},
|
||||||
"request_interval": "Request Interval"
|
"provider": {
|
||||||
|
"title": "Provider Settings",
|
||||||
|
"description": "Provide connection details for your chosen AI provider.",
|
||||||
|
"data": {
|
||||||
|
"name": "Instance name (e.g., 'GPT Assistant', 'Claude Helper')",
|
||||||
|
"api_key": "API key for authentication",
|
||||||
|
"model": "AI model to use",
|
||||||
|
"api_endpoint": "Custom API endpoint URL (optional)",
|
||||||
|
"temperature": "Response creativity (0-2, lower = more focused)",
|
||||||
|
"max_tokens": "Maximum response length (1-100000 tokens)",
|
||||||
|
"request_interval": "Minimum time between requests (0.1-60 seconds)",
|
||||||
|
"api_timeout": "API request timeout in seconds (5-600)",
|
||||||
|
"context_messages": "Number of context messages to retain (1-20)",
|
||||||
|
"max_history_size": "Maximum conversation history size (1-100)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"title": "Configure HA Text AI Instance",
|
||||||
|
"description": "Set up a new AI assistant instance with your selected provider.",
|
||||||
|
"data": {
|
||||||
|
"name": "Instance name (e.g., 'GPT Assistant', 'Claude Helper')",
|
||||||
|
"api_key": "API key for authentication",
|
||||||
|
"model": "AI model to use",
|
||||||
|
"temperature": "Response creativity (0-2, lower = more focused)",
|
||||||
|
"max_tokens": "Maximum response length (1-100000 tokens)",
|
||||||
|
"api_endpoint": "Custom API endpoint URL (optional)",
|
||||||
|
"api_provider": "API Provider",
|
||||||
|
"request_interval": "Minimum time between requests (0.1-60 seconds)",
|
||||||
|
"api_timeout": "API request timeout in seconds (5-600)",
|
||||||
|
"context_messages": "Number of context messages to retain (1-20)",
|
||||||
|
"max_history_size": "Maximum conversation history size (1-100)"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"error": {
|
"error": {
|
||||||
"invalid_auth": "Invalid API key. Please check your OpenAI API key and try again.",
|
"history_storage_error": "Failed to initialize history storage. Check permissions.",
|
||||||
"cannot_connect": "Failed to connect to API. Please check your internet connection and API endpoint.",
|
"history_rotation_error": "Error during history file rotation.",
|
||||||
"unknown": "Unexpected error occurred. Please check the logs for more details.",
|
"history_file_access_error": "Cannot access history storage directory.",
|
||||||
"already_exists": "This API key is already configured in another integration."
|
"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"
|
||||||
},
|
},
|
||||||
"abort": {
|
"abort": {
|
||||||
"already_configured": "This OpenAI integration is already configured",
|
"already_configured": "Instance already configured"
|
||||||
"auth_failed": "Authentication failed. Please verify your API key."
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "HA text AI Options",
|
"title": "Select Provider",
|
||||||
"description": "Adjust your OpenAI integration settings",
|
"description": "Choose the AI provider for this instance. The integration will reload after saving changes.",
|
||||||
"data": {
|
"data": {
|
||||||
"temperature": "Temperature",
|
"api_provider": "API Provider"
|
||||||
"max_tokens": "Max Tokens",
|
}
|
||||||
"request_interval": "Request Interval"
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Connection & Model Settings",
|
||||||
|
"description": "Configure API credentials and model parameters. Changes will take effect after the integration reloads.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API Key",
|
||||||
|
"api_endpoint": "API Endpoint URL",
|
||||||
|
"model": "AI model",
|
||||||
|
"temperature": "Response creativity (0-2)",
|
||||||
|
"max_tokens": "Maximum response length (1-100000)",
|
||||||
|
"request_interval": "Minimum request interval (0.1-60 seconds)",
|
||||||
|
"api_timeout": "API request timeout in seconds (5-600)",
|
||||||
|
"context_messages": "Number of previous messages to include in context (1-20)",
|
||||||
|
"max_history_size": "Maximum conversation history size (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"selector": {
|
||||||
|
"api_provider": {
|
||||||
|
"options": {
|
||||||
|
"openai": "OpenAI (compatible)",
|
||||||
|
"anthropic": "Anthropic (compatible)",
|
||||||
|
"deepseek": "DeepSeek",
|
||||||
|
"gemini": "Google Gemini"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"services": {
|
||||||
|
"ask_question": {
|
||||||
|
"name": "Ask Question (HA Text AI)",
|
||||||
|
"description": "Send a question to the AI model and receive a detailed response. This service now returns response data directly, eliminating the need for separate text sensors and the 255-character limitation. The response will also be stored in the conversation history.",
|
||||||
|
"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-100000 tokens)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Structured Output",
|
||||||
|
"description": "Enable JSON structured output mode. When enabled, the AI will respond with valid JSON matching the provided schema."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON Schema",
|
||||||
|
"description": "JSON Schema defining the structure of the expected response. Required when structured_output is enabled."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"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": {
|
"entity": {
|
||||||
"sensor": {
|
"sensor": {
|
||||||
"last_response": {
|
"ha_text_ai": {
|
||||||
"name": "Last Response",
|
"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": {
|
"state_attributes": {
|
||||||
"last_updated": {
|
|
||||||
"name": "Last Updated"
|
|
||||||
},
|
|
||||||
"question": {
|
"question": {
|
||||||
"name": "Last Question"
|
"name": "Last Question"
|
||||||
},
|
},
|
||||||
"response": {
|
"response": {
|
||||||
"name": "AI 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,318 @@
|
|||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"step": {
|
||||||
|
"provider": {
|
||||||
|
"title": "Seleccionar proveedor de IA",
|
||||||
|
"description": "Elige qué proveedor de servicio de IA utilizar para esta instancia.",
|
||||||
|
"data": {
|
||||||
|
"api_provider": "Proveedor de API",
|
||||||
|
"context_messages": "Número de mensajes de contexto a retener (1-20)",
|
||||||
|
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"provider": {
|
||||||
|
"title": "Configuración del proveedor",
|
||||||
|
"description": "Proporciona los detalles de conexión para tu proveedor de IA elegido.",
|
||||||
|
"data": {
|
||||||
|
"name": "Nombre de la instancia (por ejemplo, 'Asistente GPT', 'Ayudante Claude')",
|
||||||
|
"api_key": "Clave API para autenticación",
|
||||||
|
"model": "Modelo de IA a utilizar",
|
||||||
|
"api_endpoint": "URL del endpoint de API personalizado (opcional)",
|
||||||
|
"temperature": "Creatividad de la respuesta (0-2, menor = más enfocado)",
|
||||||
|
"max_tokens": "Longitud máxima de la respuesta (1-100000 tokens)",
|
||||||
|
"request_interval": "Tiempo mínimo entre solicitudes (0.1-60 segundos)",
|
||||||
|
"api_timeout": "Tiempo de espera de solicitud API en segundos (5-600)",
|
||||||
|
"context_messages": "Número de mensajes de contexto a retener (1-20)",
|
||||||
|
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"title": "Configurar instancia de IA de texto de HA",
|
||||||
|
"description": "Configura una nueva instancia de asistente de IA con tu proveedor seleccionado.",
|
||||||
|
"data": {
|
||||||
|
"name": "Nombre de la instancia (por ejemplo, 'Asistente GPT', 'Ayudante Claude')",
|
||||||
|
"api_key": "Clave API para autenticación",
|
||||||
|
"model": "Modelo de IA a utilizar",
|
||||||
|
"temperature": "Creatividad de la respuesta (0-2, menor = más enfocado)",
|
||||||
|
"max_tokens": "Longitud máxima de la respuesta (1-100000 tokens)",
|
||||||
|
"api_endpoint": "URL del endpoint de API personalizado (opcional)",
|
||||||
|
"api_provider": "Proveedor de API",
|
||||||
|
"request_interval": "Tiempo mínimo entre solicitudes (0.1-60 segundos)",
|
||||||
|
"api_timeout": "Tiempo de espera de solicitud API en segundos (5-600)",
|
||||||
|
"context_messages": "Número de mensajes de contexto a retener (1-20)",
|
||||||
|
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"history_storage_error": "Error al inicializar el almacenamiento del historial. Verifica los permisos.",
|
||||||
|
"history_rotation_error": "Error durante la rotación del archivo de historial.",
|
||||||
|
"history_file_access_error": "No se puede acceder al directorio de almacenamiento del historial.",
|
||||||
|
"name_exists": "Ya existe una instancia con este nombre",
|
||||||
|
"invalid_name": "Nombre de instancia no válido",
|
||||||
|
"invalid_auth": "La autenticación falló - verifica tu clave API",
|
||||||
|
"invalid_api_key": "Clave API no válida - verifica tus credenciales",
|
||||||
|
"cannot_connect": "Error al conectar con el servicio de API",
|
||||||
|
"invalid_model": "El modelo seleccionado no está disponible",
|
||||||
|
"rate_limit": "Límite de tasa excedido",
|
||||||
|
"context_length": "Longitud del contexto excedida",
|
||||||
|
"rate_limit_exceeded": "Límite de tasa de API excedido",
|
||||||
|
"maintenance": "El servicio está en mantenimiento",
|
||||||
|
"invalid_response": "Respuesta de API no válida recibida",
|
||||||
|
"api_error": "Ocurrió un error en el servicio de API",
|
||||||
|
"timeout": "Se agotó el tiempo de la solicitud",
|
||||||
|
"invalid_instance": "Instancia no válida especificada",
|
||||||
|
"unknown": "Ocurrió un error inesperado",
|
||||||
|
"empty": "El nombre no puede estar vacío",
|
||||||
|
"invalid_characters": "El nombre solo puede contener letras, números, espacios, guiones bajos y guiones",
|
||||||
|
"name_too_long": "El nombre debe tener 50 caracteres o menos"
|
||||||
|
},
|
||||||
|
"abort": {
|
||||||
|
"already_configured": "Instancia ya configurada"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"step": {
|
||||||
|
"init": {
|
||||||
|
"title": "Seleccionar proveedor",
|
||||||
|
"description": "Elige el proveedor de IA para esta instancia. La integración se recargará después de guardar los cambios.",
|
||||||
|
"data": {
|
||||||
|
"api_provider": "Proveedor de API"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Configuración de conexión y modelo",
|
||||||
|
"description": "Configura las credenciales de API y los parámetros del modelo. Los cambios tendrán efecto después de recargar la integración.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "Clave API",
|
||||||
|
"api_endpoint": "URL del endpoint de API",
|
||||||
|
"model": "Modelo de IA",
|
||||||
|
"temperature": "Creatividad de la respuesta (0-2)",
|
||||||
|
"max_tokens": "Longitud máxima de la respuesta (1-100000)",
|
||||||
|
"request_interval": "Intervalo mínimo de solicitud (0.1-60 segundos)",
|
||||||
|
"api_timeout": "Tiempo de espera de solicitud API en segundos (5-600)",
|
||||||
|
"context_messages": "Número de mensajes anteriores a incluir en el contexto (1-20)",
|
||||||
|
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"selector": {
|
||||||
|
"api_provider": {
|
||||||
|
"options": {
|
||||||
|
"openai": "OpenAI (compatible)",
|
||||||
|
"anthropic": "Anthropic (compatible)",
|
||||||
|
"deepseek": "DeepSeek",
|
||||||
|
"gemini": "Google Gemini"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"services": {
|
||||||
|
"ask_question": {
|
||||||
|
"name": "Hacer Pregunta (HA Text AI)",
|
||||||
|
"description": "Envía una pregunta al modelo de IA y recibe una respuesta detallada. Este servicio ahora devuelve datos de respuesta directamente, eliminando la necesidad de sensores de texto separados y la limitación de 255 caracteres. La respuesta también se almacenará en el historial de conversación.",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Instancia",
|
||||||
|
"description": "Nombre de la instancia de IA de Texto de HA a utilizar"
|
||||||
|
},
|
||||||
|
"question": {
|
||||||
|
"name": "Pregunta",
|
||||||
|
"description": "Tu pregunta o solicitud para el asistente de IA"
|
||||||
|
},
|
||||||
|
"context_messages": {
|
||||||
|
"name": "Mensajes de Contexto",
|
||||||
|
"description": "Número de mensajes anteriores a incluir en el contexto (1-20)"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "Indicaciones del Sistema",
|
||||||
|
"description": "Indicaciones opcionales para establecer contexto para esta pregunta específica"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "Modelo",
|
||||||
|
"description": "Selecciona el modelo de IA a utilizar (opcional, anula la configuración predeterminada)"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "Temperatura",
|
||||||
|
"description": "Controla la creatividad de la respuesta (0.0-2.0)"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "Máx. Tokens",
|
||||||
|
"description": "Longitud máxima de la respuesta (1-100000 tokens)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Salida Estructurada",
|
||||||
|
"description": "Habilitar modo de salida JSON estructurada. Cuando está habilitado, la IA responderá con JSON válido que coincida con el esquema proporcionado."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "Esquema JSON",
|
||||||
|
"description": "Esquema JSON que define la estructura de la respuesta esperada. Requerido cuando structured_output está habilitado."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"clear_history": {
|
||||||
|
"name": "Borrar Historial",
|
||||||
|
"description": "Elimina todas las preguntas y respuestas almacenadas del historial de conversación",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Instancia",
|
||||||
|
"description": "Nombre de la instancia de IA de Texto de HA para borrar el historial"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"get_history": {
|
||||||
|
"name": "Obtener Historial",
|
||||||
|
"description": "Recupera el historial de conversación con filtrado y ordenación opcionales",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Instancia",
|
||||||
|
"description": "Nombre de la instancia de IA de Texto de HA para obtener historial"
|
||||||
|
},
|
||||||
|
"limit": {
|
||||||
|
"name": "Límite",
|
||||||
|
"description": "Número de conversaciones a devolver (1-100)"
|
||||||
|
},
|
||||||
|
"filter_model": {
|
||||||
|
"name": "Filtrar Modelo",
|
||||||
|
"description": "Filtrar conversaciones por modelo de IA específico"
|
||||||
|
},
|
||||||
|
"start_date": {
|
||||||
|
"name": "Fecha de Inicio",
|
||||||
|
"description": "Filtrar conversaciones a partir de esta fecha/hora"
|
||||||
|
},
|
||||||
|
"include_metadata": {
|
||||||
|
"name": "Incluir Metadatos",
|
||||||
|
"description": "Incluir información adicional como tokens utilizados, tiempo de respuesta, etc."
|
||||||
|
},
|
||||||
|
"sort_order": {
|
||||||
|
"name": "Orden de Clasificación",
|
||||||
|
"description": "Orden de clasificación para los resultados (más recientes o más antiguos primero)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"set_system_prompt": {
|
||||||
|
"name": "Establecer Indicaciones del Sistema",
|
||||||
|
"description": "Establecer instrucciones de comportamiento del sistema predeterminadas para todas las futuras conversaciones",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Instancia",
|
||||||
|
"description": "Nombre de la instancia de IA de Texto de HA para establecer indicaciones del sistema"
|
||||||
|
},
|
||||||
|
"prompt": {
|
||||||
|
"name": "Indicaciones del Sistema",
|
||||||
|
"description": "Instrucciones que definen cómo debe comportarse y responder la IA"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"entity": {
|
||||||
|
"sensor": {
|
||||||
|
"ha_text_ai": {
|
||||||
|
"name": "{name}",
|
||||||
|
"state": {
|
||||||
|
"ready": "Listo",
|
||||||
|
"processing": "Procesando",
|
||||||
|
"error": "Error",
|
||||||
|
"disconnected": "Desconectado",
|
||||||
|
"rate_limited": "Limitado por tasa",
|
||||||
|
"maintenance": "Mantenimiento",
|
||||||
|
"initializing": "Inicializando",
|
||||||
|
"retrying": "Reintentando",
|
||||||
|
"queued": "En cola"
|
||||||
|
},
|
||||||
|
"state_attributes": {
|
||||||
|
"question": {
|
||||||
|
"name": "Última Pregunta"
|
||||||
|
},
|
||||||
|
"response": {
|
||||||
|
"name": "Última Respuesta"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "Modelo Actual"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "Temperatura"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "Máx. Tokens"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "Indicaciones del Sistema"
|
||||||
|
},
|
||||||
|
"response_time": {
|
||||||
|
"name": "Último Tiempo de Respuesta"
|
||||||
|
},
|
||||||
|
"total_responses": {
|
||||||
|
"name": "Total de Respuestas"
|
||||||
|
},
|
||||||
|
"error_count": {
|
||||||
|
"name": "Conteo de Errores"
|
||||||
|
},
|
||||||
|
"last_error": {
|
||||||
|
"name": "Último Error"
|
||||||
|
},
|
||||||
|
"api_status": {
|
||||||
|
"name": "Estado de API"
|
||||||
|
},
|
||||||
|
"tokens_used": {
|
||||||
|
"name": "Total de Tokens Usados"
|
||||||
|
},
|
||||||
|
"average_response_time": {
|
||||||
|
"name": "Tiempo de Respuesta Promedio"
|
||||||
|
},
|
||||||
|
"last_request_time": {
|
||||||
|
"name": "Último Tiempo de Solicitud"
|
||||||
|
},
|
||||||
|
"is_processing": {
|
||||||
|
"name": "Estado de Procesamiento"
|
||||||
|
},
|
||||||
|
"is_rate_limited": {
|
||||||
|
"name": "Estado Limitado por Tasa"
|
||||||
|
},
|
||||||
|
"is_maintenance": {
|
||||||
|
"name": "Estado de Mantenimiento"
|
||||||
|
},
|
||||||
|
"api_version": {
|
||||||
|
"name": "Versión de API"
|
||||||
|
},
|
||||||
|
"endpoint_status": {
|
||||||
|
"name": "Estado del Endpoint"
|
||||||
|
},
|
||||||
|
"performance_metrics": {
|
||||||
|
"name": "Métricas de Rendimiento"
|
||||||
|
},
|
||||||
|
"history_size": {
|
||||||
|
"name": "Tamaño del Historial"
|
||||||
|
},
|
||||||
|
"uptime": {
|
||||||
|
"name": "Tiempo de Actividad"
|
||||||
|
},
|
||||||
|
"total_tokens": {
|
||||||
|
"name": "Total de Tokens"
|
||||||
|
},
|
||||||
|
"prompt_tokens": {
|
||||||
|
"name": "Tokens de Solicitud"
|
||||||
|
},
|
||||||
|
"completion_tokens": {
|
||||||
|
"name": "Tokens de Finalización"
|
||||||
|
},
|
||||||
|
"successful_requests": {
|
||||||
|
"name": "Solicitudes Exitosas"
|
||||||
|
},
|
||||||
|
"failed_requests": {
|
||||||
|
"name": "Solicitudes Fallidas"
|
||||||
|
},
|
||||||
|
"average_latency": {
|
||||||
|
"name": "Latencia Promedio"
|
||||||
|
},
|
||||||
|
"max_latency": {
|
||||||
|
"name": "Latencia Máxima"
|
||||||
|
},
|
||||||
|
"min_latency": {
|
||||||
|
"name": "Latencia Mínima"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"step": {
|
||||||
|
"provider": {
|
||||||
|
"title": "प्रदाता सेटिंग्स",
|
||||||
|
"description": "आपके द्वारा चुने गए एआई प्रदाता के लिए कनेक्शन विवरण प्रदान करें।",
|
||||||
|
"data": {
|
||||||
|
"name": "उदाहरण का नाम (जैसे, 'जीपीटी सहायक', 'क्लॉड सहायक')",
|
||||||
|
"api_key": "प्रमाणीकरण के लिए एपीआई कुंजी",
|
||||||
|
"model": "उपयोग करने के लिए एआई मॉडल",
|
||||||
|
"api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)",
|
||||||
|
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)",
|
||||||
|
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)",
|
||||||
|
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
|
||||||
|
"api_timeout": "एपीआई अनुरोध टाइमआउट सेकंड में (5-600)",
|
||||||
|
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
||||||
|
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"title": "एचए टेक्स्ट एआई उदाहरण कॉन्फ़िगर करें",
|
||||||
|
"description": "अपने चुने हुए प्रदाता के साथ एक नया एआई सहायक उदाहरण सेट करें।",
|
||||||
|
"data": {
|
||||||
|
"name": "उदाहरण का नाम (जैसे, 'जीपीटी सहायक', 'क्लॉड सहायक')",
|
||||||
|
"api_key": "प्रमाणीकरण के लिए एपीआई कुंजी",
|
||||||
|
"model": "उपयोग करने के लिए एआई मॉडल",
|
||||||
|
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)",
|
||||||
|
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)",
|
||||||
|
"api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)",
|
||||||
|
"api_provider": "एपीआई प्रदाता",
|
||||||
|
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
|
||||||
|
"api_timeout": "एपीआई अनुरोध टाइमआउट सेकंड में (5-600)",
|
||||||
|
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
||||||
|
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"history_storage_error": "इतिहास भंडारण प्रारंभ करने में विफल। अनुमतियों की जांच करें।",
|
||||||
|
"history_rotation_error": "इतिहास फ़ाइल घुमाने के दौरान त्रुटि।",
|
||||||
|
"history_file_access_error": "इतिहास भंडारण निर्देशिका तक पहुंच नहीं है।",
|
||||||
|
"name_exists": "इस नाम के साथ एक उदाहरण पहले से मौजूद है",
|
||||||
|
"invalid_name": "अमान्य उदाहरण नाम",
|
||||||
|
"invalid_auth": "प्रमाणीकरण विफल - अपनी एपीआई कुंजी की जांच करें",
|
||||||
|
"invalid_api_key": "अमान्य एपीआई कुंजी - कृपया अपनी क्रेडेंशियल्स की पुष्टि करें",
|
||||||
|
"cannot_connect": "एपीआई सेवा से कनेक्ट करने में विफल",
|
||||||
|
"invalid_model": "चुना हुआ मॉडल उपलब्ध नहीं है",
|
||||||
|
"rate_limit": "रेट सीमा पार",
|
||||||
|
"context_length": "संदर्भ लंबाई पार",
|
||||||
|
"rate_limit_exceeded": "एपीआई रेट सीमा पार",
|
||||||
|
"maintenance": "सेवा रखरखाव में है",
|
||||||
|
"invalid_response": "अमान्य एपीआई प्रतिक्रिया प्राप्त हुई",
|
||||||
|
"api_error": "एपीआई सेवा में त्रुटि हुई",
|
||||||
|
"timeout": "अनुरोध समय सीमा समाप्त",
|
||||||
|
"invalid_instance": "अमान्य उदाहरण निर्दिष्ट किया गया",
|
||||||
|
"unknown": "अप्रत्याशित त्रुटि हुई",
|
||||||
|
"empty": "नाम खाली नहीं हो सकता",
|
||||||
|
"invalid_characters": "नाम में केवल अक्षर, अंक, रिक्त स्थान, अंडरस्कोर और हाइफन हो सकते हैं",
|
||||||
|
"name_too_long": "नाम 50 अक्षरों या उससे कम होना चाहिए"
|
||||||
|
},
|
||||||
|
"abort": {
|
||||||
|
"already_configured": "उदाहरण पहले से कॉन्फ़िगर किया गया है"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"step": {
|
||||||
|
"init": {
|
||||||
|
"title": "प्रदाता चुनें",
|
||||||
|
"description": "इस उदाहरण के लिए एआई प्रदाता चुनें। परिवर्तन सहेजने के बाद एकीकरण पुनः लोड होगा।",
|
||||||
|
"data": {
|
||||||
|
"api_provider": "एपीआई प्रदाता"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "कनेक्शन और मॉडल सेटिंग्स",
|
||||||
|
"description": "एपीआई क्रेडेंशियल और मॉडल पैरामीटर कॉन्फ़िगर करें। एकीकरण पुनः लोड होने के बाद परिवर्तन प्रभावी होंगे।",
|
||||||
|
"data": {
|
||||||
|
"api_key": "एपीआई कुंजी",
|
||||||
|
"api_endpoint": "एपीआई एंडपॉइंट यूआरएल",
|
||||||
|
"model": "एआई मॉडल",
|
||||||
|
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2)",
|
||||||
|
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000)",
|
||||||
|
"request_interval": "न्यूनतम अनुरोध अंतराल (0.1-60 सेकंड)",
|
||||||
|
"api_timeout": "एपीआई अनुरोध टाइमआउट सेकंड में (5-600)",
|
||||||
|
"context_messages": "संदर्भ में शामिल करने के लिए पिछले संदेशों की संख्या (1-20)",
|
||||||
|
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"selector": {
|
||||||
|
"api_provider": {
|
||||||
|
"options": {
|
||||||
|
"openai": "OpenAI (अनुकूलित)",
|
||||||
|
"anthropic": "Anthropic (अनुकूलित)",
|
||||||
|
"deepseek": "DeepSeek",
|
||||||
|
"gemini": "Google Gemini"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"services": {
|
||||||
|
"ask_question": {
|
||||||
|
"name": "प्रश्न पूछें (HA Text AI)",
|
||||||
|
"description": "AI मॉडल को प्रश्न भेजें और विस्तृत उत्तर प्राप्त करें। यह सेवा अब प्रत्यक्ष रूप से प्रतिक्रिया डेटा वापस करती है, अलग टेक्स्ट सेंसर की आवश्यकता और 255 वर्ण की सीमा को समाप्त करती है। प्रतिक्रिया को बातचीत के इतिहास में भी संग्रहीत किया जाएगा।",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "उदाहरण",
|
||||||
|
"description": "उपयोग करने के लिए एचए टेक्स्ट एआई उदाहरण का नाम"
|
||||||
|
},
|
||||||
|
"question": {
|
||||||
|
"name": "प्रश्न",
|
||||||
|
"description": "आपका प्रश्न या एआई सहायक के लिए प्रॉम्प्ट"
|
||||||
|
},
|
||||||
|
"context_messages": {
|
||||||
|
"name": "संदर्भ संदेश",
|
||||||
|
"description": "संदर्भ में शामिल करने के लिए पिछले संदेशों की संख्या (1-20)"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "सिस्टम प्रॉम्प्ट",
|
||||||
|
"description": "इस विशेष प्रश्न के लिए संदर्भ सेट करने के लिए वैकल्पिक सिस्टम प्रॉम्प्ट"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "मॉडल",
|
||||||
|
"description": "उपयोग करने के लिए एआई मॉडल का चयन करें (वैकल्पिक, डिफ़ॉल्ट सेटिंग को ओवरराइड करता है)"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "तापमान",
|
||||||
|
"description": "प्रतिक्रिया की रचनात्मकता को नियंत्रित करता है (0.0-2.0)"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "अधिकतम टोकन",
|
||||||
|
"description": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "संरचित आउटपुट",
|
||||||
|
"description": "JSON संरचित आउटपुट मोड सक्षम करें। सक्षम होने पर, AI प्रदान किए गए स्कीमा से मेल खाने वाले वैध JSON के साथ प्रतिक्रिया देगा।"
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON स्कीमा",
|
||||||
|
"description": "अपेक्षित प्रतिक्रिया की संरचना को परिभाषित करने वाला JSON स्कीमा। structured_output सक्षम होने पर आवश्यक।"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"clear_history": {
|
||||||
|
"name": "इतिहास साफ करें",
|
||||||
|
"description": "बातचीत के इतिहास से सभी संग्रहीत प्रश्नों और प्रतिक्रियाओं को हटाएं",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "उदाहरण",
|
||||||
|
"description": "इतिहास साफ़ करने के लिए एचए टेक्स्ट एआई उदाहरण का नाम"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"get_history": {
|
||||||
|
"name": "इतिहास प्राप्त करें",
|
||||||
|
"description": "वैकल्पिक फ़िल्टरिंग और छंटाई के साथ बातचीत का इतिहास प्राप्त करें",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "उदाहरण",
|
||||||
|
"description": "इतिहास प्राप्त करने के लिए एचए टेक्स्ट एआई उदाहरण का नाम"
|
||||||
|
},
|
||||||
|
"limit": {
|
||||||
|
"name": "सीमा",
|
||||||
|
"description": "वापस करने के लिए बातचीत की संख्या (1-100)"
|
||||||
|
},
|
||||||
|
"filter_model": {
|
||||||
|
"name": "फिल्टर मॉडल",
|
||||||
|
"description": "विशिष्ट एआई मॉडल द्वारा बातचीत को फ़िल्टर करें"
|
||||||
|
},
|
||||||
|
"start_date": {
|
||||||
|
"name": "शुरुआत की तारीख",
|
||||||
|
"description": "इस दिन/समय से शुरू होने वाली बातचीत को फ़िल्टर करें"
|
||||||
|
},
|
||||||
|
"include_metadata": {
|
||||||
|
"name": "मेटाडेटा शामिल करें",
|
||||||
|
"description": "उपयोग किए गए टोकन, प्रतिक्रिया समय आदि जैसी अतिरिक्त जानकारी शामिल करें।"
|
||||||
|
},
|
||||||
|
"sort_order": {
|
||||||
|
"name": "छंटाई क्रम",
|
||||||
|
"description": "परिणामों के लिए छंटाई क्रम (नवीनतम या सबसे पुराना पहले)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"set_system_prompt": {
|
||||||
|
"name": "सिस्टम प्रॉम्प्ट सेट करें",
|
||||||
|
"description": "सभी भविष्य की बातचीत के लिए डिफ़ॉल्ट सिस्टम व्यवहार निर्देश सेट करें",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "उदाहरण",
|
||||||
|
"description": "सिस्टम प्रॉम्प्ट सेट करने के लिए एचए टेक्स्ट एआई उदाहरण का नाम"
|
||||||
|
},
|
||||||
|
"prompt": {
|
||||||
|
"name": "सिस्टम प्रॉम्प्ट",
|
||||||
|
"description": "निर्देश जो यह परिभाषित करते हैं कि एआई को कैसे व्यवहार करना चाहिए और प्रतिक्रिया देनी चाहिए"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"entity": {
|
||||||
|
"sensor": {
|
||||||
|
"ha_text_ai": {
|
||||||
|
"name": "{name}",
|
||||||
|
"state": {
|
||||||
|
"ready": "तैयार",
|
||||||
|
"processing": "प्रसंस्करण",
|
||||||
|
"error": "त्रुटि",
|
||||||
|
"disconnected": "असंयुक्त",
|
||||||
|
"rate_limited": "रेट सीमित",
|
||||||
|
"maintenance": "रखरखाव",
|
||||||
|
"initializing": "प्रारंभिककरण",
|
||||||
|
"retrying": "पुनः प्रयास कर रहा है",
|
||||||
|
"queued": "क्यू में"
|
||||||
|
},
|
||||||
|
"state_attributes": {
|
||||||
|
"question": {
|
||||||
|
"name": "अंतिम प्रश्न"
|
||||||
|
},
|
||||||
|
"response": {
|
||||||
|
"name": "अंतिम प्रतिक्रिया"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "वर्तमान मॉडल"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "तापमान"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "अधिकतम टोकन"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "सिस्टम प्रॉम्प्ट"
|
||||||
|
},
|
||||||
|
"response_time": {
|
||||||
|
"name": "अंतिम प्रतिक्रिया का समय"
|
||||||
|
},
|
||||||
|
"total_responses": {
|
||||||
|
"name": "कुल प्रतिक्रियाएं"
|
||||||
|
},
|
||||||
|
"error_count": {
|
||||||
|
"name": "त्रुटियों की संख्या"
|
||||||
|
},
|
||||||
|
"last_error": {
|
||||||
|
"name": "अंतिम त्रुटि"
|
||||||
|
},
|
||||||
|
"api_status": {
|
||||||
|
"name": "एपीआई स्थिति"
|
||||||
|
},
|
||||||
|
"tokens_used": {
|
||||||
|
"name": "कुल उपयोग किए गए टोकन"
|
||||||
|
},
|
||||||
|
"average_response_time": {
|
||||||
|
"name": "औसत प्रतिक्रिया समय"
|
||||||
|
},
|
||||||
|
"last_request_time": {
|
||||||
|
"name": "अंतिम अनुरोध का समय"
|
||||||
|
},
|
||||||
|
"is_processing": {
|
||||||
|
"name": "प्रसंस्करण स्थिति"
|
||||||
|
},
|
||||||
|
"is_rate_limited": {
|
||||||
|
"name": "रेट सीमित स्थिति"
|
||||||
|
},
|
||||||
|
"is_maintenance": {
|
||||||
|
"name": "रखरखाव स्थिति"
|
||||||
|
},
|
||||||
|
"api_version": {
|
||||||
|
"name": "एपीआई संस्करण"
|
||||||
|
},
|
||||||
|
"endpoint_status": {
|
||||||
|
"name": "एंडपॉइंट स्थिति"
|
||||||
|
},
|
||||||
|
"performance_metrics": {
|
||||||
|
"name": "प्रदर्शन मैट्रिक्स"
|
||||||
|
},
|
||||||
|
"history_size": {
|
||||||
|
"name": "इतिहास का आकार"
|
||||||
|
},
|
||||||
|
"uptime": {
|
||||||
|
"name": "अपटाइम"
|
||||||
|
},
|
||||||
|
"total_tokens": {
|
||||||
|
"name": "कुल टोकन"
|
||||||
|
},
|
||||||
|
"prompt_tokens": {
|
||||||
|
"name": "प्रॉम्प्ट टोकन"
|
||||||
|
},
|
||||||
|
"completion_tokens": {
|
||||||
|
"name": "पूर्णता टोकन"
|
||||||
|
},
|
||||||
|
"successful_requests": {
|
||||||
|
"name": "सफल अनुरोध"
|
||||||
|
},
|
||||||
|
"failed_requests": {
|
||||||
|
"name": "विफल अनुरोध"
|
||||||
|
},
|
||||||
|
"average_latency": {
|
||||||
|
"name": "औसत विलंबता"
|
||||||
|
},
|
||||||
|
"max_latency": {
|
||||||
|
"name": "अधिकतम विलंबता"
|
||||||
|
},
|
||||||
|
"min_latency": {
|
||||||
|
"name": "न्यूनतम विलंबता"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"step": {
|
||||||
|
"provider": {
|
||||||
|
"title": "Seleziona fornitore AI",
|
||||||
|
"description": "Scegli quale fornitore di servizi AI utilizzare per questa istanza.",
|
||||||
|
"data": {
|
||||||
|
"api_provider": "Fornitore API",
|
||||||
|
"context_messages": "Numero di messaggi di contesto da mantenere (1-20)",
|
||||||
|
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"provider": {
|
||||||
|
"title": "Impostazioni fornitore",
|
||||||
|
"description": "Fornisci i dettagli di connessione per il tuo fornitore di AI scelto.",
|
||||||
|
"data": {
|
||||||
|
"name": "Nome dell'istanza (es. 'Assistente GPT', 'Aiuto Claude')",
|
||||||
|
"api_key": "Chiave API per l'autenticazione",
|
||||||
|
"model": "Modello AI da utilizzare",
|
||||||
|
"api_endpoint": "URL dell'endpoint API personalizzato (opzionale)",
|
||||||
|
"temperature": "Creatività della risposta (0-2, più basso = più focalizzato)",
|
||||||
|
"max_tokens": "Lunghezza massima della risposta (1-100000 token)",
|
||||||
|
"request_interval": "Tempo minimo tra le richieste (0.1-60 secondi)",
|
||||||
|
"api_timeout": "Timeout della richiesta API in secondi (5-600)",
|
||||||
|
"context_messages": "Numero di messaggi di contesto da mantenere (1-20)",
|
||||||
|
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"title": "Configura istanza AI di testo HA",
|
||||||
|
"description": "Imposta una nuova istanza di assistente AI con il fornitore selezionato.",
|
||||||
|
"data": {
|
||||||
|
"name": "Nome dell'istanza (es. 'Assistente GPT', 'Aiuto Claude')",
|
||||||
|
"api_key": "Chiave API per l'autenticazione",
|
||||||
|
"model": "Modello AI da utilizzare",
|
||||||
|
"temperature": "Creatività della risposta (0-2, più basso = più focalizzato)",
|
||||||
|
"max_tokens": "Lunghezza massima della risposta (1-100000 token)",
|
||||||
|
"api_endpoint": "URL dell'endpoint API personalizzato (opzionale)",
|
||||||
|
"api_provider": "Fornitore API",
|
||||||
|
"request_interval": "Tempo minimo tra le richieste (0.1-60 secondi)",
|
||||||
|
"api_timeout": "Timeout della richiesta API in secondi (5-600)",
|
||||||
|
"context_messages": "Numero di messaggi di contesto da mantenere (1-20)",
|
||||||
|
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"history_storage_error": "Impossibile inizializzare la memorizzazione della cronologia. Controlla i permessi.",
|
||||||
|
"history_rotation_error": "Errore durante la rotazione del file di cronologia.",
|
||||||
|
"history_file_access_error": "Impossibile accedere alla directory di memorizzazione della cronologia.",
|
||||||
|
"name_exists": "Esiste già un'istanza con questo nome",
|
||||||
|
"invalid_name": "Nome dell'istanza non valido",
|
||||||
|
"invalid_auth": "Autenticazione fallita - controlla la tua chiave API",
|
||||||
|
"invalid_api_key": "Chiave API non valida - verifica le tue credenziali",
|
||||||
|
"cannot_connect": "Impossibile connettersi al servizio API",
|
||||||
|
"invalid_model": "Il modello selezionato non è disponibile",
|
||||||
|
"rate_limit": "Limite di frequenza superato",
|
||||||
|
"context_length": "Lunghezza del contesto superata",
|
||||||
|
"rate_limit_exceeded": "Limite di frequenza API superato",
|
||||||
|
"maintenance": "Il servizio è in manutenzione",
|
||||||
|
"invalid_response": "Risposta API non valida ricevuta",
|
||||||
|
"api_error": "Si è verificato un errore nel servizio API",
|
||||||
|
"timeout": "Richiesta scaduta",
|
||||||
|
"invalid_instance": "Istanze specificata non valida",
|
||||||
|
"unknown": "Si è verificato un errore imprevisto",
|
||||||
|
"empty": "Il nome non può essere vuoto",
|
||||||
|
"invalid_characters": "Il nome può contenere solo lettere, numeri, spazi, trattini bassi e trattini",
|
||||||
|
"name_too_long": "Il nome deve essere lungo 50 caratteri o meno"
|
||||||
|
},
|
||||||
|
"abort": {
|
||||||
|
"already_configured": "Istanze già configurata"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"step": {
|
||||||
|
"init": {
|
||||||
|
"title": "Seleziona fornitore",
|
||||||
|
"description": "Scegli il fornitore AI per questa istanza. L'integrazione verrà ricaricata dopo aver salvato le modifiche.",
|
||||||
|
"data": {
|
||||||
|
"api_provider": "Fornitore API"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Impostazioni di connessione e modello",
|
||||||
|
"description": "Configura le credenziali API e i parametri del modello. Le modifiche avranno effetto dopo il ricaricamento dell'integrazione.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "Chiave API",
|
||||||
|
"api_endpoint": "URL dell'endpoint API",
|
||||||
|
"model": "Modello AI",
|
||||||
|
"temperature": "Creatività della risposta (0-2)",
|
||||||
|
"max_tokens": "Lunghezza massima della risposta (1-100000)",
|
||||||
|
"request_interval": "Intervallo minimo di richiesta (0.1-60 secondi)",
|
||||||
|
"api_timeout": "Timeout della richiesta API in secondi (5-600)",
|
||||||
|
"context_messages": "Numero di messaggi precedenti da includere nel contesto (1-20)",
|
||||||
|
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"selector": {
|
||||||
|
"api_provider": {
|
||||||
|
"options": {
|
||||||
|
"openai": "OpenAI (compatibile)",
|
||||||
|
"anthropic": "Anthropic (compatibile)",
|
||||||
|
"deepseek": "DeepSeek",
|
||||||
|
"gemini": "Google Gemini"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"services": {
|
||||||
|
"ask_question": {
|
||||||
|
"name": "Fai una domanda (HA Text AI)",
|
||||||
|
"description": "Invia una domanda al modello AI e ricevi una risposta dettagliata. Questo servizio ora restituisce i dati di risposta direttamente, eliminando la necessità di sensori di testo separati e la limitazione di 255 caratteri. La risposta sarà anche memorizzata nella cronologia delle conversazioni.",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Istanze",
|
||||||
|
"description": "Nome dell'istanza HA Text AI da utilizzare"
|
||||||
|
},
|
||||||
|
"question": {
|
||||||
|
"name": "Domanda",
|
||||||
|
"description": "La tua domanda o richiesta per l'assistente AI"
|
||||||
|
},
|
||||||
|
"context_messages": {
|
||||||
|
"name": "Messaggi di contesto",
|
||||||
|
"description": "Numero di messaggi precedenti da includere nel contesto (1-20)"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "Prompt di sistema",
|
||||||
|
"description": "Prompt di sistema opzionale per impostare il contesto per questa specifica domanda"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "Modello",
|
||||||
|
"description": "Seleziona il modello AI da utilizzare (opzionale, sovrascrive l'impostazione predefinita)"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "Temperatura",
|
||||||
|
"description": "Controlla la creatività della risposta (0.0-2.0)"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "Token massimi",
|
||||||
|
"description": "Lunghezza massima della risposta (1-100000 token)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Output Strutturato",
|
||||||
|
"description": "Abilita la modalità di output JSON strutturato. Quando abilitato, l'IA risponderà con JSON valido corrispondente allo schema fornito."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "Schema JSON",
|
||||||
|
"description": "Schema JSON che definisce la struttura della risposta attesa. Richiesto quando structured_output è abilitato."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"clear_history": {
|
||||||
|
"name": "Cancella cronologia",
|
||||||
|
"description": "Elimina tutte le domande e risposte memorizzate dalla cronologia delle conversazioni",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Istanze",
|
||||||
|
"description": "Nome dell'istanza HA Text AI per cui cancellare la cronologia"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"get_history": {
|
||||||
|
"name": "Ottieni cronologia",
|
||||||
|
"description": "Recupera la cronologia delle conversazioni con opzioni di filtro e ordinamento",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Istanze",
|
||||||
|
"description": "Nome dell'istanza HA Text AI da cui recuperare la cronologia"
|
||||||
|
},
|
||||||
|
"limit": {
|
||||||
|
"name": "Limite",
|
||||||
|
"description": "Numero di conversazioni da restituire (1-100)"
|
||||||
|
},
|
||||||
|
"filter_model": {
|
||||||
|
"name": "Filtra modello",
|
||||||
|
"description": "Filtra le conversazioni per modello AI specifico"
|
||||||
|
},
|
||||||
|
"start_date": {
|
||||||
|
"name": "Data di inizio",
|
||||||
|
"description": "Filtra le conversazioni a partire da questa data/ora"
|
||||||
|
},
|
||||||
|
"include_metadata": {
|
||||||
|
"name": "Includi metadati",
|
||||||
|
"description": "Includi informazioni aggiuntive come token utilizzati, tempo di risposta, ecc."
|
||||||
|
},
|
||||||
|
"sort_order": {
|
||||||
|
"name": "Ordine di ordinamento",
|
||||||
|
"description": "Ordine di ordinamento per i risultati (più recenti o più vecchi per primi)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"set_system_prompt": {
|
||||||
|
"name": "Imposta prompt di sistema",
|
||||||
|
"description": "Imposta le istruzioni di comportamento predefinite per tutte le future conversazioni",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Istanze",
|
||||||
|
"description": "Nome dell'istanza HA Text AI per cui impostare il prompt di sistema"
|
||||||
|
},
|
||||||
|
"prompt": {
|
||||||
|
"name": "Prompt di sistema",
|
||||||
|
"description": "Istruzioni che definiscono come l'AI dovrebbe comportarsi e rispondere"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"entity": {
|
||||||
|
"sensor": {
|
||||||
|
"ha_text_ai": {
|
||||||
|
"name": "{name}",
|
||||||
|
"state": {
|
||||||
|
"ready": "Pronto",
|
||||||
|
"processing": "Elaborazione",
|
||||||
|
"error": "Errore",
|
||||||
|
"disconnected": "Disconnesso",
|
||||||
|
"rate_limited": "Limite di frequenza",
|
||||||
|
"maintenance": "Manutenzione",
|
||||||
|
"initializing": "Inizializzazione",
|
||||||
|
"retrying": "Riprova",
|
||||||
|
"queued": "In coda"
|
||||||
|
},
|
||||||
|
"state_attributes": {
|
||||||
|
"question": {
|
||||||
|
"name": "Ultima domanda"
|
||||||
|
},
|
||||||
|
"response": {
|
||||||
|
"name": "Ultima risposta"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "Modello attuale"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "Temperatura"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "Token massimi"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "Prompt di sistema"
|
||||||
|
},
|
||||||
|
"response_time": {
|
||||||
|
"name": "Ultimo tempo di risposta"
|
||||||
|
},
|
||||||
|
"total_responses": {
|
||||||
|
"name": "Risposte totali"
|
||||||
|
},
|
||||||
|
"error_count": {
|
||||||
|
"name": "Conteggio errori"
|
||||||
|
},
|
||||||
|
"last_error": {
|
||||||
|
"name": "Ultimo errore"
|
||||||
|
},
|
||||||
|
"api_status": {
|
||||||
|
"name": "Stato API"
|
||||||
|
},
|
||||||
|
"tokens_used": {
|
||||||
|
"name": "Token totali utilizzati"
|
||||||
|
},
|
||||||
|
"average_response_time": {
|
||||||
|
"name": "Tempo medio di risposta"
|
||||||
|
},
|
||||||
|
"last_request_time": {
|
||||||
|
"name": "Ultimo tempo di richiesta"
|
||||||
|
},
|
||||||
|
"is_processing": {
|
||||||
|
"name": "Stato di elaborazione"
|
||||||
|
},
|
||||||
|
"is_rate_limited": {
|
||||||
|
"name": "Stato limite di frequenza"
|
||||||
|
},
|
||||||
|
"is_maintenance": {
|
||||||
|
"name": "Stato di manutenzione"
|
||||||
|
},
|
||||||
|
"api_version": {
|
||||||
|
"name": "Versione API"
|
||||||
|
},
|
||||||
|
"endpoint_status": {
|
||||||
|
"name": "Stato dell'endpoint"
|
||||||
|
},
|
||||||
|
"performance_metrics": {
|
||||||
|
"name": "Metriche di prestazione"
|
||||||
|
},
|
||||||
|
"history_size": {
|
||||||
|
"name": "Dimensione della cronologia"
|
||||||
|
},
|
||||||
|
"uptime": {
|
||||||
|
"name": "Tempo di attività"
|
||||||
|
},
|
||||||
|
"total_tokens": {
|
||||||
|
"name": "Token totali"
|
||||||
|
},
|
||||||
|
"prompt_tokens": {
|
||||||
|
"name": "Token di prompt"
|
||||||
|
},
|
||||||
|
"completion_tokens": {
|
||||||
|
"name": "Token di completamento"
|
||||||
|
},
|
||||||
|
"successful_requests": {
|
||||||
|
"name": "Richieste riuscite"
|
||||||
|
},
|
||||||
|
"failed_requests": {
|
||||||
|
"name": "Richieste fallite"
|
||||||
|
},
|
||||||
|
"average_latency": {
|
||||||
|
"name": "Latenza media"
|
||||||
|
},
|
||||||
|
"max_latency": {
|
||||||
|
"name": "Latenza massima"
|
||||||
|
},
|
||||||
|
"min_latency": {
|
||||||
|
"name": "Latenza minima"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,318 @@
|
|||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"step": {
|
||||||
|
"provider": {
|
||||||
|
"title": "Выбор провайдера ИИ",
|
||||||
|
"description": "Выберите сервис искусственного интеллекта для этого экземпляра.",
|
||||||
|
"data": {
|
||||||
|
"api_provider": "Провайдер API",
|
||||||
|
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
||||||
|
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"provider": {
|
||||||
|
"title": "Настройки провайдера",
|
||||||
|
"description": "Укажите параметры подключения для выбранного провайдера ИИ.",
|
||||||
|
"data": {
|
||||||
|
"name": "Название экземпляра (например, 'GPT Помощник', 'Клод Ассистент')",
|
||||||
|
"api_key": "API-ключ для аутентификации",
|
||||||
|
"model": "Модель ИИ для использования",
|
||||||
|
"api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)",
|
||||||
|
"temperature": "Креативность ответа (0-2, меньше = более сфокусированно)",
|
||||||
|
"max_tokens": "Максимальная длина ответа (1-100000 токенов)",
|
||||||
|
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||||
|
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||||
|
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
||||||
|
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"title": "Настройка экземпляра текстового ИИ для Home Assistant",
|
||||||
|
"description": "Настройте новый экземпляр ИИ-помощника с выбранным провайдером.",
|
||||||
|
"data": {
|
||||||
|
"name": "Название экземпляра (например, 'GPT Помощник', 'Клод Ассистент')",
|
||||||
|
"api_key": "API-ключ для аутентификации",
|
||||||
|
"model": "Модель ИИ для использования",
|
||||||
|
"temperature": "Креативность ответа (0-2, меньше = более сфокусированно)",
|
||||||
|
"max_tokens": "Максимальная длина ответа (1-100000 токенов)",
|
||||||
|
"api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)",
|
||||||
|
"api_provider": "Провайдер API",
|
||||||
|
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||||
|
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||||
|
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
||||||
|
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"history_storage_error": "Не удалось инициализировать хранилище истории. Проверьте разрешения.",
|
||||||
|
"history_rotation_error": "Ошибка при ротации файла истории.",
|
||||||
|
"history_file_access_error": "Невозможно получить доступ к директории хранения истории.",
|
||||||
|
"name_exists": "Экземпляр с таким именем уже существует",
|
||||||
|
"invalid_name": "Недопустимое имя экземпляра",
|
||||||
|
"invalid_auth": "Ошибка аутентификации - проверьте API-ключ",
|
||||||
|
"invalid_api_key": "Недопустимый API-ключ - пожалуйста, проверьте учетные данные",
|
||||||
|
"cannot_connect": "Не удалось подключиться к сервису API",
|
||||||
|
"invalid_model": "Выбранная модель недоступна",
|
||||||
|
"rate_limit": "Превышен лимит запросов",
|
||||||
|
"context_length": "Превышена длина контекста",
|
||||||
|
"rate_limit_exceeded": "Превышен лимит запросов API",
|
||||||
|
"maintenance": "Сервис находится на техническом обслуживании",
|
||||||
|
"invalid_response": "Получен некорректный ответ API",
|
||||||
|
"api_error": "Произошла ошибка сервиса API",
|
||||||
|
"timeout": "Время ожидания запроса истекло",
|
||||||
|
"invalid_instance": "Указан некорректный экземпляр",
|
||||||
|
"unknown": "Произошла непредвиденная ошибка",
|
||||||
|
"empty": "Имя не может быть пустым",
|
||||||
|
"invalid_characters": "Имя может содержать только буквы, цифры, пробелы, подчеркивания и дефисы",
|
||||||
|
"name_too_long": "Имя должно быть не длиннее 50 символов"
|
||||||
|
},
|
||||||
|
"abort": {
|
||||||
|
"already_configured": "Экземпляр уже настроен"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"step": {
|
||||||
|
"init": {
|
||||||
|
"title": "Выбор провайдера",
|
||||||
|
"description": "Выберите провайдера ИИ для этого экземпляра. Интеграция перезагрузится после сохранения изменений.",
|
||||||
|
"data": {
|
||||||
|
"api_provider": "Провайдер API"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Настройки подключения и модели",
|
||||||
|
"description": "Настройте учётные данные API и параметры модели. Изменения вступят в силу после перезагрузки интеграции.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API-ключ",
|
||||||
|
"api_endpoint": "URL конечной точки API",
|
||||||
|
"model": "Модель ИИ",
|
||||||
|
"temperature": "Креативность ответа (0-2)",
|
||||||
|
"max_tokens": "Максимальная длина ответа (1-100000)",
|
||||||
|
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||||
|
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||||
|
"context_messages": "Количество предыдущих сообщений для включения в контекст (1-20)",
|
||||||
|
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"selector": {
|
||||||
|
"api_provider": {
|
||||||
|
"options": {
|
||||||
|
"openai": "OpenAI (совместимый)",
|
||||||
|
"anthropic": "Anthropic (совместимый)",
|
||||||
|
"deepseek": "DeepSeek",
|
||||||
|
"gemini": "Google Gemini"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"services": {
|
||||||
|
"ask_question": {
|
||||||
|
"name": "Задать вопрос (HA Text AI)",
|
||||||
|
"description": "Отправить вопрос модели ИИ и получить подробный ответ. Сервис теперь возвращает данные ответа напрямую, устраняя необходимость в отдельных текстовых сенсорах и ограничение в 255 символов. Ответ также будет сохранен в истории разговора.",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Экземпляр",
|
||||||
|
"description": "Название экземпляра текстового ИИ для использования"
|
||||||
|
},
|
||||||
|
"question": {
|
||||||
|
"name": "Вопрос",
|
||||||
|
"description": "Ваш вопрос или запрос к ИИ-помощнику"
|
||||||
|
},
|
||||||
|
"context_messages": {
|
||||||
|
"name": "Контекстные сообщения",
|
||||||
|
"description": "Количество предыдущих сообщений для включения в контекст (1-20)"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "Системный промпт",
|
||||||
|
"description": "Необязательный системный промпт для установки контекста для этого конкретного вопроса"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "Модель",
|
||||||
|
"description": "Выберите модель ИИ для использования (необязательно, переопределяет настройки по умолчанию)"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "Температура",
|
||||||
|
"description": "Управление креативностью ответа (0.0-2.0)"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "Максимум токенов",
|
||||||
|
"description": "Максимальная длина ответа (1-100000 токенов)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Структурированный вывод",
|
||||||
|
"description": "Включить режим структурированного JSON-вывода. При включении ИИ будет отвечать валидным JSON, соответствующим указанной схеме."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON Schema",
|
||||||
|
"description": "JSON-схема, определяющая структуру ожидаемого ответа. Обязательна при включении structured_output."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"clear_history": {
|
||||||
|
"name": "Очистить историю",
|
||||||
|
"description": "Удалить все сохраненные вопросы и ответы из истории разговора",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Экземпляр",
|
||||||
|
"description": "Название экземпляра текстового ИИ для очистки истории"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"get_history": {
|
||||||
|
"name": "Получить историю",
|
||||||
|
"description": "Получить историю разговора с дополнительной фильтрацией и сортировкой",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Экземпляр",
|
||||||
|
"description": "Название экземпляра текстового ИИ для получения истории"
|
||||||
|
},
|
||||||
|
"limit": {
|
||||||
|
"name": "Лимит",
|
||||||
|
"description": "Количество разговоров для возврата (1-100)"
|
||||||
|
},
|
||||||
|
"filter_model": {
|
||||||
|
"name": "Фильтр модели",
|
||||||
|
"description": "Фильтрация разговоров по конкретной модели ИИ"
|
||||||
|
},
|
||||||
|
"start_date": {
|
||||||
|
"name": "Начальная дата",
|
||||||
|
"description": "Фильтрация разговоров, начиная с указанной даты/времени"
|
||||||
|
},
|
||||||
|
"include_metadata": {
|
||||||
|
"name": "Включить метаданные",
|
||||||
|
"description": "Включить дополнительную информацию, например, использованные токены, время ответа и т.д."
|
||||||
|
},
|
||||||
|
"sort_order": {
|
||||||
|
"name": "Порядок сортировки",
|
||||||
|
"description": "Порядок сортировки результатов (сначала новые или старые)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"set_system_prompt": {
|
||||||
|
"name": "Установить системный промпт",
|
||||||
|
"description": "Установить инструкции по умолчанию для поведения ИИ во всех будущих разговорах",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Экземпляр",
|
||||||
|
"description": "Название экземпляра текстового ИИ для установки системного промпта"
|
||||||
|
},
|
||||||
|
"prompt": {
|
||||||
|
"name": "Системный промпт",
|
||||||
|
"description": "Инструкции, определяющие, как ИИ должен вести себя и отвечать"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"entity": {
|
||||||
|
"sensor": {
|
||||||
|
"ha_text_ai": {
|
||||||
|
"name": "{name}",
|
||||||
|
"state": {
|
||||||
|
"ready": "Готов",
|
||||||
|
"processing": "Обработка",
|
||||||
|
"error": "Ошибка",
|
||||||
|
"disconnected": "Отключен",
|
||||||
|
"rate_limited": "Лимит запросов",
|
||||||
|
"maintenance": "Техническое обслуживание",
|
||||||
|
"initializing": "Инициализация",
|
||||||
|
"retrying": "Повторная попытка",
|
||||||
|
"queued": "В очереди"
|
||||||
|
},
|
||||||
|
"state_attributes": {
|
||||||
|
"question": {
|
||||||
|
"name": "Последний вопрос"
|
||||||
|
},
|
||||||
|
"response": {
|
||||||
|
"name": "Последний ответ"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "Текущая модель"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "Температура"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "Максимум токенов"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "Системный промпт"
|
||||||
|
},
|
||||||
|
"response_time": {
|
||||||
|
"name": "Время последнего ответа"
|
||||||
|
},
|
||||||
|
"total_responses": {
|
||||||
|
"name": "Всего ответов"
|
||||||
|
},
|
||||||
|
"error_count": {
|
||||||
|
"name": "Количество ошибок"
|
||||||
|
},
|
||||||
|
"last_error": {
|
||||||
|
"name": "Последняя ошибка"
|
||||||
|
},
|
||||||
|
"api_status": {
|
||||||
|
"name": "Статус API"
|
||||||
|
},
|
||||||
|
"tokens_used": {
|
||||||
|
"name": "Всего использовано токенов"
|
||||||
|
},
|
||||||
|
"average_response_time": {
|
||||||
|
"name": "Среднее время ответа"
|
||||||
|
},
|
||||||
|
"last_request_time": {
|
||||||
|
"name": "Время последнего запроса"
|
||||||
|
},
|
||||||
|
"is_processing": {
|
||||||
|
"name": "Статус обработки"
|
||||||
|
},
|
||||||
|
"is_rate_limited": {
|
||||||
|
"name": "Статус лимита запросов"
|
||||||
|
},
|
||||||
|
"is_maintenance": {
|
||||||
|
"name": "Статус обслуживания"
|
||||||
|
},
|
||||||
|
"api_version": {
|
||||||
|
"name": "Версия API"
|
||||||
|
},
|
||||||
|
"endpoint_status": {
|
||||||
|
"name": "Статус конечной точки"
|
||||||
|
},
|
||||||
|
"performance_metrics": {
|
||||||
|
"name": "Показатели производительности"
|
||||||
|
},
|
||||||
|
"history_size": {
|
||||||
|
"name": "Размер истории"
|
||||||
|
},
|
||||||
|
"uptime": {
|
||||||
|
"name": "Время работы"
|
||||||
|
},
|
||||||
|
"total_tokens": {
|
||||||
|
"name": "Всего токенов"
|
||||||
|
},
|
||||||
|
"prompt_tokens": {
|
||||||
|
"name": "Токены промпта"
|
||||||
|
},
|
||||||
|
"completion_tokens": {
|
||||||
|
"name": "Токены завершения"
|
||||||
|
},
|
||||||
|
"successful_requests": {
|
||||||
|
"name": "Успешные запросы"
|
||||||
|
},
|
||||||
|
"failed_requests": {
|
||||||
|
"name": "Неудачные запросы"
|
||||||
|
},
|
||||||
|
"average_latency": {
|
||||||
|
"name": "Средняя задержка"
|
||||||
|
},
|
||||||
|
"max_latency": {
|
||||||
|
"name": "Максимальная задержка"
|
||||||
|
},
|
||||||
|
"min_latency": {
|
||||||
|
"name": "Минимальная задержка"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"step": {
|
||||||
|
"provider": {
|
||||||
|
"title": "Подешавања провајдера",
|
||||||
|
"description": "Обезбедите детаље о вези за изабраног AI провајдера.",
|
||||||
|
"data": {
|
||||||
|
"name": "Име инстанце (нпр. 'GPT Асистент', 'Claude Помоћник')",
|
||||||
|
"api_key": "API кључ за аутентификацију",
|
||||||
|
"model": "AI модел који ће се користити",
|
||||||
|
"api_endpoint": "Прилагођени URL API крајње тачке (опционо)",
|
||||||
|
"temperature": "Креативност одговора (0-2, нижа = фокусираније)",
|
||||||
|
"max_tokens": "Максимална дужина одговора (1-100000 токена)",
|
||||||
|
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
||||||
|
"api_timeout": "Временско ограничење API захтева у секундама (5-600)",
|
||||||
|
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
||||||
|
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"title": "Конфигуришите HA Text AI инстанцу",
|
||||||
|
"description": "Подесите нову AI асистент инстанцу са изабраним провајдером.",
|
||||||
|
"data": {
|
||||||
|
"name": "Име инстанце (нпр. 'GPT Асистент', 'Claude Помоћник')",
|
||||||
|
"api_key": "API кључ за аутентификацију",
|
||||||
|
"model": "AI модел који ће се користити",
|
||||||
|
"temperature": "Креативност одговора (0-2, нижа = фокусираније)",
|
||||||
|
"max_tokens": "Максимална дужина одговора (1-100000 токена)",
|
||||||
|
"api_endpoint": "Прилагођени URL API крајње тачке (опционо)",
|
||||||
|
"api_provider": "API провајдер",
|
||||||
|
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
||||||
|
"api_timeout": "Временско ограничење API захтева у секундама (5-600)",
|
||||||
|
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
||||||
|
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"history_storage_error": "Неуспела инициализација складишта историје. Проверите дозволе.",
|
||||||
|
"history_rotation_error": "Грешка током ротације историјских датотека.",
|
||||||
|
"history_file_access_error": "Немогуће приступити директоријуму складишта историје.",
|
||||||
|
"name_exists": "Инстанца са овим именом већ постоји",
|
||||||
|
"invalid_name": "Неважеће име инстанце",
|
||||||
|
"invalid_auth": "Аутентификација није успела - проверите ваш API кључ",
|
||||||
|
"invalid_api_key": "Неважећи API кључ - молимо проверите ваше акредитиве",
|
||||||
|
"cannot_connect": "Неуспело повезивање са API сервисом",
|
||||||
|
"invalid_model": "Изабрани модел није доступан",
|
||||||
|
"rate_limit": "Пређена граница захтева",
|
||||||
|
"context_length": "Дужина контекста пређена",
|
||||||
|
"rate_limit_exceeded": "Пређена граница API захтева",
|
||||||
|
"maintenance": "Сервис је у одржавању",
|
||||||
|
"invalid_response": "Примљен неважећи API одговор",
|
||||||
|
"api_error": "Дошло је до грешке у API сервису",
|
||||||
|
"timeout": "Време захтева је истекло",
|
||||||
|
"invalid_instance": "Неважећа инстанца је назначена",
|
||||||
|
"unknown": "Дошло је до неочекиване грешке",
|
||||||
|
"empty": "Име не може бити празно",
|
||||||
|
"invalid_characters": "Име може садржавати само слова, цифре, размаке, подцрта и цртице",
|
||||||
|
"name_too_long": "Име мора бити 50 знакова или мање"
|
||||||
|
},
|
||||||
|
"abort": {
|
||||||
|
"already_configured": "Инстанца је већ конфигурисана"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"step": {
|
||||||
|
"init": {
|
||||||
|
"title": "Изаберите провајдера",
|
||||||
|
"description": "Изаберите AI провајдера за ову инстанцу. Интеграција ће се поново учитати након чувања измена.",
|
||||||
|
"data": {
|
||||||
|
"api_provider": "API провајдер"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Подешавања везе и модела",
|
||||||
|
"description": "Конфигуришите API акредитиве и параметре модела. Промене ће ступити на снагу након поновног учитавања интеграције.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API кључ",
|
||||||
|
"api_endpoint": "URL API крајње тачке",
|
||||||
|
"model": "AI модел",
|
||||||
|
"temperature": "Креативност одговора (0-2)",
|
||||||
|
"max_tokens": "Максимална дужина одговора (1-100000)",
|
||||||
|
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
||||||
|
"api_timeout": "Временско ограничење API захтева у секундама (5-600)",
|
||||||
|
"context_messages": "Број претходних порука које треба укључити у контекст (1-20)",
|
||||||
|
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"selector": {
|
||||||
|
"api_provider": {
|
||||||
|
"options": {
|
||||||
|
"openai": "OpenAI (компатибилан)",
|
||||||
|
"anthropic": "Anthropic (компатибилан)",
|
||||||
|
"deepseek": "DeepSeek",
|
||||||
|
"gemini": "Google Gemini"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"services": {
|
||||||
|
"ask_question": {
|
||||||
|
"name": "Поставите питање (HA Text AI)",
|
||||||
|
"description": "Пошаљите питање AI моделу и добијте детаљан одговор. Овај сервис сада враћа податке одговора директно, елиминишући потребу за засебним текстуалним сензорима и ограничење од 255 карактера. Одговор ће такође бити сачуван у историји разговора.",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Инстанца",
|
||||||
|
"description": "Име HA Text AI инстанце коју ћете користити"
|
||||||
|
},
|
||||||
|
"question": {
|
||||||
|
"name": "Питање",
|
||||||
|
"description": "Ваше питање или упит за AI асистента"
|
||||||
|
},
|
||||||
|
"context_messages": {
|
||||||
|
"name": "Контекстуалне поруке",
|
||||||
|
"description": "Број претходних порука које треба укључити у контекст (1-20)"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "Системски упит",
|
||||||
|
"description": "Опционални системски упит за постављање контекста за ово конкретно питање"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "Модел",
|
||||||
|
"description": "Изаберите AI модел који ћете користити (опционо, надмашује подразумевану поставку)"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "Температура",
|
||||||
|
"description": "Контролише креативност одговора (0.0-2.0)"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "Максимални токени",
|
||||||
|
"description": "Максимална дужина одговора (1-100000 токена)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Структурисани излаз",
|
||||||
|
"description": "Омогући JSON структурисани излаз. Када је омогућено, AI ће одговарати валидним JSON-ом који одговара датој шеми."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON шема",
|
||||||
|
"description": "JSON шема која дефинише структуру очекиваног одговора. Обавезна када је structured_output омогућен."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"clear_history": {
|
||||||
|
"name": "Обриши историју",
|
||||||
|
"description": "Избришите све сачуване питања и одговоре из историје разговора",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Инстанца",
|
||||||
|
"description": "Име HA Text AI инстанце за коју желите да обришете историју"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"get_history": {
|
||||||
|
"name": "Добијте историју",
|
||||||
|
"description": "Повратите историју разговора уз опционално филтрирање и сортирање",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Инстанца",
|
||||||
|
"description": "Име HA Text AI инстанце из које желите да добијете историју"
|
||||||
|
},
|
||||||
|
"limit": {
|
||||||
|
"name": "Лимит",
|
||||||
|
"description": "Број разговора које треба вратити (1-100)"
|
||||||
|
},
|
||||||
|
"filter_model": {
|
||||||
|
"name": "Филтер модел",
|
||||||
|
"description": "Филтрирајте разговоре по одређеном AI моделу"
|
||||||
|
},
|
||||||
|
"start_date": {
|
||||||
|
"name": "Датум почетка",
|
||||||
|
"description": "Филтрирајте разговоре који почињу од овог датума/времена"
|
||||||
|
},
|
||||||
|
"include_metadata": {
|
||||||
|
"name": "Укључи метаподатке",
|
||||||
|
"description": "Укључите додатне информације као што су коришћени токени, време одговора итд."
|
||||||
|
},
|
||||||
|
"sort_order": {
|
||||||
|
"name": "Редослед сортирања",
|
||||||
|
"description": "Редослед сортирања за резултате (најновији или најстарији први)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"set_system_prompt": {
|
||||||
|
"name": "Поставите системски упит",
|
||||||
|
"description": "Поставите подразумеване инструкције за системско понашање за све будуће разговоре",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Инстанца",
|
||||||
|
"description": "Име HA Text AI инстанце за коју желите да поставите системски упит"
|
||||||
|
},
|
||||||
|
"prompt": {
|
||||||
|
"name": "Системски упит",
|
||||||
|
"description": "Инструкције које дефинишу како AI треба да се понаша и одговара"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"entity": {
|
||||||
|
"sensor": {
|
||||||
|
"ha_text_ai": {
|
||||||
|
"name": "{name}",
|
||||||
|
"state": {
|
||||||
|
"ready": "Спремно",
|
||||||
|
"processing": "Обрада",
|
||||||
|
"error": "Грешка",
|
||||||
|
"disconnected": "Прекључено",
|
||||||
|
"rate_limited": "Ограничење захтева",
|
||||||
|
"maintenance": "Одржавање",
|
||||||
|
"initializing": "Инициализује се",
|
||||||
|
"retrying": "Покушава поново",
|
||||||
|
"queued": "У реду"
|
||||||
|
},
|
||||||
|
"state_attributes": {
|
||||||
|
"question": {
|
||||||
|
"name": "Последње питање"
|
||||||
|
},
|
||||||
|
"response": {
|
||||||
|
"name": "Последњи одговор"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "Тренутни модел"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "Температура"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "Максимални токени"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "Системски упит"
|
||||||
|
},
|
||||||
|
"response_time": {
|
||||||
|
"name": "Време последњег одговора"
|
||||||
|
},
|
||||||
|
"total_responses": {
|
||||||
|
"name": "Укупно одговора"
|
||||||
|
},
|
||||||
|
"error_count": {
|
||||||
|
"name": "Број грешака"
|
||||||
|
},
|
||||||
|
"last_error": {
|
||||||
|
"name": "Последња грешка"
|
||||||
|
},
|
||||||
|
"api_status": {
|
||||||
|
"name": "Статус API"
|
||||||
|
},
|
||||||
|
"tokens_used": {
|
||||||
|
"name": "Укупно коришћени токени"
|
||||||
|
},
|
||||||
|
"average_response_time": {
|
||||||
|
"name": "Просечно време одговора"
|
||||||
|
},
|
||||||
|
"last_request_time": {
|
||||||
|
"name": "Време последњег захтева"
|
||||||
|
},
|
||||||
|
"is_processing": {
|
||||||
|
"name": "Статус обраде"
|
||||||
|
},
|
||||||
|
"is_rate_limited": {
|
||||||
|
"name": "Статус ограничења захтева"
|
||||||
|
},
|
||||||
|
"is_maintenance": {
|
||||||
|
"name": "Статус одржавања"
|
||||||
|
},
|
||||||
|
"api_version": {
|
||||||
|
"name": "Верзија API"
|
||||||
|
},
|
||||||
|
"endpoint_status": {
|
||||||
|
"name": "Статус крајње тачке"
|
||||||
|
},
|
||||||
|
"performance_metrics": {
|
||||||
|
"name": "Перформансне метрике"
|
||||||
|
},
|
||||||
|
"history_size": {
|
||||||
|
"name": "Величина историје"
|
||||||
|
},
|
||||||
|
"uptime": {
|
||||||
|
"name": "Уптиме"
|
||||||
|
},
|
||||||
|
"total_tokens": {
|
||||||
|
"name": "Укупно токена"
|
||||||
|
},
|
||||||
|
"prompt_tokens": {
|
||||||
|
"name": "Токени упита"
|
||||||
|
},
|
||||||
|
"completion_tokens": {
|
||||||
|
"name": "Токени завршетка"
|
||||||
|
},
|
||||||
|
"successful_requests": {
|
||||||
|
"name": "Успешни захтеви"
|
||||||
|
},
|
||||||
|
"failed_requests": {
|
||||||
|
"name": "Неуспешни захтеви"
|
||||||
|
},
|
||||||
|
"average_latency": {
|
||||||
|
"name": "Просечна латенција"
|
||||||
|
},
|
||||||
|
"max_latency": {
|
||||||
|
"name": "Максимална латенција"
|
||||||
|
},
|
||||||
|
"min_latency": {
|
||||||
|
"name": "Минимална латенција"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,309 @@
|
|||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"step": {
|
||||||
|
"provider": {
|
||||||
|
"title": "提供者设置",
|
||||||
|
"description": "提供所选AI提供者的连接详细信息。",
|
||||||
|
"data": {
|
||||||
|
"name": "实例名称(例如,'GPT助手','Claude助手')",
|
||||||
|
"api_key": "用于身份验证的API密钥",
|
||||||
|
"model": "要使用的AI模型",
|
||||||
|
"api_endpoint": "自定义API端点URL(可选)",
|
||||||
|
"temperature": "响应创造力(0-2,越低越专注)",
|
||||||
|
"max_tokens": "最大响应长度(1-100000个标记)",
|
||||||
|
"request_interval": "请求之间的最小时间(0.1-60秒)",
|
||||||
|
"api_timeout": "API请求超时时间(5-600秒)",
|
||||||
|
"context_messages": "保留的上下文消息数量(1-20)",
|
||||||
|
"max_history_size": "最大对话历史大小(1-100)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"title": "配置HA文本AI实例",
|
||||||
|
"description": "使用所选提供者设置新的AI助手实例。",
|
||||||
|
"data": {
|
||||||
|
"name": "实例名称(例如,'GPT助手','Claude助手')",
|
||||||
|
"api_key": "用于身份验证的API密钥",
|
||||||
|
"model": "要使用的AI模型",
|
||||||
|
"temperature": "响应创造力(0-2,越低越专注)",
|
||||||
|
"max_tokens": "最大响应长度(1-100000个标记)",
|
||||||
|
"api_endpoint": "自定义API端点URL(可选)",
|
||||||
|
"api_provider": "API提供者",
|
||||||
|
"request_interval": "请求之间的最小时间(0.1-60秒)",
|
||||||
|
"api_timeout": "API请求超时时间(5-600秒)",
|
||||||
|
"context_messages": "保留的上下文消息数量(1-20)",
|
||||||
|
"max_history_size": "最大对话历史大小(1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"history_storage_error": "无法初始化历史存储。检查权限。",
|
||||||
|
"history_rotation_error": "历史文件轮换时出错。",
|
||||||
|
"history_file_access_error": "无法访问历史存储目录。",
|
||||||
|
"name_exists": "具有此名称的实例已存在",
|
||||||
|
"invalid_name": "无效的实例名称",
|
||||||
|
"invalid_auth": "身份验证失败 - 检查您的API密钥",
|
||||||
|
"invalid_api_key": "无效的API密钥 - 请验证您的凭据",
|
||||||
|
"cannot_connect": "无法连接到API服务",
|
||||||
|
"invalid_model": "所选模型不可用",
|
||||||
|
"rate_limit": "超出速率限制",
|
||||||
|
"context_length": "上下文长度超出限制",
|
||||||
|
"rate_limit_exceeded": "API速率限制超出",
|
||||||
|
"maintenance": "服务正在维护中",
|
||||||
|
"invalid_response": "收到无效的API响应",
|
||||||
|
"api_error": "发生API服务错误",
|
||||||
|
"timeout": "请求超时",
|
||||||
|
"invalid_instance": "指定的实例无效",
|
||||||
|
"unknown": "发生意外错误",
|
||||||
|
"empty": "名称不能为空",
|
||||||
|
"invalid_characters": "名称只能包含字母、数字、空格、下划线和连字符",
|
||||||
|
"name_too_long": "名称必须少于50个字符"
|
||||||
|
},
|
||||||
|
"abort": {
|
||||||
|
"already_configured": "实例已配置"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"options": {
|
||||||
|
"step": {
|
||||||
|
"init": {
|
||||||
|
"title": "选择提供者",
|
||||||
|
"description": "选择此实例的AI提供者。保存更改后集成将重新加载。",
|
||||||
|
"data": {
|
||||||
|
"api_provider": "API提供者"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "连接和模型设置",
|
||||||
|
"description": "配置API凭据和模型参数。更改将在集成重新加载后生效。",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API密钥",
|
||||||
|
"api_endpoint": "API端点URL",
|
||||||
|
"model": "AI模型",
|
||||||
|
"temperature": "响应创造力(0-2)",
|
||||||
|
"max_tokens": "最大响应长度(1-100000)",
|
||||||
|
"request_interval": "最小请求间隔(0.1-60秒)",
|
||||||
|
"api_timeout": "API请求超时时间(5-600秒)",
|
||||||
|
"context_messages": "要包含在上下文中的先前消息数量(1-20)",
|
||||||
|
"max_history_size": "最大对话历史大小(1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"selector": {
|
||||||
|
"api_provider": {
|
||||||
|
"options": {
|
||||||
|
"openai": "OpenAI(兼容)",
|
||||||
|
"anthropic": "Anthropic(兼容)",
|
||||||
|
"deepseek": "DeepSeek",
|
||||||
|
"gemini": "Google Gemini"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"services": {
|
||||||
|
"ask_question": {
|
||||||
|
"name": "提问 (HA Text AI)",
|
||||||
|
"description": "向AI模型发送问题并获得详细回答。此服务现在直接返回响应数据,消除了对单独文本传感器的需要和255字符限制。响应也将存储在对话历史中。",
|
||||||
|
"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-100000个标记)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "结构化输出",
|
||||||
|
"description": "启用JSON结构化输出模式。启用后,AI将以符合提供的模式的有效JSON进行响应。"
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON模式",
|
||||||
|
"description": "定义预期响应结构的JSON模式。启用structured_output时必需。"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"clear_history": {
|
||||||
|
"name": "清除历史",
|
||||||
|
"description": "删除对话历史中存储的所有问题和响应",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "实例",
|
||||||
|
"description": "要清除历史的HA文本AI实例名称"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"get_history": {
|
||||||
|
"name": "获取历史",
|
||||||
|
"description": "检索对话历史,可选的过滤和排序",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "实例",
|
||||||
|
"description": "要获取历史的HA文本AI实例名称"
|
||||||
|
},
|
||||||
|
"limit": {
|
||||||
|
"name": "限制",
|
||||||
|
"description": "要返回的对话数量(1-100)"
|
||||||
|
},
|
||||||
|
"filter_model": {
|
||||||
|
"name": "过滤模型",
|
||||||
|
"description": "按特定AI模型过滤对话"
|
||||||
|
},
|
||||||
|
"start_date": {
|
||||||
|
"name": "开始日期",
|
||||||
|
"description": "过滤从此日期/时间开始的对话"
|
||||||
|
},
|
||||||
|
"include_metadata": {
|
||||||
|
"name": "包含元数据",
|
||||||
|
"description": "包括额外信息,如使用的标记、响应时间等。"
|
||||||
|
},
|
||||||
|
"sort_order": {
|
||||||
|
"name": "排序顺序",
|
||||||
|
"description": "结果的排序顺序(最新或最旧优先)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"set_system_prompt": {
|
||||||
|
"name": "设置系统提示",
|
||||||
|
"description": "为所有未来的对话设置默认的系统行为指令",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "实例",
|
||||||
|
"description": "要设置系统提示的HA文本AI实例名称"
|
||||||
|
},
|
||||||
|
"prompt": {
|
||||||
|
"name": "系统提示",
|
||||||
|
"description": "定义AI应如何行为和响应的指令"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"entity": {
|
||||||
|
"sensor": {
|
||||||
|
"ha_text_ai": {
|
||||||
|
"name": "{name}",
|
||||||
|
"state": {
|
||||||
|
"ready": "准备就绪",
|
||||||
|
"processing": "处理中",
|
||||||
|
"error": "错误",
|
||||||
|
"disconnected": "已断开连接",
|
||||||
|
"rate_limited": "速率限制",
|
||||||
|
"maintenance": "维护中",
|
||||||
|
"initializing": "初始化中",
|
||||||
|
"retrying": "重试中",
|
||||||
|
"queued": "排队中"
|
||||||
|
},
|
||||||
|
"state_attributes": {
|
||||||
|
"question": {
|
||||||
|
"name": "最后问题"
|
||||||
|
},
|
||||||
|
"response": {
|
||||||
|
"name": "最后响应"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "当前模型"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "温度"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "最大标记数"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "系统提示"
|
||||||
|
},
|
||||||
|
"response_time": {
|
||||||
|
"name": "最后响应时间"
|
||||||
|
},
|
||||||
|
"total_responses": {
|
||||||
|
"name": "总响应数"
|
||||||
|
},
|
||||||
|
"error_count": {
|
||||||
|
"name": "错误计数"
|
||||||
|
},
|
||||||
|
"last_error": {
|
||||||
|
"name": "最后错误"
|
||||||
|
},
|
||||||
|
"api_status": {
|
||||||
|
"name": "API状态"
|
||||||
|
},
|
||||||
|
"tokens_used": {
|
||||||
|
"name": "总使用标记数"
|
||||||
|
},
|
||||||
|
"average_response_time": {
|
||||||
|
"name": "平均响应时间"
|
||||||
|
},
|
||||||
|
"last_request_time": {
|
||||||
|
"name": "最后请求时间"
|
||||||
|
},
|
||||||
|
"is_processing": {
|
||||||
|
"name": "处理状态"
|
||||||
|
},
|
||||||
|
"is_rate_limited": {
|
||||||
|
"name": "速率限制状态"
|
||||||
|
},
|
||||||
|
"is_maintenance": {
|
||||||
|
"name": "维护状态"
|
||||||
|
},
|
||||||
|
"api_version": {
|
||||||
|
"name": "API版本"
|
||||||
|
},
|
||||||
|
"endpoint_status": {
|
||||||
|
"name": "端点状态"
|
||||||
|
},
|
||||||
|
"performance_metrics": {
|
||||||
|
"name": "性能指标"
|
||||||
|
},
|
||||||
|
"history_size": {
|
||||||
|
"name": "历史大小"
|
||||||
|
},
|
||||||
|
"uptime": {
|
||||||
|
"name": "正常运行时间"
|
||||||
|
},
|
||||||
|
"total_tokens": {
|
||||||
|
"name": "总标记数"
|
||||||
|
},
|
||||||
|
"prompt_tokens": {
|
||||||
|
"name": "提示标记数"
|
||||||
|
},
|
||||||
|
"completion_tokens": {
|
||||||
|
"name": "完成标记数"
|
||||||
|
},
|
||||||
|
"successful_requests": {
|
||||||
|
"name": "成功请求数"
|
||||||
|
},
|
||||||
|
"failed_requests": {
|
||||||
|
"name": "失败请求数"
|
||||||
|
},
|
||||||
|
"average_latency": {
|
||||||
|
"name": "平均延迟"
|
||||||
|
},
|
||||||
|
"max_latency": {
|
||||||
|
"name": "最大延迟"
|
||||||
|
},
|
||||||
|
"min_latency": {
|
||||||
|
"name": "最小延迟"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,9 +1,5 @@
|
|||||||
{
|
{
|
||||||
"name": "HA text AI",
|
"name": "HA Text AI",
|
||||||
"render_readme": true,
|
"render_readme": true,
|
||||||
"domains": ["sensor"],
|
"homeassistant": "2024.12.0"
|
||||||
"homeassistant": "2024.11.0",
|
|
||||||
"icon": "mdi:brain",
|
|
||||||
"version": "1.0.2",
|
|
||||||
"documentation": "https://github.com/smkrv/ha-text-ai"
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
pytest
|
|
||||||
pytest-asyncio
|
|
||||||
homeassistant
|
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
```
|
||||||
|
ha_text_ai/
|
||||||
|
├── __init__.py
|
||||||
|
├── api_client.py
|
||||||
|
├── config_flow.py
|
||||||
|
├── const.py
|
||||||
|
├── coordinator.py
|
||||||
|
├── icons
|
||||||
|
│ ├── dark_icon.png
|
||||||
|
│ ├── dark_icon@2x.png
|
||||||
|
│ ├── dark_logo.png
|
||||||
|
│ ├── dark_logo@2x.png
|
||||||
|
│ ├── icon.png
|
||||||
|
│ ├── icon@2x.png
|
||||||
|
│ ├── logo.png
|
||||||
|
│ └── logo@2x.png
|
||||||
|
├── manifest.json
|
||||||
|
├── sensor.py
|
||||||
|
├── services.yaml
|
||||||
|
└── translations
|
||||||
|
├── de.json
|
||||||
|
├── en.json
|
||||||
|
├── es.json
|
||||||
|
├── hi.json
|
||||||
|
├── it.json
|
||||||
|
├── ru.json
|
||||||
|
├── sr.json
|
||||||
|
└── zh.json
|
||||||
|
|
||||||
|
```
|
||||||