Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
03cd40de29 | ||
|
|
33d4a190b9 | ||
|
|
990134bde5 | ||
|
|
3cd8d3076a | ||
|
|
65dbb5dfc0 | ||
|
|
fc59f584a3 | ||
|
|
bcfe69b5f7 | ||
|
|
9d4d2d5cd1 | ||
|
|
6e635f7e2f | ||
|
|
e8b9b911ef | ||
|
|
5af733b1b0 | ||
|
|
1e2ff81d07 | ||
|
|
47c731c9ee | ||
|
|
4e3b4cfdb7 | ||
|
|
c45828953d | ||
|
|
ad36352fe8 | ||
|
|
618ad34ccc | ||
|
|
0a06fbeca6 | ||
|
|
772a614a20 | ||
|
|
c8be545655 | ||
|
|
a8a91972ba | ||
|
|
9cdeb9f417 | ||
|
|
31560a8835 | ||
|
|
c54bfcff3b | ||
|
|
63c5c7c51e | ||
|
|
998103ce73 | ||
|
|
ce0a75f219 | ||
|
|
e7c8b22fde | ||
|
|
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 |
@@ -0,0 +1,15 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
commit-message:
|
||||
prefix: "chore"
|
||||
labels:
|
||||
- "dependencies"
|
||||
- "github-actions"
|
||||
groups:
|
||||
actions:
|
||||
patterns:
|
||||
- "*"
|
||||
@@ -1,5 +1,6 @@
|
||||
name: Validate with hassfest
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
@@ -25,19 +26,15 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- name: ⤵️ Check out code from GitHub
|
||||
uses: actions/checkout@v4
|
||||
- name: Check out code from GitHub
|
||||
uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: 🚀 Run hassfest validation
|
||||
- name: Run hassfest validation
|
||||
uses: home-assistant/actions/hassfest@master
|
||||
|
||||
- name: ℹ️ Print hassfest version
|
||||
if: always()
|
||||
run: |
|
||||
echo "Hassfest version: $(hassfest --version)"
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
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@v7
|
||||
with:
|
||||
ref: ${{ github.event.release.tag_name }}
|
||||
persist-credentials: false
|
||||
|
||||
- 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@v3
|
||||
with:
|
||||
tag_name: ${{ github.event.release.tag_name }}
|
||||
files: ha_text_ai.zip
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -1,4 +1,6 @@
|
||||
name: Validate
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
on:
|
||||
push:
|
||||
|
||||
@@ -1,40 +1,40 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
dist/
|
||||
build/
|
||||
*.egg
|
||||
|
||||
# Home Assistant
|
||||
.storage
|
||||
.cloud
|
||||
.google.token
|
||||
# Virtual environments
|
||||
.venv/
|
||||
venv/
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
*.psd
|
||||
|
||||
# Archives
|
||||
*.zip
|
||||
*.txt
|
||||
|
||||
# Home Assistant
|
||||
.storage/
|
||||
|
||||
# Claude Code working files
|
||||
handoff.*.md
|
||||
CLAUDE.md
|
||||
AGENTS.md
|
||||
GEMINI.md
|
||||
.claude/
|
||||
.cursor/
|
||||
.cursorrules
|
||||
.windsurfrules
|
||||
docs/specs/
|
||||
docs/superpowers/
|
||||
docs/plans/
|
||||
|
||||
@@ -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.
|
||||
@@ -1,437 +1,21 @@
|
||||
Attribution-NonCommercial-ShareAlike 4.0 International
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
||||
does not provide legal services or legal advice. Distribution of
|
||||
Creative Commons public licenses does not create a lawyer-client or
|
||||
other relationship. Creative Commons makes its licenses and related
|
||||
information available on an "as-is" basis. Creative Commons gives no
|
||||
warranties regarding its licenses, any material licensed under their
|
||||
terms and conditions, or any related information. Creative Commons
|
||||
disclaims all liability for damages resulting from their use to the
|
||||
fullest extent possible.
|
||||
|
||||
Using Creative Commons Public Licenses
|
||||
|
||||
Creative Commons public licenses provide a standard set of terms and
|
||||
conditions that creators and other rights holders may use to share
|
||||
original works of authorship and other material subject to copyright
|
||||
and certain other rights specified in the public license below. The
|
||||
following considerations are for informational purposes only, are not
|
||||
exhaustive, and do not form part of our licenses.
|
||||
|
||||
Considerations for licensors: Our public licenses are
|
||||
intended for use by those authorized to give the public
|
||||
permission to use material in ways otherwise restricted by
|
||||
copyright and certain other rights. Our licenses are
|
||||
irrevocable. Licensors should read and understand the terms
|
||||
and conditions of the license they choose before applying it.
|
||||
Licensors should also secure all rights necessary before
|
||||
applying our licenses so that the public can reuse the
|
||||
material as expected. Licensors should clearly mark any
|
||||
material not subject to the license. This includes other CC-
|
||||
licensed material, or material used under an exception or
|
||||
limitation to copyright. More considerations for licensors:
|
||||
wiki.creativecommons.org/Considerations_for_licensors
|
||||
|
||||
Considerations for the public: By using one of our public
|
||||
licenses, a licensor grants the public permission to use the
|
||||
licensed material under specified terms and conditions. If
|
||||
the licensor's permission is not necessary for any reason--for
|
||||
example, because of any applicable exception or limitation to
|
||||
copyright--then that use is not regulated by the license. Our
|
||||
licenses grant only permissions under copyright and certain
|
||||
other rights that a licensor has authority to grant. Use of
|
||||
the licensed material may still be restricted for other
|
||||
reasons, including because others have copyright or other
|
||||
rights in the material. A licensor may make special requests,
|
||||
such as asking that all changes be marked or described.
|
||||
Although not required by our licenses, you are encouraged to
|
||||
respect those requests where reasonable. More considerations
|
||||
for the public:
|
||||
wiki.creativecommons.org/Considerations_for_licensees
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
|
||||
Public License
|
||||
|
||||
By exercising the Licensed Rights (defined below), You accept and agree
|
||||
to be bound by the terms and conditions of this Creative Commons
|
||||
Attribution-NonCommercial-ShareAlike 4.0 International Public License
|
||||
("Public License"). To the extent this Public License may be
|
||||
interpreted as a contract, You are granted the Licensed Rights in
|
||||
consideration of Your acceptance of these terms and conditions, and the
|
||||
Licensor grants You such rights in consideration of benefits the
|
||||
Licensor receives from making the Licensed Material available under
|
||||
these terms and conditions.
|
||||
|
||||
|
||||
Section 1 -- Definitions.
|
||||
|
||||
a. Adapted Material means material subject to Copyright and Similar
|
||||
Rights that is derived from or based upon the Licensed Material
|
||||
and in which the Licensed Material is translated, altered,
|
||||
arranged, transformed, or otherwise modified in a manner requiring
|
||||
permission under the Copyright and Similar Rights held by the
|
||||
Licensor. For purposes of this Public License, where the Licensed
|
||||
Material is a musical work, performance, or sound recording,
|
||||
Adapted Material is always produced where the Licensed Material is
|
||||
synched in timed relation with a moving image.
|
||||
|
||||
b. Adapter's License means the license You apply to Your Copyright
|
||||
and Similar Rights in Your contributions to Adapted Material in
|
||||
accordance with the terms and conditions of this Public License.
|
||||
|
||||
c. BY-NC-SA Compatible License means a license listed at
|
||||
creativecommons.org/compatiblelicenses, approved by Creative
|
||||
Commons as essentially the equivalent of this Public License.
|
||||
|
||||
d. Copyright and Similar Rights means copyright and/or similar rights
|
||||
closely related to copyright including, without limitation,
|
||||
performance, broadcast, sound recording, and Sui Generis Database
|
||||
Rights, without regard to how the rights are labeled or
|
||||
categorized. For purposes of this Public License, the rights
|
||||
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
||||
Rights.
|
||||
|
||||
e. Effective Technological Measures means those measures that, in the
|
||||
absence of proper authority, may not be circumvented under laws
|
||||
fulfilling obligations under Article 11 of the WIPO Copyright
|
||||
Treaty adopted on December 20, 1996, and/or similar international
|
||||
agreements.
|
||||
|
||||
f. Exceptions and Limitations means fair use, fair dealing, and/or
|
||||
any other exception or limitation to Copyright and Similar Rights
|
||||
that applies to Your use of the Licensed Material.
|
||||
|
||||
g. License Elements means the license attributes listed in the name
|
||||
of a Creative Commons Public License. The License Elements of this
|
||||
Public License are Attribution, NonCommercial, and ShareAlike.
|
||||
|
||||
h. Licensed Material means the artistic or literary work, database,
|
||||
or other material to which the Licensor applied this Public
|
||||
License.
|
||||
|
||||
i. Licensed Rights means the rights granted to You subject to the
|
||||
terms and conditions of this Public License, which are limited to
|
||||
all Copyright and Similar Rights that apply to Your use of the
|
||||
Licensed Material and that the Licensor has authority to license.
|
||||
|
||||
j. Licensor means the individual(s) or entity(ies) granting rights
|
||||
under this Public License.
|
||||
|
||||
k. NonCommercial means not primarily intended for or directed towards
|
||||
commercial advantage or monetary compensation. For purposes of
|
||||
this Public License, the exchange of the Licensed Material for
|
||||
other material subject to Copyright and Similar Rights by digital
|
||||
file-sharing or similar means is NonCommercial provided there is
|
||||
no payment of monetary compensation in connection with the
|
||||
exchange.
|
||||
|
||||
l. Share means to provide material to the public by any means or
|
||||
process that requires permission under the Licensed Rights, such
|
||||
as reproduction, public display, public performance, distribution,
|
||||
dissemination, communication, or importation, and to make material
|
||||
available to the public including in ways that members of the
|
||||
public may access the material from a place and at a time
|
||||
individually chosen by them.
|
||||
|
||||
m. Sui Generis Database Rights means rights other than copyright
|
||||
resulting from Directive 96/9/EC of the European Parliament and of
|
||||
the Council of 11 March 1996 on the legal protection of databases,
|
||||
as amended and/or succeeded, as well as other essentially
|
||||
equivalent rights anywhere in the world.
|
||||
|
||||
n. You means the individual or entity exercising the Licensed Rights
|
||||
under this Public License. Your has a corresponding meaning.
|
||||
|
||||
|
||||
Section 2 -- Scope.
|
||||
|
||||
a. License grant.
|
||||
|
||||
1. Subject to the terms and conditions of this Public License,
|
||||
the Licensor hereby grants You a worldwide, royalty-free,
|
||||
non-sublicensable, non-exclusive, irrevocable license to
|
||||
exercise the Licensed Rights in the Licensed Material to:
|
||||
|
||||
a. reproduce and Share the Licensed Material, in whole or
|
||||
in part, for NonCommercial purposes only; and
|
||||
|
||||
b. produce, reproduce, and Share Adapted Material for
|
||||
NonCommercial purposes only.
|
||||
|
||||
2. Exceptions and Limitations. For the avoidance of doubt, where
|
||||
Exceptions and Limitations apply to Your use, this Public
|
||||
License does not apply, and You do not need to comply with
|
||||
its terms and conditions.
|
||||
|
||||
3. Term. The term of this Public License is specified in Section
|
||||
6(a).
|
||||
|
||||
4. Media and formats; technical modifications allowed. The
|
||||
Licensor authorizes You to exercise the Licensed Rights in
|
||||
all media and formats whether now known or hereafter created,
|
||||
and to make technical modifications necessary to do so. The
|
||||
Licensor waives and/or agrees not to assert any right or
|
||||
authority to forbid You from making technical modifications
|
||||
necessary to exercise the Licensed Rights, including
|
||||
technical modifications necessary to circumvent Effective
|
||||
Technological Measures. For purposes of this Public License,
|
||||
simply making modifications authorized by this Section 2(a)
|
||||
(4) never produces Adapted Material.
|
||||
|
||||
5. Downstream recipients.
|
||||
|
||||
a. Offer from the Licensor -- Licensed Material. Every
|
||||
recipient of the Licensed Material automatically
|
||||
receives an offer from the Licensor to exercise the
|
||||
Licensed Rights under the terms and conditions of this
|
||||
Public License.
|
||||
|
||||
b. Additional offer from the Licensor -- Adapted Material.
|
||||
Every recipient of Adapted Material from You
|
||||
automatically receives an offer from the Licensor to
|
||||
exercise the Licensed Rights in the Adapted Material
|
||||
under the conditions of the Adapter's License You apply.
|
||||
|
||||
c. No downstream restrictions. You may not offer or impose
|
||||
any additional or different terms or conditions on, or
|
||||
apply any Effective Technological Measures to, the
|
||||
Licensed Material if doing so restricts exercise of the
|
||||
Licensed Rights by any recipient of the Licensed
|
||||
Material.
|
||||
|
||||
6. No endorsement. Nothing in this Public License constitutes or
|
||||
may be construed as permission to assert or imply that You
|
||||
are, or that Your use of the Licensed Material is, connected
|
||||
with, or sponsored, endorsed, or granted official status by,
|
||||
the Licensor or others designated to receive attribution as
|
||||
provided in Section 3(a)(1)(A)(i).
|
||||
|
||||
b. Other rights.
|
||||
|
||||
1. Moral rights, such as the right of integrity, are not
|
||||
licensed under this Public License, nor are publicity,
|
||||
privacy, and/or other similar personality rights; however, to
|
||||
the extent possible, the Licensor waives and/or agrees not to
|
||||
assert any such rights held by the Licensor to the limited
|
||||
extent necessary to allow You to exercise the Licensed
|
||||
Rights, but not otherwise.
|
||||
|
||||
2. Patent and trademark rights are not licensed under this
|
||||
Public License.
|
||||
|
||||
3. To the extent possible, the Licensor waives any right to
|
||||
collect royalties from You for the exercise of the Licensed
|
||||
Rights, whether directly or through a collecting society
|
||||
under any voluntary or waivable statutory or compulsory
|
||||
licensing scheme. In all other cases the Licensor expressly
|
||||
reserves any right to collect such royalties, including when
|
||||
the Licensed Material is used other than for NonCommercial
|
||||
purposes.
|
||||
|
||||
|
||||
Section 3 -- License Conditions.
|
||||
|
||||
Your exercise of the Licensed Rights is expressly made subject to the
|
||||
following conditions.
|
||||
|
||||
a. Attribution.
|
||||
|
||||
1. If You Share the Licensed Material (including in modified
|
||||
form), You must:
|
||||
|
||||
a. retain the following if it is supplied by the Licensor
|
||||
with the Licensed Material:
|
||||
|
||||
i. identification of the creator(s) of the Licensed
|
||||
Material and any others designated to receive
|
||||
attribution, in any reasonable manner requested by
|
||||
the Licensor (including by pseudonym if
|
||||
designated);
|
||||
|
||||
ii. a copyright notice;
|
||||
|
||||
iii. a notice that refers to this Public License;
|
||||
|
||||
iv. a notice that refers to the disclaimer of
|
||||
warranties;
|
||||
|
||||
v. a URI or hyperlink to the Licensed Material to the
|
||||
extent reasonably practicable;
|
||||
|
||||
b. indicate if You modified the Licensed Material and
|
||||
retain an indication of any previous modifications; and
|
||||
|
||||
c. indicate the Licensed Material is licensed under this
|
||||
Public License, and include the text of, or the URI or
|
||||
hyperlink to, this Public License.
|
||||
|
||||
2. You may satisfy the conditions in Section 3(a)(1) in any
|
||||
reasonable manner based on the medium, means, and context in
|
||||
which You Share the Licensed Material. For example, it may be
|
||||
reasonable to satisfy the conditions by providing a URI or
|
||||
hyperlink to a resource that includes the required
|
||||
information.
|
||||
3. If requested by the Licensor, You must remove any of the
|
||||
information required by Section 3(a)(1)(A) to the extent
|
||||
reasonably practicable.
|
||||
|
||||
b. ShareAlike.
|
||||
|
||||
In addition to the conditions in Section 3(a), if You Share
|
||||
Adapted Material You produce, the following conditions also apply.
|
||||
|
||||
1. The Adapter's License You apply must be a Creative Commons
|
||||
license with the same License Elements, this version or
|
||||
later, or a BY-NC-SA Compatible License.
|
||||
|
||||
2. You must include the text of, or the URI or hyperlink to, the
|
||||
Adapter's License You apply. You may satisfy this condition
|
||||
in any reasonable manner based on the medium, means, and
|
||||
context in which You Share Adapted Material.
|
||||
|
||||
3. You may not offer or impose any additional or different terms
|
||||
or conditions on, or apply any Effective Technological
|
||||
Measures to, Adapted Material that restrict exercise of the
|
||||
rights granted under the Adapter's License You apply.
|
||||
|
||||
|
||||
Section 4 -- Sui Generis Database Rights.
|
||||
|
||||
Where the Licensed Rights include Sui Generis Database Rights that
|
||||
apply to Your use of the Licensed Material:
|
||||
|
||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
||||
to extract, reuse, reproduce, and Share all or a substantial
|
||||
portion of the contents of the database for NonCommercial purposes
|
||||
only;
|
||||
|
||||
b. if You include all or a substantial portion of the database
|
||||
contents in a database in which You have Sui Generis Database
|
||||
Rights, then the database in which You have Sui Generis Database
|
||||
Rights (but not its individual contents) is Adapted Material,
|
||||
including for purposes of Section 3(b); and
|
||||
|
||||
c. You must comply with the conditions in Section 3(a) if You Share
|
||||
all or a substantial portion of the contents of the database.
|
||||
|
||||
For the avoidance of doubt, this Section 4 supplements and does not
|
||||
replace Your obligations under this Public License where the Licensed
|
||||
Rights include other Copyright and Similar Rights.
|
||||
|
||||
|
||||
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
||||
|
||||
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
||||
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
||||
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
||||
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
||||
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
||||
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
||||
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
||||
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
||||
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
||||
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
||||
|
||||
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
||||
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
||||
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
||||
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
||||
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
||||
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
||||
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
||||
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
||||
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
||||
|
||||
c. The disclaimer of warranties and limitation of liability provided
|
||||
above shall be interpreted in a manner that, to the extent
|
||||
possible, most closely approximates an absolute disclaimer and
|
||||
waiver of all liability.
|
||||
|
||||
|
||||
Section 6 -- Term and Termination.
|
||||
|
||||
a. This Public License applies for the term of the Copyright and
|
||||
Similar Rights licensed here. However, if You fail to comply with
|
||||
this Public License, then Your rights under this Public License
|
||||
terminate automatically.
|
||||
|
||||
b. Where Your right to use the Licensed Material has terminated under
|
||||
Section 6(a), it reinstates:
|
||||
|
||||
1. automatically as of the date the violation is cured, provided
|
||||
it is cured within 30 days of Your discovery of the
|
||||
violation; or
|
||||
|
||||
2. upon express reinstatement by the Licensor.
|
||||
|
||||
For the avoidance of doubt, this Section 6(b) does not affect any
|
||||
right the Licensor may have to seek remedies for Your violations
|
||||
of this Public License.
|
||||
|
||||
c. For the avoidance of doubt, the Licensor may also offer the
|
||||
Licensed Material under separate terms or conditions or stop
|
||||
distributing the Licensed Material at any time; however, doing so
|
||||
will not terminate this Public License.
|
||||
|
||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
||||
License.
|
||||
|
||||
|
||||
Section 7 -- Other Terms and Conditions.
|
||||
|
||||
a. The Licensor shall not be bound by any additional or different
|
||||
terms or conditions communicated by You unless expressly agreed.
|
||||
|
||||
b. Any arrangements, understandings, or agreements regarding the
|
||||
Licensed Material not stated herein are separate from and
|
||||
independent of the terms and conditions of this Public License.
|
||||
|
||||
|
||||
Section 8 -- Interpretation.
|
||||
|
||||
a. For the avoidance of doubt, this Public License does not, and
|
||||
shall not be interpreted to, reduce, limit, restrict, or impose
|
||||
conditions on any use of the Licensed Material that could lawfully
|
||||
be made without permission under this Public License.
|
||||
|
||||
b. To the extent possible, if any provision of this Public License is
|
||||
deemed unenforceable, it shall be automatically reformed to the
|
||||
minimum extent necessary to make it enforceable. If the provision
|
||||
cannot be reformed, it shall be severed from this Public License
|
||||
without affecting the enforceability of the remaining terms and
|
||||
conditions.
|
||||
|
||||
c. No term or condition of this Public License will be waived and no
|
||||
failure to comply consented to unless expressly agreed to by the
|
||||
Licensor.
|
||||
|
||||
d. Nothing in this Public License constitutes or may be interpreted
|
||||
as a limitation upon, or waiver of, any privileges and immunities
|
||||
that apply to the Licensor or You, including from the legal
|
||||
processes of any jurisdiction or authority.
|
||||
|
||||
=======================================================================
|
||||
|
||||
Creative Commons is not a party to its public
|
||||
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
||||
its public licenses to material it publishes and in those instances
|
||||
will be considered the “Licensor.” The text of the Creative Commons
|
||||
public licenses is dedicated to the public domain under the CC0 Public
|
||||
Domain Dedication. Except for the limited purpose of indicating that
|
||||
material is shared under a Creative Commons public license or as
|
||||
otherwise permitted by the Creative Commons policies published at
|
||||
creativecommons.org/policies, Creative Commons does not authorize the
|
||||
use of the trademark "Creative Commons" or any other trademark or logo
|
||||
of Creative Commons without its prior written consent including,
|
||||
without limitation, in connection with any unauthorized modifications
|
||||
to any of its public licenses or any other arrangements,
|
||||
understandings, or agreements concerning use of licensed material. For
|
||||
the avoidance of doubt, this paragraph does not form part of the
|
||||
public licenses.
|
||||
|
||||
Creative Commons may be contacted at creativecommons.org.
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024-2026 SMKRV
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
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.
|
||||
|
||||
@@ -1,223 +1,241 @@
|
||||
# 🤖 HA Text AI for Home Assistant
|
||||
# HA Text AI for Home Assistant
|
||||
|
||||
<div align="center">
|
||||
|
||||
  [](https://opensource.org/licenses/MIT) [](https://github.com/hacs/integration)   
|
||||
  [](https://opensource.org/licenses/MIT) [](https://github.com/hacs/integration)
|
||||
       
|
||||
|
||||
<img src="https://github.com/smkrv/ha-text-ai/blob/524849f6a945ec62c2cf6a6b7ecd9a28b37bf0fa/misc/icons/logo.jpg" alt="HA Text AI" height="160"/>
|
||||
|
||||
### Advanced AI Integration for [Home Assistant](https://www.home-assistant.io/) with LLM multi-provider support
|
||||
<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;"/>
|
||||
|
||||
### Multi-provider LLM integration for [Home Assistant](https://www.home-assistant.io/)
|
||||
</div>
|
||||
|
||||
<p align="center">
|
||||
Transform your smart home experience with powerful AI assistance powered by multiple AI providers including OpenAI GPT and Anthropic Claude models. Get intelligent responses, automate complex scenarios, and enhance your home automation with advanced natural language processing.
|
||||
|
||||
Ask OpenAI, Anthropic Claude, DeepSeek and Google Gemini models questions from your automations and scripts. The integration keeps per-instance conversation history, returns full-length responses through response variables, supports structured JSON output, and exposes token, latency and error metrics as sensor attributes.
|
||||
</p>
|
||||
|
||||
---
|
||||
|
||||
> [!IMPORTANT]
|
||||
> 🚧 ALPHA VERSION 🚧
|
||||
> Expect: potential bugs, frequent changes, incomplete features.
|
||||
> 🤝 Community Driven
|
||||
> 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://community.home-assistant.io/t/ha-text-ai-transforming-home-automation-with-multi-provider-language-models/799741"><img src="https://img.shields.io/badge/Community-blue?style=for-the-badge&logo=homeassistant&logoColor=white&color=03a9f4"/></a>
|
||||
> <a href="https://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](misc/screenshots/screenshot.jpg)
|
||||
> [Screenshots](assets/images/screenshots/screenshot.jpg)
|
||||
|
||||
## 🌟 Features
|
||||
## Features
|
||||
|
||||
- 🧠 **Multi-Provider AI Integration**:
|
||||
- Support for OpenAI GPT models
|
||||
- Anthropic Claude integration
|
||||
- Custom API endpoints
|
||||
- Flexible model selection
|
||||
- **Multi-provider support**: OpenAI, Anthropic Claude, DeepSeek, Google Gemini, plus any OpenAI-compatible endpoint
|
||||
- **Conversation context**: the model sees previous messages; depth is configurable per request (1-20)
|
||||
- **Response variables**: `ask_question` returns the full response directly to the calling automation, bypassing the 255-character state limit
|
||||
- **Structured output**: JSON responses matching a schema you provide
|
||||
- **Per-request overrides**: model, temperature, max_tokens, system prompt, thinking mode
|
||||
- **Usage metrics**: token counters, latency and success/error statistics as sensor attributes
|
||||
- **File-based history**: per-instance JSON storage with automatic rotation at 1 MB
|
||||
|
||||
- 💬 **Advanced Language Processing**:
|
||||
- Context-aware responses
|
||||
- Multi-turn conversations
|
||||
- Custom system instructions
|
||||
- Natural conversation flow
|
||||
#### Translations
|
||||
|
||||
- 📝 **Enhanced Memory Management**:
|
||||
- Persistent conversation history
|
||||
- Context-aware responses
|
||||
- Customizable history limits
|
||||
- Model-specific filtering
|
||||
| Code | Language | Status |
|
||||
|------|----------|--------|
|
||||
| de | Deutsch | Full |
|
||||
| en | English | Primary |
|
||||
| es | Español | Full |
|
||||
| hi | हिन्दी | Full |
|
||||
| it | Italiano | Full |
|
||||
| ru | Русский | Full |
|
||||
| sr | Српски | Full |
|
||||
| zh | 中文 | Full |
|
||||
|
||||
- ⚡ **Performance Optimization**:
|
||||
- Efficient token usage
|
||||
- Smart rate limiting
|
||||
- Response caching
|
||||
- Request interval control
|
||||
## Prerequisites
|
||||
|
||||
- 🎯 **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
|
||||
|
||||
## 📋 Prerequisites
|
||||
|
||||
- Home Assistant 2024.11 or later
|
||||
- Active API key from:
|
||||
- Home Assistant 2024.12.0 or later
|
||||
- An API key from one of:
|
||||
- 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))
|
||||
- Python 3.9 or newer
|
||||
- Stable internet connection
|
||||
- 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
|
||||
|
||||
### Configuration Options
|
||||
- API Provider (OpenAI/Anthropic)
|
||||
- API Key (provider-specific)
|
||||
- Model Selection (flexible, provider-specific models)
|
||||
- Temperature (Creativity control, 0.0-2.0)
|
||||
- Max Tokens (Response length limit)
|
||||
- Request Interval (API call throttling)
|
||||
- Custom API Endpoint (optional)
|
||||
## Configuration Options
|
||||
|
||||
#### ⓘ Potentially Compatible Providers
|
||||
The integration is designed to be flexible and may work with other providers offering OpenAI-compatible APIs:
|
||||
- Groq
|
||||
- Together AI
|
||||
- Perplexity AI
|
||||
- Mistral AI
|
||||
- Google AI
|
||||
- Local AI servers (like Ollama)
|
||||
- Custom OpenAI-compatible endpoints
|
||||
### Core Configuration Settings
|
||||
- **API Provider**: OpenAI / Anthropic / DeepSeek / Gemini
|
||||
- **API Key**: provider-specific authentication
|
||||
- **Model**: any model your provider offers
|
||||
- **Temperature**: sampling temperature (0.0-2.0)
|
||||
- **Max Tokens**: response length cap, passed to the LLM API
|
||||
- **Request Interval**: minimum delay between API calls (seconds)
|
||||
- **History Size**: number of conversations to retain
|
||||
- **Custom API Endpoint**: for OpenRouter, proxies and self-hosted servers
|
||||
- **Disable Thinking**: turn off model reasoning where the provider supports it
|
||||
- **Allow Local Network**: permit endpoints on private addresses (needed for local servers like Ollama)
|
||||
|
||||
#### Additional Notes
|
||||
- Not all providers guarantee full compatibility
|
||||
- Performance may vary between providers
|
||||
- Check individual provider's documentation
|
||||
- Ensure your API key has sufficient credits/quota
|
||||
### Recommended Models
|
||||
|
||||
#### 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
|
||||
#### OpenAI Models
|
||||
- **GPT-5.6 Sol** - flagship tier for the hardest tasks
|
||||
- **GPT-5.6 Terra** - mid-tier for high-volume tasks
|
||||
- **GPT-5.6 Luna** - fastest and cheapest, enough for most home automation queries
|
||||
|
||||
## ⚡ Installation
|
||||
#### Anthropic Claude Models
|
||||
- **Claude Fable 5** - the most capable model for complex tasks
|
||||
- **Claude Sonnet 5** - balance between quality and cost
|
||||
- **Claude Haiku 4.5** - the fastest and cheapest option in the lineup
|
||||
|
||||
#### DeepSeek Models
|
||||
- **deepseek-v4-flash** - fast general-purpose model (default)
|
||||
- **deepseek-v4-pro** - stronger at reasoning and coding
|
||||
|
||||
> The legacy model names `deepseek-chat` and `deepseek-reasoner` stop working on 2026-07-24. If your instance still uses one of them, switch the model in the integration options.
|
||||
|
||||
#### Google Gemini Models
|
||||
- **gemini-3.5-flash** - default; Google's strongest currently available model
|
||||
- **gemini-3.1-pro** - previous flagship, still supported
|
||||
|
||||
> Google shut down `gemini-2.0-flash` on 2026-06-01 and retires the 2.5 family on 2026-10-16. If your instance uses one of those, switch the model in the integration options.
|
||||
|
||||
<details>
|
||||
<summary>Potentially Compatible Providers</summary>
|
||||
|
||||
Other providers with OpenAI-compatible APIs may work through the custom endpoint option:
|
||||
- Groq
|
||||
- Together AI
|
||||
- Perplexity AI
|
||||
- Mistral AI
|
||||
- Local AI servers (like Ollama - enable **Allow Local Network** in the options)
|
||||
- Custom OpenAI-compatible endpoints
|
||||
|
||||
Compatibility is not guaranteed. A provider needs an OpenAI-like REST API with JSON request/response format, standard bearer authentication and similar parameter handling. Check the provider's documentation and make sure your API key has sufficient quota.
|
||||
|
||||
</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. Click "..." in top right corner
|
||||
4. Select "Custom repositories"
|
||||
5. Add repository URL: `https://github.com/smkrv/ha-text-ai`
|
||||
6. Choose "Integration" as category
|
||||
7. Click "Download"
|
||||
8. Restart Home Assistant
|
||||
2. Search for "HA Text AI"
|
||||
3. Click "Download"
|
||||
4. 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
|
||||
1. Download the latest release
|
||||
2. Extract and copy `custom_components/ha_text_ai` to your `custom_components` directory
|
||||
1. Download `ha_text_ai.zip` from the latest release
|
||||
2. Extract the archive and copy the `ha_text_ai` folder into your `custom_components` directory
|
||||
3. Restart Home Assistant
|
||||
4. Add configuration via UI or YAML
|
||||
4. Add configuration via UI (Settings > Devices & Services > Add Integration)
|
||||
|
||||
## ⚙️ Configuration
|
||||
## Configuration
|
||||
|
||||
### Via UI (Recommended)
|
||||
1. Go to Settings → Devices & Services
|
||||
1. Go to Settings > Devices & Services
|
||||
2. Click "Add Integration"
|
||||
3. Search for "HA Text AI"
|
||||
4. Follow the configuration steps
|
||||
|
||||
### Via YAML
|
||||
> **Note:** This integration is configured exclusively through the UI (config entries). YAML configuration is not supported.
|
||||
|
||||
### Platform Configuration (Global Settings)
|
||||
## Quick Start
|
||||
|
||||
After configuration you get one entity per instance, named `sensor.ha_text_ai_<name>`. It is a status sensor: it shows the last response and usage metrics, but you don't type questions into it. Questions go through the `ha_text_ai.ask_question` action, called from Developer Tools, automations, or scripts.
|
||||
|
||||
### First question, no YAML
|
||||
|
||||
1. Open Developer Tools > Actions (called "Services" in older HA versions).
|
||||
2. Search for "HA Text AI: Ask Question".
|
||||
3. Pick your instance, type a question, press "Perform action".
|
||||
4. The response appears below the form.
|
||||
|
||||
### In an automation
|
||||
|
||||
1. Go to Settings > Automations & scenes > Create automation.
|
||||
2. Add a trigger: a button press, a time, a state change.
|
||||
3. Add action > search "HA Text AI: Ask Question" > fill in the question and pick your instance.
|
||||
4. To use the reply in a follow-up step, the action needs `response_variable: ai_response`. If the visual editor doesn't show a field for it, open the three-dot menu on that action, choose "Edit in YAML", and add the line at the end.
|
||||
5. In the next action, `{{ ai_response.response_text }}` holds the full answer, for example as a notification message.
|
||||
|
||||
Complete working automations: [Automation Examples](#automation-examples-with-response-variables).
|
||||
|
||||
### On a dashboard
|
||||
|
||||
The sensor keeps the last question and answer as attributes, so a Markdown card can show them:
|
||||
|
||||
```yaml
|
||||
ha_text_ai:
|
||||
api_provider: openai # Required
|
||||
api_key: !secret ai_api_key # Required
|
||||
model: gpt-4o-mini # Strongly recommended
|
||||
temperature: 0.7 # Optional
|
||||
max_tokens: 1000 # Optional
|
||||
request_interval: 1.0 # Optional
|
||||
api_endpoint: https://api.openai.com/v1 # Required
|
||||
system_prompt: | # Optional
|
||||
You are a home automation expert assistant.
|
||||
Focus on practical and efficient solutions.
|
||||
type: markdown
|
||||
content: >-
|
||||
**Q:** {{ state_attr('sensor.ha_text_ai_my_assistant', 'question') }}
|
||||
|
||||
**A:** {{ state_attr('sensor.ha_text_ai_my_assistant', 'response') }}
|
||||
```
|
||||
|
||||
### Sensor Configuration
|
||||
The attributes fill in after the first question. They are capped at 2048 characters, so long answers come back complete only via `response_variable`.
|
||||
|
||||
```yaml
|
||||
sensor:
|
||||
- platform: ha_text_ai
|
||||
name: "My AI Assistant" # Required, unique identifier
|
||||
api_provider: openai # Optional (inherits from platform)
|
||||
model: "gpt-4o-mini" # Optional
|
||||
temperature: 0.7 # Optional
|
||||
max_tokens: 1000 # Optional
|
||||
```
|
||||
## Available Services
|
||||
|
||||
### 📋 Configuration Parameters
|
||||
### Response Variables
|
||||
|
||||
#### Platform Configuration
|
||||
|
||||
| Parameter | Type | Required | Default | Description |
|
||||
|-----------|------|----------|---------|-------------|
|
||||
| `api_provider` | String | ✅ | - | AI service provider (openai, anthropic) |
|
||||
| `api_key` | String | ✅ | - | Authentication key for AI service |
|
||||
| `model` | String | ⚠️ | Provider default | Strongly recommended: Specific AI model to use. If not specified, the provider's default model will be used |
|
||||
| `temperature` | Float | ❌ | 0.7 | Response creativity level (0.0-2.0) |
|
||||
| `max_tokens` | Integer | ❌ | 1000 | Maximum response length |
|
||||
| `request_interval` | Float | ❌ | 1.0 | Delay between API requests |
|
||||
| `api_endpoint` | URL | ⚠️ | Provider default | Custom API endpoint |
|
||||
| `system_prompt` | String | ❌ | - | Default context for AI interactions |
|
||||
|
||||
#### Sensor Configuration
|
||||
|
||||
| Parameter | Type | Required | Default | Description |
|
||||
|-----------|------|----------|---------|-------------|
|
||||
| `platform` | String | ✅ | - | Must be `ha_text_ai` |
|
||||
| `name` | String | ✅ | - | Unique sensor identifier |
|
||||
| `api_provider` | String | ❌ | Platform setting | Override global provider |
|
||||
| `model` | String | ⚠️ | Platform setting | Recommended: Override global model. If not specified, uses platform or provider default |
|
||||
| `temperature` | Float | ❌ | Platform setting | Override global temperature |
|
||||
| `max_tokens` | Integer | ❌ | Platform setting | Override global max tokens |
|
||||
|
||||
## 🛠️ Available Services
|
||||
`ask_question` returns its result directly to the calling automation via `response_variable`. The full response text comes back regardless of length (no 255-character truncation), it is available immediately without polling sensor state, and each service call gets its own result, so parallel automations don't overwrite each other.
|
||||
|
||||
### ask_question
|
||||
```yaml
|
||||
service: ha_text_ai.ask_question
|
||||
data:
|
||||
question: "What's the optimal temperature for sleeping?"
|
||||
model: "claude-3-sonnet" # optional
|
||||
instance: sensor.ha_text_ai_claude
|
||||
model: "claude-sonnet-5" # optional, overrides the configured model
|
||||
temperature: 0.5 # optional
|
||||
max_tokens: 500 # optional
|
||||
context_messages: 10 #optional, number of previous messages to include in context, default: 5
|
||||
context_messages: 10 # optional, previous messages to include (1-20, default 5)
|
||||
system_prompt: "You are a sleep optimization expert" # optional
|
||||
disable_thinking: true # optional, disable model reasoning for this request
|
||||
response_variable: ai_response
|
||||
```
|
||||
|
||||
For structured JSON output, add `structured_output` with a schema:
|
||||
```yaml
|
||||
service: ha_text_ai.ask_question
|
||||
data:
|
||||
question: "Suggest three energy-saving actions for tonight"
|
||||
instance: sensor.ha_text_ai_gpt
|
||||
structured_output: true
|
||||
json_schema: >-
|
||||
{"type": "object", "properties": {"actions": {"type": "array", "items": {"type": "string"}}}}
|
||||
response_variable: ai_response
|
||||
```
|
||||
|
||||
#### 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-sonnet-5"
|
||||
instance: "sensor.ha_text_ai_claude"
|
||||
question: "What's the optimal temperature for sleeping?"
|
||||
timestamp: "2026-07-09T16:57:00.000Z"
|
||||
success: true
|
||||
# error and error_type are present only when success is false
|
||||
```
|
||||
|
||||
### set_system_prompt
|
||||
```yaml
|
||||
service: ha_text_ai.set_system_prompt
|
||||
data:
|
||||
instance: sensor.ha_text_ai_gpt
|
||||
prompt: |
|
||||
You are a home automation expert focused on:
|
||||
1. Energy efficiency
|
||||
@@ -229,34 +247,183 @@ data:
|
||||
### clear_history
|
||||
```yaml
|
||||
service: ha_text_ai.clear_history
|
||||
data:
|
||||
instance: sensor.ha_text_ai_gpt
|
||||
```
|
||||
|
||||
### get_history
|
||||
```yaml
|
||||
service: ha_text_ai.get_history
|
||||
data:
|
||||
limit: 5 # optional
|
||||
filter_model: "gpt-4o" # optional
|
||||
limit: 5 # optional, number of conversations to return (values above 200 are clamped); omit to get the full stored history
|
||||
filter_model: "gpt-4o" # optional, filter by specific AI model
|
||||
start_date: "2026-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
|
||||
response_variable: history_result # entries are in history_result.history
|
||||
```
|
||||
|
||||
### 🏷️ HA Text AI Sensor Naming Convention
|
||||
## Automation Examples with Response Variables
|
||||
|
||||
#### Character Restrictions
|
||||
- Only lowercase letters (a-z)
|
||||
- Numbers (0-9)
|
||||
- Underscore (_)
|
||||
- Maximum length: 50 characters (including `ha_text_ai_`)
|
||||
### Example 1: Smart Home Advice with Direct Response
|
||||
```yaml
|
||||
automation:
|
||||
- alias: "Get AI Home Advice"
|
||||
trigger:
|
||||
- platform: state
|
||||
entity_id: input_button.ask_ai_advice
|
||||
action:
|
||||
- service: ha_text_ai.ask_question
|
||||
data:
|
||||
question: "What's the best way to optimize energy usage in my home?"
|
||||
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 }}
|
||||
```
|
||||
|
||||
### Example 2: Weather-Based AI Recommendations
|
||||
```yaml
|
||||
automation:
|
||||
- alias: "Weather-Based AI Suggestions"
|
||||
trigger:
|
||||
- platform: numeric_state
|
||||
entity_id: sensor.outdoor_temperature
|
||||
below: 0
|
||||
action:
|
||||
- service: ha_text_ai.ask_question
|
||||
data:
|
||||
question: |
|
||||
The outdoor temperature is {{ states('sensor.outdoor_temperature') }}°C.
|
||||
What should I do to prepare my home for freezing weather?
|
||||
system_prompt: "You are a home maintenance expert. Provide practical, actionable advice."
|
||||
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 }}"
|
||||
```
|
||||
|
||||
### 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
|
||||
|
||||
Analyze this data and provide insights.
|
||||
instance: sensor.ha_text_ai_gpt
|
||||
response_variable: status_analysis
|
||||
|
||||
# Step 2: Get recommendations based on analysis
|
||||
- service: ha_text_ai.ask_question
|
||||
data:
|
||||
question: |
|
||||
Based on this analysis: "{{ status_analysis.response_text[:500] }}"
|
||||
|
||||
Provide 3 specific actionable recommendations for improvement.
|
||||
context_messages: 2 # Include previous conversation
|
||||
instance: sensor.ha_text_ai_gpt
|
||||
response_variable: recommendations
|
||||
|
||||
# Step 3: Send the combined 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:
|
||||
```yaml
|
||||
# Old way: delay-based polling, response truncated by the 255-character state limit
|
||||
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:
|
||||
```yaml
|
||||
# New way: full response, available immediately
|
||||
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
|
||||
- service: notify.mobile
|
||||
data:
|
||||
message: "{{ ai_response.response_text }}" # Full response, no truncation
|
||||
```
|
||||
|
||||
### HA Text AI Sensor Naming Convention
|
||||
|
||||
#### Naming Rules
|
||||
- Only lowercase letters (a-z), numbers (0-9) and underscore (_)
|
||||
- The part after the `sensor.ha_text_ai_` prefix is limited to 50 characters
|
||||
- No spaces; keep it descriptive but short
|
||||
|
||||
#### Sensor Name Structure
|
||||
```yaml
|
||||
# Always starts with 'sensor.ha_text_ai_'
|
||||
# You define only the part after the underscore
|
||||
# You define only the part after the prefix
|
||||
sensor.ha_text_ai_YOUR_UNIQUE_SUFFIX
|
||||
|
||||
# Examples:
|
||||
sensor.ha_text_ai_gpt # GPT-based sensor
|
||||
sensor.ha_text_ai_claude # Claude-based sensor
|
||||
sensor.ha_text_ai_gpt # Custom suffix
|
||||
sensor.ha_text_ai_abc # Custom suffix
|
||||
```
|
||||
|
||||
#### Response Retrieval
|
||||
@@ -273,6 +440,7 @@ automation:
|
||||
- service: ha_text_ai.ask_question
|
||||
data:
|
||||
question: "Home automation advice"
|
||||
instance: sensor.ha_text_ai_gpt
|
||||
- service: notify.mobile
|
||||
data:
|
||||
message: >
|
||||
@@ -280,129 +448,149 @@ automation:
|
||||
{{ 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
|
||||
|
||||
### 🔍 HA Text AI Sensor Attributes
|
||||
- **Model and provider**: current model, API provider, model used for the last response
|
||||
- **System status**: processing, rate-limit and endpoint state
|
||||
- **Performance metrics**: request success/failure counters and latency statistics
|
||||
- **Token usage**: total, prompt and completion token counters as reported by the provider's API
|
||||
- **Last interaction**: most recent question, response and timestamp
|
||||
- **System health**: error counter, maintenance flag, uptime
|
||||
|
||||
Attributes may be 0 or empty until the first request completes.
|
||||
|
||||
<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
|
||||
# Model currently configured for this instance
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'model') }} # gpt-4o-mini
|
||||
|
||||
# Service provider for the AI model (determines API endpoint and authentication)
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'Api provider') }} # openai
|
||||
# Service provider (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
|
||||
# Model that produced the last response (may differ after a per-request override)
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'last_model') }} # gpt-4o-mini
|
||||
```
|
||||
|
||||
#### 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
|
||||
|
||||
# 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
|
||||
|
||||
# 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
|
||||
# Status of the 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 successfully completed API requests
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'successful_requests') }} # 42
|
||||
|
||||
# Number of API requests that encountered errors
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'Failed 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
|
||||
# Average / max / min response time, in seconds
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'average_latency') }} # 1.85
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'max_latency') }} # 4.2
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'min_latency') }} # 0.9
|
||||
```
|
||||
|
||||
#### Conversation and Token Usage
|
||||
```yaml
|
||||
# Number of previous interactions stored in conversation context
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'History size') }} # 0
|
||||
# Number of entries in the current history file
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'history_size') }} # 12
|
||||
|
||||
# Total number of tokens used across all interactions
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'Total tokens') }} # 0
|
||||
# Token counters as reported by the provider's API
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'total_tokens') }} # 4520
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'prompt_tokens') }} # 3100
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'completion_tokens') }} # 1420
|
||||
|
||||
# Tokens used in the input prompts
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'Prompt tokens') }} # 0
|
||||
|
||||
# Tokens used in the AI's generated responses
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'Completion tokens') }} # 0
|
||||
# Last 3 conversation entries, each truncated to 256 characters
|
||||
# (full history is available via the get_history service)
|
||||
{{ 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
|
||||
# Most recent response, truncated to 2048 characters in the attribute
|
||||
# (the response_variable path returns the full text)
|
||||
{{ 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
|
||||
# The most recently processed question
|
||||
{{ 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
|
||||
# When the last interaction occurred
|
||||
{{ 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
|
||||
# Cumulative count of errors across all requests
|
||||
{{ 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
|
||||
# Error message of the last failed request (null after a success)
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'last_error') }} # null
|
||||
|
||||
# Total continuous operational time of the AI service (in hours or days)
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'Uptime') }} # 547,58
|
||||
# Maintenance flag
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'is_maintenance') }} # false
|
||||
|
||||
# Seconds since the integration instance was set up
|
||||
{{ state_attr('sensor.ha_text_ai_gpt', 'uptime') }} # 547.58
|
||||
```
|
||||
|
||||
### 💡 Pro Tips
|
||||
- Always check attribute existence
|
||||
- Use these attributes for monitoring and automation
|
||||
- Some values might be 0 or empty initially
|
||||
### 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
|
||||
|
||||
</details>
|
||||
|
||||
## 📘 FAQ
|
||||
## FAQ
|
||||
|
||||
**Q: Which AI providers are supported?**
|
||||
A: Currently OpenAI (GPT models) and Anthropic (Claude models) are supported, with more providers planned.
|
||||
A: OpenAI, Anthropic, DeepSeek and Google Gemini are built-in providers. OpenRouter and other OpenAI-compatible services work through the OpenAI provider with a custom endpoint.
|
||||
|
||||
**Q: How can I reduce API costs?**
|
||||
A: Use GPT-3.5-Turbo or Claude-3-Sonnet for most queries, implement caching, and optimize token usage.
|
||||
A: Use a cheap fast model (GPT-5.6 Luna, Claude Haiku 4.5, deepseek-v4-flash, gemini-3.5-flash) for routine queries, lower `context_messages`, and cap `max_tokens`.
|
||||
|
||||
**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.
|
||||
A: Depends on your API provider's plan. Monitor usage via the sensor attributes and throttle calls with the `request_interval` option.
|
||||
|
||||
**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.
|
||||
A: Each integration instance is bound to one provider. Add a separate instance per provider and pick the instance in your service calls; within an instance you can override the model per request.
|
||||
|
||||
**Q: How can I reduce API costs?**
|
||||
A: Use GPT-3.5-Turbo for most queries, implement caching, and optimize token usage.
|
||||
**Q: What are the token limits for different models?**
|
||||
A: Context window sizes vary by provider and model - check your provider's documentation. The `max_tokens` option caps only the response length, not the context window.
|
||||
|
||||
**Q: How do I monitor token usage?**
|
||||
A: Use the sensor attributes `total_tokens`, `prompt_tokens` and `completion_tokens`. You can also create automations to alert you when usage exceeds a threshold.
|
||||
|
||||
**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.
|
||||
A: Conversation history and API keys are stored locally in your Home Assistant instance. Questions and context are sent to the provider you configure over HTTPS; nothing is shared with third parties beyond that provider.
|
||||
|
||||
**Q: How do context messages work?**
|
||||
A: Context messages allow the AI to remember and reference previous conversation history. By default, 5 previous messages are included, but you can customize this from 1 to 20 messages to control the conversation depth and token usage.
|
||||
A: Context messages let the AI reference previous conversation history. By default 5 previous messages are included; you can set 1 to 20 per request to balance conversation depth against token usage.
|
||||
|
||||
## 🤝 Contributing
|
||||
**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: 50 conversations by default, configurable up to 100 in the UI. Files are automatically rotated when they reach 1MB.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributions welcome! Please read our [Contributing Guide](CONTRIBUTING.md).
|
||||
|
||||
@@ -425,12 +613,12 @@ 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
|
||||
|
||||
Author: SMKRV
|
||||
[CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) - see [LICENSE](LICENSE) for details.
|
||||
[MIT License](https://opensource.org/licenses/MIT) - see [LICENSE](LICENSE) for details.
|
||||
|
||||
## 💡 Support the Project
|
||||
## Support the Project
|
||||
|
||||
The best support is:
|
||||
- Sharing feedback
|
||||
@@ -444,13 +632,12 @@ If you want to say thanks financially, you can send a small token of appreciatio
|
||||
**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">
|
||||
|
||||
Made with ❤️ and Claude 3.5 Sonnet for the Home Assistant Community
|
||||
Made 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)
|
||||
|
||||
|
||||
@@ -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 |
|
Before Width: | Height: | Size: 618 KiB After Width: | Height: | Size: 618 KiB |
|
Before Width: | Height: | Size: 923 KiB After Width: | Height: | Size: 923 KiB |
|
After Width: | Height: | Size: 339 KiB |
|
Before Width: | Height: | Size: 1.0 MiB After Width: | Height: | Size: 1.0 MiB |
@@ -1,7 +1,7 @@
|
||||
"""
|
||||
The HA Text AI integration.
|
||||
|
||||
@license: CC BY-NC-SA 4.0 International
|
||||
@license: MIT (https://opensource.org/licenses/MIT)
|
||||
@author: SMKRV
|
||||
@github: https://github.com/smkrv/ha-text-ai
|
||||
@source: https://github.com/smkrv/ha-text-ai
|
||||
@@ -9,23 +9,23 @@ The HA Text AI integration.
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict
|
||||
from typing import Any
|
||||
|
||||
import asyncio
|
||||
|
||||
import voluptuous as vol
|
||||
from async_timeout import timeout
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.const import CONF_API_KEY, CONF_NAME, Platform
|
||||
from homeassistant.core import HomeAssistant, ServiceCall
|
||||
from homeassistant.const import CONF_API_KEY, CONF_NAME, EVENT_HOMEASSISTANT_CLOSE
|
||||
from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse
|
||||
from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers import aiohttp_client
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from .coordinator import HATextAICoordinator
|
||||
from .api_client import APIClient
|
||||
from .utils import create_pinned_session, normalize_name, safe_log_data, validate_endpoint
|
||||
from .providers import get_default_endpoint, get_default_model, build_auth_headers
|
||||
from .const import (
|
||||
DOMAIN,
|
||||
PLATFORMS,
|
||||
@@ -34,24 +34,24 @@ from .const import (
|
||||
CONF_MAX_TOKENS,
|
||||
CONF_API_ENDPOINT,
|
||||
CONF_REQUEST_INTERVAL,
|
||||
CONF_API_TIMEOUT,
|
||||
CONF_API_PROVIDER,
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
API_PROVIDER_OPENAI,
|
||||
API_PROVIDER_ANTHROPIC,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_TEMPERATURE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
DEFAULT_OPENAI_ENDPOINT,
|
||||
DEFAULT_ANTHROPIC_ENDPOINT,
|
||||
DEFAULT_REQUEST_INTERVAL,
|
||||
DEFAULT_API_TIMEOUT,
|
||||
DEFAULT_CONTEXT_MESSAGES,
|
||||
API_TIMEOUT,
|
||||
SERVICE_ASK_QUESTION,
|
||||
SERVICE_CLEAR_HISTORY,
|
||||
SERVICE_GET_HISTORY,
|
||||
SERVICE_SET_SYSTEM_PROMPT,
|
||||
DEFAULT_MAX_HISTORY,
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
CONF_ALLOW_LOCAL_NETWORK,
|
||||
DEFAULT_ALLOW_LOCAL_NETWORK,
|
||||
CONF_DISABLE_THINKING,
|
||||
DEFAULT_DISABLE_THINKING,
|
||||
)
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
@@ -60,12 +60,17 @@ CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
|
||||
|
||||
SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
|
||||
vol.Required("instance"): cv.string,
|
||||
vol.Required("question"): cv.string,
|
||||
vol.Optional("system_prompt"): cv.string,
|
||||
vol.Required("question"): vol.All(cv.string, vol.Length(min=1, max=100000)),
|
||||
vol.Optional("system_prompt"): vol.All(cv.string, vol.Length(max=50000)),
|
||||
vol.Optional("model"): cv.string,
|
||||
vol.Optional("temperature"): cv.positive_float,
|
||||
vol.Optional("temperature"): vol.All(
|
||||
vol.Coerce(float), vol.Range(min=0.0, max=2.0)
|
||||
),
|
||||
vol.Optional("max_tokens"): cv.positive_int,
|
||||
vol.Optional("context_messages"): cv.positive_int,
|
||||
vol.Optional("structured_output", default=False): cv.boolean,
|
||||
vol.Optional("json_schema"): vol.All(cv.string, vol.Length(max=50000)),
|
||||
vol.Optional("disable_thinking"): cv.boolean,
|
||||
})
|
||||
|
||||
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
|
||||
@@ -75,50 +80,100 @@ SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
|
||||
|
||||
SERVICE_SCHEMA_GET_HISTORY = vol.Schema({
|
||||
vol.Required("instance"): cv.string,
|
||||
vol.Optional("limit"): cv.positive_int,
|
||||
# No default and no schema max: omitting limit returns the full history
|
||||
# (pre-2.5.0 behavior) and oversized values are clamped to
|
||||
# ABSOLUTE_MAX_HISTORY_SIZE in history.async_get_history instead of
|
||||
# failing the whole service call.
|
||||
vol.Optional("limit"): vol.All(cv.positive_int, vol.Range(min=1)),
|
||||
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."""
|
||||
"""Get coordinator by instance name or normalized name.
|
||||
|
||||
Accepts instance_name, normalized_name, or sensor entity_id.
|
||||
"""
|
||||
if instance.startswith("sensor."):
|
||||
instance = instance.replace("sensor.ha_text_ai_", "", 1)
|
||||
|
||||
normalized_input = normalize_name(instance)
|
||||
|
||||
for entry_id, coord in hass.data[DOMAIN].items():
|
||||
if isinstance(coord, HATextAICoordinator) and coord.instance_name.lower() == instance.lower():
|
||||
if not isinstance(coord, HATextAICoordinator):
|
||||
continue
|
||||
if (
|
||||
coord.instance_name.lower() == instance.lower()
|
||||
or coord.normalized_name == normalized_input
|
||||
):
|
||||
return coord
|
||||
|
||||
raise HomeAssistantError(f"Instance {instance} not found")
|
||||
|
||||
async def async_setup(hass: HomeAssistant, config: Dict[str, Any]) -> bool:
|
||||
"""Set up the HA Text AI component."""
|
||||
async def async_setup(hass: HomeAssistant, config: dict[str, Any]) -> bool:
|
||||
"""Set up the Home Assistant Text AI component."""
|
||||
# Initialize domain data storage
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
_async_register_services(hass)
|
||||
return True
|
||||
|
||||
try:
|
||||
source = os.path.join(os.path.dirname(__file__), 'icons', 'icon.svg')
|
||||
dest_dir = os.path.join(hass.config.path('www'), 'icons')
|
||||
os.makedirs(dest_dir, exist_ok=True)
|
||||
dest = os.path.join(dest_dir, 'icon.png')
|
||||
if not os.path.exists(dest):
|
||||
shutil.copyfile(source, dest)
|
||||
except Exception as ex:
|
||||
_LOGGER.warning("Failed to copy custom icon: %s", str(ex))
|
||||
def _async_register_services(hass: HomeAssistant) -> None:
|
||||
"""Register domain services; safe to call again after unload.
|
||||
|
||||
async def async_ask_question(call: ServiceCall) -> None:
|
||||
"""Handle ask_question service."""
|
||||
Unloading the last config entry unregisters the services, and a config
|
||||
entry reload (every options change does one) runs unload + setup_entry
|
||||
without re-running async_setup — so setup_entry must be able to bring
|
||||
the services back.
|
||||
"""
|
||||
if hass.services.has_service(DOMAIN, SERVICE_ASK_QUESTION):
|
||||
return
|
||||
|
||||
async def async_ask_question(call: ServiceCall) -> dict:
|
||||
"""Handle ask_question service with response data."""
|
||||
try:
|
||||
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||
await coordinator.async_ask_question(
|
||||
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"),
|
||||
disable_thinking=call.data.get("disable_thinking"),
|
||||
)
|
||||
|
||||
# Return structured response data
|
||||
return {
|
||||
"response_text": response.get("content", ""),
|
||||
"tokens_used": response.get("tokens", {}).get("total", 0),
|
||||
"prompt_tokens": response.get("tokens", {}).get("prompt", 0),
|
||||
"completion_tokens": response.get("tokens", {}).get("completion", 0),
|
||||
"model_used": response.get("model", call.data.get("model", coordinator.model)),
|
||||
"instance": call.data["instance"],
|
||||
"question": call.data["question"],
|
||||
"timestamp": response.get("timestamp"),
|
||||
"success": True
|
||||
}
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error asking question: %s", str(err))
|
||||
raise HomeAssistantError(f"Failed to process question: {str(err)}")
|
||||
# Return error response
|
||||
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": dt_util.utcnow().isoformat(),
|
||||
"success": False,
|
||||
"error": str(err),
|
||||
"error_type": type(err).__name__
|
||||
}
|
||||
|
||||
async def async_clear_history(call: ServiceCall) -> None:
|
||||
"""Handle clear_history service."""
|
||||
@@ -127,19 +182,26 @@ async def async_setup(hass: HomeAssistant, config: Dict[str, Any]) -> bool:
|
||||
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)}")
|
||||
raise HomeAssistantError(f"Failed to clear history: {str(err)}") from err
|
||||
|
||||
async def async_get_history(call: ServiceCall) -> list:
|
||||
async def async_get_history(call: ServiceCall) -> dict:
|
||||
"""Handle get_history service."""
|
||||
try:
|
||||
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||
return await coordinator.async_get_history(
|
||||
history = await coordinator.async_get_history(
|
||||
limit=call.data.get("limit"),
|
||||
filter_model=call.data.get("filter_model")
|
||||
filter_model=call.data.get("filter_model"),
|
||||
start_date=call.data.get("start_date"),
|
||||
include_metadata=call.data.get("include_metadata", False),
|
||||
sort_order=call.data.get("sort_order", "newest")
|
||||
)
|
||||
# HA requires action responses to be dicts. The bare list made
|
||||
# every return_response call fail with a server error, so this
|
||||
# path never worked before and the wrapper breaks no consumer.
|
||||
return {"history": history}
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error getting history: %s", str(err))
|
||||
raise HomeAssistantError(f"Failed to get history: {str(err)}")
|
||||
raise HomeAssistantError(f"Failed to get history: {str(err)}") from err
|
||||
|
||||
async def async_set_system_prompt(call: ServiceCall) -> None:
|
||||
"""Handle set_system_prompt service."""
|
||||
@@ -148,13 +210,15 @@ async def async_setup(hass: HomeAssistant, config: Dict[str, Any]) -> bool:
|
||||
await coordinator.async_set_system_prompt(call.data["prompt"])
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error setting system prompt: %s", str(err))
|
||||
raise HomeAssistantError(f"Failed to set system prompt: {str(err)}")
|
||||
raise HomeAssistantError(f"Failed to set system prompt: {str(err)}") from err
|
||||
|
||||
# Register services
|
||||
hass.services.async_register(
|
||||
DOMAIN,
|
||||
SERVICE_ASK_QUESTION,
|
||||
async_ask_question,
|
||||
schema=SERVICE_SCHEMA_ASK_QUESTION
|
||||
schema=SERVICE_SCHEMA_ASK_QUESTION,
|
||||
supports_response=SupportsResponse.OPTIONAL
|
||||
)
|
||||
|
||||
hass.services.async_register(
|
||||
@@ -168,7 +232,8 @@ async def async_setup(hass: HomeAssistant, config: Dict[str, Any]) -> bool:
|
||||
DOMAIN,
|
||||
SERVICE_GET_HISTORY,
|
||||
async_get_history,
|
||||
schema=SERVICE_SCHEMA_GET_HISTORY
|
||||
schema=SERVICE_SCHEMA_GET_HISTORY,
|
||||
supports_response=SupportsResponse.OPTIONAL
|
||||
)
|
||||
|
||||
hass.services.async_register(
|
||||
@@ -178,22 +243,33 @@ async def async_setup(hass: HomeAssistant, config: Dict[str, Any]) -> bool:
|
||||
schema=SERVICE_SCHEMA_SET_SYSTEM_PROMPT
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
async def async_check_api(session, endpoint: str, headers: dict, provider: str) -> bool:
|
||||
"""Check API availability for different providers."""
|
||||
async def async_check_api(session, endpoint: str, headers: dict, provider: str, api_timeout: int = DEFAULT_API_TIMEOUT) -> bool:
|
||||
"""Check API availability using provider registry configuration."""
|
||||
try:
|
||||
if provider == API_PROVIDER_ANTHROPIC:
|
||||
check_url = f"{endpoint}/v1/models"
|
||||
else: # OpenAI
|
||||
check_url = f"{endpoint}/models"
|
||||
from .providers import get_provider_config
|
||||
provider_config = get_provider_config(provider)
|
||||
check_path = provider_config.get("check_path")
|
||||
|
||||
async with timeout(API_TIMEOUT):
|
||||
async with session.get(check_url, headers=headers) as response:
|
||||
if response.status in [200, 404]:
|
||||
if check_path is None:
|
||||
# Provider does not support /models check (e.g. Gemini)
|
||||
auth_header = provider_config["auth_header"]
|
||||
auth_value = headers.get(auth_header, "").replace(provider_config.get("auth_prefix", ""), "")
|
||||
if auth_value:
|
||||
return True
|
||||
_LOGGER.error("API key is missing or empty for %s", provider)
|
||||
return False
|
||||
|
||||
check_url = f"{endpoint}{check_path}"
|
||||
|
||||
async with asyncio.timeout(api_timeout):
|
||||
async with session.get(
|
||||
check_url, headers=headers, allow_redirects=False
|
||||
) as response:
|
||||
if response.status == 200:
|
||||
return True
|
||||
elif response.status == 401:
|
||||
raise ConfigEntryNotReady("Invalid API key")
|
||||
_LOGGER.error("Invalid API key")
|
||||
return False
|
||||
elif response.status == 429:
|
||||
_LOGGER.warning("Rate limit exceeded during API check")
|
||||
return False
|
||||
@@ -206,43 +282,54 @@ async def async_check_api(session, endpoint: str, headers: dict, provider: str)
|
||||
|
||||
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}")
|
||||
_LOGGER.debug("Setting up HA Text AI entry: %s", safe_log_data(dict(entry.data)))
|
||||
|
||||
session = None
|
||||
try:
|
||||
if CONF_API_PROVIDER not in entry.data:
|
||||
# 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")
|
||||
|
||||
# Get configuration
|
||||
session = aiohttp_client.async_get_clientsession(hass)
|
||||
api_provider = entry.data.get(CONF_API_PROVIDER)
|
||||
model = entry.data.get(CONF_MODEL, DEFAULT_MODEL)
|
||||
endpoint = entry.data.get(
|
||||
CONF_API_ENDPOINT,
|
||||
DEFAULT_OPENAI_ENDPOINT if api_provider == API_PROVIDER_OPENAI
|
||||
else DEFAULT_ANTHROPIC_ENDPOINT
|
||||
).rstrip('/')
|
||||
api_key = entry.data[CONF_API_KEY]
|
||||
model = config.get(CONF_MODEL, get_default_model(api_provider))
|
||||
raw_endpoint = config.get(CONF_API_ENDPOINT, get_default_endpoint(api_provider))
|
||||
allow_local = config.get(CONF_ALLOW_LOCAL_NETWORK, DEFAULT_ALLOW_LOCAL_NETWORK)
|
||||
if allow_local:
|
||||
_LOGGER.info(
|
||||
"Local network mode enabled for endpoint %s — "
|
||||
"SSRF protection relaxed for self-hosted proxies",
|
||||
raw_endpoint,
|
||||
)
|
||||
try:
|
||||
endpoint, resolved_ips = await validate_endpoint(
|
||||
hass, raw_endpoint, allow_local=allow_local
|
||||
)
|
||||
except ValueError as err:
|
||||
_LOGGER.error("Invalid API endpoint: %s", err)
|
||||
raise ConfigEntryNotReady(f"Invalid API endpoint: {err}") from err
|
||||
|
||||
# Pinned session closes DNS-rebinding TOCTOU and isolates cookies
|
||||
# from other integrations sharing the same endpoint hostname.
|
||||
# The integration owns this session: APIClient.shutdown() closes it
|
||||
# on unload, the except handler below closes it on failed setup.
|
||||
session = create_pinned_session(endpoint, resolved_ips)
|
||||
# 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 = entry.data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
||||
max_tokens = entry.data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
||||
temperature = entry.data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
||||
max_history_size = entry.data.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
|
||||
context_messages = entry.data.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
|
||||
is_anthropic = api_provider == API_PROVIDER_ANTHROPIC
|
||||
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)
|
||||
disable_thinking = config.get(CONF_DISABLE_THINKING, DEFAULT_DISABLE_THINKING)
|
||||
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json"
|
||||
}
|
||||
headers = build_auth_headers(api_provider, api_key)
|
||||
|
||||
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):
|
||||
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)
|
||||
@@ -253,6 +340,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
headers=headers,
|
||||
api_provider=api_provider,
|
||||
model=model,
|
||||
api_timeout=api_timeout,
|
||||
api_key=api_key,
|
||||
)
|
||||
|
||||
coordinator = HATextAICoordinator(
|
||||
@@ -261,45 +350,89 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||
model=model,
|
||||
update_interval=request_interval,
|
||||
instance_name=instance_name,
|
||||
config_entry=entry,
|
||||
max_tokens=max_tokens,
|
||||
temperature=temperature,
|
||||
max_history_size=max_history_size,
|
||||
context_messages=context_messages,
|
||||
is_anthropic=is_anthropic,
|
||||
api_timeout=api_timeout,
|
||||
disable_thinking=disable_thinking,
|
||||
)
|
||||
|
||||
_LOGGER.debug(f"Created coordinator for {instance_name}")
|
||||
# Initialize coordinator (directories, history, metrics)
|
||||
await coordinator.async_initialize()
|
||||
|
||||
_LOGGER.debug("Created coordinator for %s", instance_name)
|
||||
|
||||
# Store coordinator
|
||||
hass.data.setdefault(DOMAIN, {})
|
||||
hass.data[DOMAIN][entry.entry_id] = coordinator
|
||||
|
||||
_LOGGER.debug(f"Stored coordinator in hass.data[{DOMAIN}][{entry.entry_id}]")
|
||||
# A reload after the last entry was unloaded needs the services back.
|
||||
_async_register_services(hass)
|
||||
|
||||
_LOGGER.debug("Stored coordinator in hass.data[%s][%s]", DOMAIN, entry.entry_id)
|
||||
|
||||
# Set up platforms
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
_LOGGER.debug(f"Setup completed for {instance_name}")
|
||||
# Register update listener for options changes
|
||||
entry.async_on_unload(entry.add_update_listener(async_update_options))
|
||||
|
||||
# HA Core stop does not unload entries, so close the dedicated
|
||||
# session on the CLOSE event too; unload removes this listener
|
||||
# and closes the session via APIClient.shutdown() instead.
|
||||
async def _async_close_session_on_stop(_event) -> None:
|
||||
if not session.closed:
|
||||
await session.close()
|
||||
|
||||
entry.async_on_unload(
|
||||
hass.bus.async_listen_once(
|
||||
EVENT_HOMEASSISTANT_CLOSE, _async_close_session_on_stop
|
||||
)
|
||||
)
|
||||
|
||||
_LOGGER.debug("Setup completed for %s", instance_name)
|
||||
|
||||
return True
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.exception(f"Error setting up HA Text AI: {err}")
|
||||
_LOGGER.exception("Error setting up HA Text AI: %s", err)
|
||||
if session is not None and not session.closed:
|
||||
await session.close()
|
||||
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:
|
||||
"""Unload a config entry."""
|
||||
try:
|
||||
if entry.entry_id in hass.data[DOMAIN]:
|
||||
coordinator = hass.data[DOMAIN][entry.entry_id]
|
||||
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
if unload_ok and entry.entry_id in hass.data[DOMAIN]:
|
||||
coordinator = hass.data[DOMAIN].pop(entry.entry_id)
|
||||
|
||||
if hasattr(coordinator.client, 'shutdown'):
|
||||
await coordinator.client.shutdown()
|
||||
|
||||
await coordinator.async_shutdown()
|
||||
hass.data[DOMAIN].pop(entry.entry_id)
|
||||
|
||||
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
# When removing the last config entry, also unregister services and
|
||||
# clear the domain bucket so HA doesn't show stale services in the UI.
|
||||
if not hass.data.get(DOMAIN):
|
||||
hass.data.pop(DOMAIN, None)
|
||||
for service in (
|
||||
SERVICE_ASK_QUESTION,
|
||||
SERVICE_CLEAR_HISTORY,
|
||||
SERVICE_GET_HISTORY,
|
||||
SERVICE_SET_SYSTEM_PROMPT,
|
||||
):
|
||||
if hass.services.has_service(DOMAIN, service):
|
||||
hass.services.async_remove(DOMAIN, service)
|
||||
|
||||
return unload_ok
|
||||
|
||||
except Exception as ex:
|
||||
_LOGGER.exception("Error unloading entry: %s", str(ex))
|
||||
|
||||
@@ -1,23 +1,28 @@
|
||||
"""
|
||||
API Client for HA Text AI.
|
||||
|
||||
@license: CC BY-NC-SA 4.0 International
|
||||
@license: MIT (https://opensource.org/licenses/MIT)
|
||||
@author: SMKRV
|
||||
@github: https://github.com/smkrv/ha-text-ai
|
||||
@source: https://github.com/smkrv/ha-text-ai
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
import asyncio
|
||||
from typing import Any, Dict, List, Optional
|
||||
import re
|
||||
from typing import Any
|
||||
from aiohttp import ClientSession, ClientTimeout
|
||||
from async_timeout import timeout
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from .const import (
|
||||
API_TIMEOUT,
|
||||
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,
|
||||
@@ -26,7 +31,6 @@ from .const import (
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class APIClient:
|
||||
"""API Client for OpenAI and Anthropic."""
|
||||
|
||||
@@ -34,9 +38,11 @@ class APIClient:
|
||||
self,
|
||||
session: ClientSession,
|
||||
endpoint: str,
|
||||
headers: Dict[str, str],
|
||||
headers: dict[str, str],
|
||||
api_provider: str,
|
||||
model: str,
|
||||
api_timeout: int = DEFAULT_API_TIMEOUT,
|
||||
api_key: str | None = None,
|
||||
) -> None:
|
||||
"""Initialize API client."""
|
||||
self.session = session
|
||||
@@ -44,105 +50,420 @@ class APIClient:
|
||||
self.headers = headers
|
||||
self.api_provider = api_provider
|
||||
self.model = model
|
||||
self.timeout = ClientTimeout(total=API_TIMEOUT)
|
||||
self.api_timeout = api_timeout
|
||||
self.timeout = ClientTimeout(total=api_timeout)
|
||||
self._api_key = api_key
|
||||
if self.api_provider == API_PROVIDER_GEMINI and not api_key:
|
||||
raise ValueError("Gemini provider requires api_key parameter")
|
||||
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."""
|
||||
"""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}"
|
||||
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}"
|
||||
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."""
|
||||
_LOGGER.debug(f"API Request: URL={url}, Payload={payload}")
|
||||
payload: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""Make API request with retry logic for transient errors only.
|
||||
|
||||
Retries on:
|
||||
- asyncio.TimeoutError
|
||||
- HTTP 429 (rate limit) — honors Retry-After header when present
|
||||
- HTTP 502/503/504 (upstream transient errors)
|
||||
|
||||
4xx (other than 429) return immediately — they are not retryable.
|
||||
"""
|
||||
safe_payload = {k: v for k, v in payload.items() if k not in ['messages', 'system']}
|
||||
_LOGGER.debug("API Request: URL=%s, Safe payload: %s", url, safe_payload)
|
||||
|
||||
retryable_5xx = {502, 503, 504}
|
||||
|
||||
for attempt in range(API_RETRY_COUNT):
|
||||
try:
|
||||
async with timeout(API_TIMEOUT):
|
||||
async with self.session.post(
|
||||
url,
|
||||
json=payload,
|
||||
headers=self.headers,
|
||||
timeout=self.timeout,
|
||||
) as response:
|
||||
_LOGGER.debug(f"Response status: {response.status}")
|
||||
if response.status != 200:
|
||||
error_data = await response.json()
|
||||
_LOGGER.error(f"API error: {error_data}")
|
||||
raise HomeAssistantError(f"API error: {error_data}")
|
||||
async with self.session.post(
|
||||
url,
|
||||
json=payload,
|
||||
headers=self.headers,
|
||||
timeout=self.timeout,
|
||||
# The session pins DNS to validated IPs; following a
|
||||
# redirect would resolve a new host past that pin.
|
||||
allow_redirects=False,
|
||||
) as response:
|
||||
_LOGGER.debug("Response status: %s", response.status)
|
||||
if response.status == 200:
|
||||
return await response.json()
|
||||
except asyncio.TimeoutError:
|
||||
_LOGGER.warning(f"Timeout on attempt {attempt + 1}")
|
||||
|
||||
# Try to get error details
|
||||
error_data = {}
|
||||
try:
|
||||
error_data = await response.json()
|
||||
except Exception:
|
||||
error_data = {"raw": await response.text()}
|
||||
|
||||
# Rate limit — retry with backoff, prefer Retry-After header
|
||||
if response.status == 429:
|
||||
_LOGGER.warning(
|
||||
"Rate limit on attempt %d/%d", attempt + 1, API_RETRY_COUNT
|
||||
)
|
||||
if attempt < API_RETRY_COUNT - 1:
|
||||
retry_after = self._parse_retry_after(
|
||||
response.headers.get("Retry-After")
|
||||
)
|
||||
await asyncio.sleep(retry_after or (2 ** attempt))
|
||||
continue
|
||||
raise HomeAssistantError("API rate limit exceeded")
|
||||
|
||||
# Upstream transient errors — retry with backoff
|
||||
if response.status in retryable_5xx:
|
||||
_LOGGER.warning(
|
||||
"Upstream %d on attempt %d/%d",
|
||||
response.status, attempt + 1, API_RETRY_COUNT,
|
||||
)
|
||||
if attempt < API_RETRY_COUNT - 1:
|
||||
await asyncio.sleep(2 ** attempt)
|
||||
continue
|
||||
raise HomeAssistantError(
|
||||
f"Upstream error after retries: status {response.status}"
|
||||
)
|
||||
|
||||
# Other client/server errors — don't retry
|
||||
truncated_error = str(error_data)[:512]
|
||||
_LOGGER.error("API error (status %d): %s", response.status, truncated_error)
|
||||
raise HomeAssistantError(f"API error: status {response.status}")
|
||||
|
||||
except asyncio.TimeoutError as err:
|
||||
_LOGGER.warning("Timeout on attempt %d/%d", attempt + 1, API_RETRY_COUNT)
|
||||
if attempt == API_RETRY_COUNT - 1:
|
||||
raise HomeAssistantError("API request timed out")
|
||||
await asyncio.sleep(1 * (attempt + 1))
|
||||
raise HomeAssistantError("API request timed out") from err
|
||||
await asyncio.sleep(2 ** attempt)
|
||||
except HomeAssistantError:
|
||||
raise
|
||||
except Exception as e:
|
||||
_LOGGER.warning(f"API request failed on attempt {attempt + 1}: {str(e)}")
|
||||
_LOGGER.warning(
|
||||
"API request failed on attempt %d/%d: %s",
|
||||
attempt + 1, API_RETRY_COUNT, type(e).__name__,
|
||||
)
|
||||
if attempt == API_RETRY_COUNT - 1:
|
||||
raise
|
||||
await asyncio.sleep(1 * (attempt + 1))
|
||||
await asyncio.sleep(2 ** attempt)
|
||||
|
||||
raise HomeAssistantError("API request failed after all retries")
|
||||
|
||||
@staticmethod
|
||||
def _parse_retry_after(value: str | None) -> float | None:
|
||||
"""Parse Retry-After header (seconds). Caps at 60s to avoid long stalls."""
|
||||
if not value:
|
||||
return None
|
||||
try:
|
||||
seconds = float(value.strip())
|
||||
except (ValueError, AttributeError):
|
||||
return None
|
||||
if seconds <= 0:
|
||||
return None
|
||||
return min(seconds, 60.0)
|
||||
|
||||
async def create(
|
||||
self,
|
||||
model: str,
|
||||
messages: List[Dict[str, str]],
|
||||
messages: list[dict[str, str]],
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
) -> Dict[str, Any]:
|
||||
structured_output: bool = False,
|
||||
json_schema: str | None = None,
|
||||
disable_thinking: bool = False,
|
||||
) -> 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
|
||||
model, messages, temperature, max_tokens,
|
||||
structured_output, json_schema, disable_thinking
|
||||
)
|
||||
elif self.api_provider == API_PROVIDER_DEEPSEEK:
|
||||
return await self._create_deepseek_completion(
|
||||
model, messages, temperature, max_tokens,
|
||||
structured_output, json_schema, disable_thinking
|
||||
)
|
||||
elif self.api_provider == API_PROVIDER_GEMINI:
|
||||
return await self._create_gemini_completion(
|
||||
model, messages, temperature, max_tokens,
|
||||
structured_output, json_schema, disable_thinking
|
||||
)
|
||||
else:
|
||||
return await self._create_openai_completion(
|
||||
model, messages, temperature, max_tokens
|
||||
model, messages, temperature, max_tokens,
|
||||
structured_output, json_schema, disable_thinking
|
||||
)
|
||||
except (KeyError, IndexError) as e:
|
||||
if "'choices'" in str(e) or "'message'" in str(e):
|
||||
raise HomeAssistantError("Failed to get a response from the AI model. Please check your internet connection and try again later.")
|
||||
else:
|
||||
raise
|
||||
except Exception as e:
|
||||
_LOGGER.error("API request failed: %s", str(e))
|
||||
raise HomeAssistantError(f"API request failed: {str(e)}")
|
||||
raise HomeAssistantError(f"API request failed: {str(e)}") from e
|
||||
|
||||
# Non-reasoning variants whose names otherwise overlap with the
|
||||
# reasoning prefix set (e.g. "gpt-5-chat-latest" is classic chat).
|
||||
_OPENAI_NON_REASONING_PATTERNS: tuple[str, ...] = ("gpt-5-chat",)
|
||||
_OPENAI_REASONING_REGEX = re.compile(
|
||||
r"^(?:o\d+|gpt-[5-9](?:\.\d+)?)(?:[-_].*)?$"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def _is_openai_reasoning_model(cls, model: str) -> bool:
|
||||
"""Detect OpenAI reasoning models (o-series and GPT-5+ family).
|
||||
|
||||
Reasoning models require max_completion_tokens (not max_tokens),
|
||||
do not accept custom temperature, and use "developer" role instead
|
||||
of "system". Uses a regex so future o5/gpt-6 releases are caught
|
||||
without code change. Explicitly excludes chat-variants
|
||||
(e.g. gpt-5-chat-latest) which are classic chat models.
|
||||
"""
|
||||
if not model:
|
||||
return False
|
||||
m = model.strip().lower()
|
||||
# OpenRouter-style "openai/o3" prefix — strip provider namespace.
|
||||
if "/" in m:
|
||||
m = m.rsplit("/", 1)[-1]
|
||||
for non_reasoning in cls._OPENAI_NON_REASONING_PATTERNS:
|
||||
if m.startswith(non_reasoning):
|
||||
return False
|
||||
return bool(cls._OPENAI_REASONING_REGEX.match(m))
|
||||
|
||||
@staticmethod
|
||||
def _convert_system_to_developer(
|
||||
messages: list[dict[str, str]],
|
||||
) -> list[dict[str, str]]:
|
||||
"""Rename role "system" to "developer" for OpenAI reasoning models."""
|
||||
return [
|
||||
{**m, "role": "developer"} if m.get("role") == "system" else m
|
||||
for m in messages
|
||||
]
|
||||
|
||||
# Matches /no_think only as a standalone soft-switch token (word-bounded),
|
||||
# not when users discuss the concept ("discuss /no_think semantics").
|
||||
_NO_THINK_TOKEN_RE = re.compile(r"(?:^|\s)/no_think(?:\s|$)")
|
||||
|
||||
@classmethod
|
||||
def _apply_no_think_tag(
|
||||
cls,
|
||||
messages: list[dict[str, str]],
|
||||
) -> list[dict[str, str]]:
|
||||
"""Append Qwen-style /no_think soft switch to the last user message.
|
||||
|
||||
Why: Qwen3 reasoning models treat "/no_think" in the last user turn as a
|
||||
request to skip thinking. Non-Qwen models ignore the trailing token
|
||||
harmlessly, so this is safe to apply to all OpenAI-compatible backends.
|
||||
Uses word-boundary regex for dedup so that user content mentioning
|
||||
"/no_think" mid-sentence isn't mistaken for an existing soft switch.
|
||||
"""
|
||||
if not messages:
|
||||
return messages
|
||||
patched = [m.copy() for m in messages]
|
||||
for i in range(len(patched) - 1, -1, -1):
|
||||
if patched[i].get("role") == "user":
|
||||
content = patched[i].get("content", "")
|
||||
if not cls._NO_THINK_TOKEN_RE.search(content):
|
||||
patched[i]["content"] = f"{content.rstrip()} /no_think".lstrip()
|
||||
break
|
||||
return patched
|
||||
|
||||
@staticmethod
|
||||
def _strip_think_blocks(text: str) -> str:
|
||||
"""Remove <think>...</think> reasoning blocks from model output.
|
||||
|
||||
Why: Some reasoning models (DeepSeek-R1, Qwen-Thinking) emit chain-of-thought
|
||||
wrapped in <think> tags even when thinking is nominally disabled. Strip them
|
||||
so the final answer stays clean. Handles nested blocks via iterative
|
||||
replacement, and drops dangling opening tags when a response is
|
||||
truncated mid-block.
|
||||
"""
|
||||
if not text or "<think>" not in text:
|
||||
return text
|
||||
pattern = re.compile(r"<think>.*?</think>", flags=re.DOTALL)
|
||||
cleaned = text
|
||||
# Iterative pass: each iteration peels one layer of nested tags.
|
||||
# Bounded to 10 iterations to avoid pathological inputs.
|
||||
for _ in range(10):
|
||||
new = pattern.sub("", cleaned)
|
||||
if new == cleaned:
|
||||
break
|
||||
cleaned = new
|
||||
# If a truncated response left a dangling <think> open, drop the rest
|
||||
# from that marker onward to avoid leaking partial reasoning.
|
||||
if "<think>" in cleaned:
|
||||
cleaned = cleaned.split("<think>", 1)[0]
|
||||
return cleaned.strip()
|
||||
|
||||
@staticmethod
|
||||
def _apply_structured_output(
|
||||
payload: dict[str, Any],
|
||||
structured_output: bool,
|
||||
json_schema: str | None,
|
||||
) -> None:
|
||||
"""Apply OpenAI-compatible structured output to payload in-place."""
|
||||
if not (structured_output and json_schema):
|
||||
return
|
||||
try:
|
||||
schema = json.loads(json_schema)
|
||||
payload["response_format"] = {
|
||||
"type": "json_schema",
|
||||
"json_schema": {
|
||||
"name": "structured_response",
|
||||
"strict": True,
|
||||
"schema": schema,
|
||||
},
|
||||
}
|
||||
except json.JSONDecodeError as e:
|
||||
_LOGGER.warning("Invalid JSON schema: %s. Falling back to json_object.", e)
|
||||
payload["response_format"] = {"type": "json_object"}
|
||||
|
||||
async def _create_deepseek_completion(
|
||||
self,
|
||||
model: str,
|
||||
messages: list[dict[str, str]],
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
structured_output: bool = False,
|
||||
json_schema: str | None = None,
|
||||
disable_thinking: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Create completion using DeepSeek API.
|
||||
|
||||
DeepSeek-reasoner (R1) is a reasoning model: it ignores /no_think
|
||||
(thinking is always on by design) and emits reasoning_content as a
|
||||
separate field alongside content. We skip the no_think append for
|
||||
this model and preserve reasoning_content in the response payload
|
||||
so it's available for logging/debug.
|
||||
|
||||
DeepSeek V4+ (deepseek-v4-flash/-pro) selects thinking mode via a
|
||||
top-level "thinking" request parameter instead of the model name,
|
||||
so /no_think does not apply there.
|
||||
"""
|
||||
url = f"{self.endpoint}/chat/completions"
|
||||
m_lower = model.lower()
|
||||
is_reasoner = "reasoner" in m_lower
|
||||
is_v4plus = re.search(r"deepseek-v[4-9]", m_lower) is not None
|
||||
final_messages = (
|
||||
self._apply_no_think_tag(messages)
|
||||
if (disable_thinking and not is_reasoner and not is_v4plus)
|
||||
else messages
|
||||
)
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": final_messages,
|
||||
"temperature": temperature,
|
||||
"max_tokens": max_tokens,
|
||||
"stream": False,
|
||||
}
|
||||
if disable_thinking and is_v4plus:
|
||||
payload["thinking"] = {"type": "disabled"}
|
||||
self._apply_structured_output(payload, structured_output, json_schema)
|
||||
|
||||
data = await self._make_request(url, payload)
|
||||
message = data["choices"][0]["message"]
|
||||
content = message.get("content", "")
|
||||
reasoning = message.get("reasoning_content")
|
||||
if disable_thinking and not is_reasoner:
|
||||
content = self._strip_think_blocks(content)
|
||||
return {
|
||||
"choices": [
|
||||
{
|
||||
"message": {
|
||||
"content": content,
|
||||
**({"reasoning_content": reasoning} if reasoning else {}),
|
||||
},
|
||||
}
|
||||
],
|
||||
"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]],
|
||||
messages: list[dict[str, str]],
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
) -> Dict[str, Any]:
|
||||
"""Create completion using OpenAI API."""
|
||||
structured_output: bool = False,
|
||||
json_schema: str | None = None,
|
||||
disable_thinking: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Create completion using OpenAI API.
|
||||
|
||||
Reasoning models (o-series, gpt-5 family) require a different payload
|
||||
shape: max_completion_tokens instead of max_tokens, no custom
|
||||
temperature, and role "developer" instead of "system". When
|
||||
disable_thinking=True for a reasoning model we set reasoning_effort
|
||||
to "low" to minimize hidden CoT tokens. For classic chat models the
|
||||
Qwen-style /no_think soft switch is appended instead.
|
||||
"""
|
||||
url = f"{self.endpoint}/chat/completions"
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
"temperature": temperature,
|
||||
"max_tokens": max_tokens,
|
||||
}
|
||||
is_reasoning = self._is_openai_reasoning_model(model)
|
||||
|
||||
if is_reasoning:
|
||||
prepared_messages = self._convert_system_to_developer(messages)
|
||||
payload: dict[str, Any] = {
|
||||
"model": model,
|
||||
"messages": prepared_messages,
|
||||
"max_completion_tokens": max_tokens,
|
||||
}
|
||||
if disable_thinking:
|
||||
# gpt-5+ supports "minimal" (cheapest, lowest-CoT). o-series
|
||||
# rejects "minimal" and accepts low/medium/high — fall back to "low".
|
||||
effort = "minimal" if model.lower().startswith(("gpt-5", "gpt5")) else "low"
|
||||
payload["reasoning_effort"] = effort
|
||||
else:
|
||||
prepared_messages = (
|
||||
self._apply_no_think_tag(messages) if disable_thinking else messages
|
||||
)
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": prepared_messages,
|
||||
"temperature": temperature,
|
||||
"max_tokens": max_tokens,
|
||||
}
|
||||
self._apply_structured_output(payload, structured_output, json_schema)
|
||||
|
||||
data = await self._make_request(url, payload)
|
||||
content = data["choices"][0]["message"]["content"]
|
||||
# Strip <think> blocks only for classic chat models. Reasoning models
|
||||
# never emit the tags in user-facing content.
|
||||
if disable_thinking and not is_reasoning:
|
||||
content = self._strip_think_blocks(content)
|
||||
return {
|
||||
"choices": [
|
||||
{
|
||||
"message": {"content": data["choices"][0]["message"]["content"]},
|
||||
"message": {"content": content},
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
@@ -155,10 +476,13 @@ class APIClient:
|
||||
async def _create_anthropic_completion(
|
||||
self,
|
||||
model: str,
|
||||
messages: List[Dict[str, str]],
|
||||
messages: list[dict[str, str]],
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
) -> Dict[str, Any]:
|
||||
structured_output: bool = False,
|
||||
json_schema: str | None = None,
|
||||
disable_thinking: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""Create completion using Anthropic API."""
|
||||
url = f"{self.endpoint}/v1/messages"
|
||||
|
||||
@@ -173,21 +497,56 @@ class APIClient:
|
||||
else:
|
||||
filtered_messages.append(msg)
|
||||
|
||||
# For Anthropic, add structured output instruction to system prompt.
|
||||
# Validate schema is well-formed JSON before concatenation: untrusted
|
||||
# schema strings (built from templates/webhook data) could otherwise
|
||||
# break out of the JSON fence and rewrite the system instruction.
|
||||
if structured_output and json_schema:
|
||||
try:
|
||||
json.loads(json_schema)
|
||||
except json.JSONDecodeError as err:
|
||||
_LOGGER.warning(
|
||||
"Anthropic: invalid JSON schema, ignoring structured_output: %s", err
|
||||
)
|
||||
else:
|
||||
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")
|
||||
|
||||
# Anthropic accepts temperature in [0, 1], not [0, 2] like OpenAI.
|
||||
# Clip silently to avoid a 400 when a user-set config exceeds the cap.
|
||||
clipped_temp = min(1.0, max(0.0, float(temperature)))
|
||||
payload = {
|
||||
"model": model,
|
||||
"messages": filtered_messages,
|
||||
"max_tokens": max_tokens,
|
||||
"temperature": temperature,
|
||||
"temperature": clipped_temp,
|
||||
}
|
||||
|
||||
if system_prompt:
|
||||
payload["system"] = system_prompt
|
||||
|
||||
data = await self._make_request(url, payload)
|
||||
# Anthropic returns an array of content blocks; if extended thinking
|
||||
# is ever enabled the first block may be type="thinking". Find the
|
||||
# first text-type block instead of hardcoding index [0].
|
||||
content = ""
|
||||
for block in data.get("content", []):
|
||||
if block.get("type") == "text":
|
||||
content = block.get("text", "")
|
||||
break
|
||||
return {
|
||||
"choices": [
|
||||
{
|
||||
"message": {"content": data["content"][0]["text"]},
|
||||
"message": {"content": content},
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
@@ -197,16 +556,212 @@ class APIClient:
|
||||
},
|
||||
}
|
||||
|
||||
async def check_connection(self) -> bool:
|
||||
"""Check API connection."""
|
||||
async def _create_gemini_completion(
|
||||
self,
|
||||
model: str,
|
||||
messages: list[dict[str, str]],
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
structured_output: bool = False,
|
||||
json_schema: str | None = None,
|
||||
disable_thinking: bool = False,
|
||||
) -> 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:
|
||||
await self._make_request(self.endpoint, {"test": "connection"})
|
||||
return True
|
||||
def import_genai():
|
||||
from google import genai
|
||||
return genai
|
||||
|
||||
genai = await asyncio.to_thread(import_genai)
|
||||
|
||||
api_key = self._api_key
|
||||
|
||||
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:
|
||||
parsed_schema = json.loads(json_schema)
|
||||
_LOGGER.debug("Gemini structured output enabled with schema")
|
||||
except json.JSONDecodeError as e:
|
||||
_LOGGER.warning("Invalid JSON schema provided: %s. Structured output disabled.", e)
|
||||
|
||||
# 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
|
||||
|
||||
# Disable thinking. Gemini 3.x+ replaced the numeric
|
||||
# thinking_budget with a semantic thinking_level; Pro
|
||||
# variants do not accept MINIMAL, their floor is LOW.
|
||||
# Gemini 2.5: Flash accepts thinking_budget=0 (fully off),
|
||||
# Pro rejects 0 and requires at least 128 tokens.
|
||||
# 2.0 and earlier ignore the field.
|
||||
if disable_thinking:
|
||||
m_lower = model.lower()
|
||||
try:
|
||||
if re.search(r"gemini-[3-9]", m_lower):
|
||||
level = "LOW" if "pro" in m_lower else "MINIMAL"
|
||||
config.thinking_config = types.ThinkingConfig(
|
||||
thinking_level=level
|
||||
)
|
||||
else:
|
||||
budget = 128 if "2.5-pro" in m_lower else 0
|
||||
config.thinking_config = types.ThinkingConfig(
|
||||
thinking_budget=budget
|
||||
)
|
||||
except (AttributeError, TypeError, ValueError) as err:
|
||||
_LOGGER.debug(
|
||||
"ThinkingConfig not supported by this google-genai version: %s", err
|
||||
)
|
||||
|
||||
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 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, pass history to chat
|
||||
# and only send the last user message
|
||||
last_user_msg = None
|
||||
history = []
|
||||
|
||||
# Find the last user message — that's the new query
|
||||
for i in range(len(contents) - 1, -1, -1):
|
||||
if contents[i]["role"] == "user":
|
||||
last_user_msg = contents[i]["parts"][0]["text"]
|
||||
history = contents[:i]
|
||||
break
|
||||
|
||||
if last_user_msg is None:
|
||||
# No user messages at all — shouldn't happen, but handle gracefully
|
||||
return client.models.generate_content(
|
||||
model=model,
|
||||
contents="I need your assistance.",
|
||||
config=config
|
||||
)
|
||||
|
||||
chat = client.chats.create(
|
||||
model=model, config=config, history=history
|
||||
)
|
||||
return chat.send_message(last_user_msg)
|
||||
|
||||
# Gemini uses sync SDK via to_thread, so needs its own timeout
|
||||
# (aiohttp ClientTimeout doesn't apply here)
|
||||
async with asyncio.timeout(self.api_timeout):
|
||||
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)
|
||||
|
||||
if disable_thinking:
|
||||
response_text = self._strip_think_blocks(response_text)
|
||||
|
||||
return {
|
||||
"choices": [{
|
||||
"message": {
|
||||
"content": response_text
|
||||
}
|
||||
}],
|
||||
"usage": usage
|
||||
}
|
||||
|
||||
except ImportError as e:
|
||||
_LOGGER.error("Google Gemini library not installed: %s", e)
|
||||
raise HomeAssistantError(
|
||||
"Missing dependency: google-genai. Please install it."
|
||||
) from e
|
||||
except Exception as e:
|
||||
_LOGGER.error(f"Connection check failed: {str(e)}")
|
||||
return False
|
||||
_LOGGER.error("Gemini API error: %s", e)
|
||||
raise HomeAssistantError(f"Gemini API request failed: {e}") from e
|
||||
|
||||
async def shutdown(self) -> None:
|
||||
"""Shutdown API client."""
|
||||
"""Shutdown API client and close its dedicated session."""
|
||||
_LOGGER.debug("Shutting down API client")
|
||||
await self.session.close()
|
||||
self._closed = True
|
||||
# The session is dedicated to this config entry (pinned resolver,
|
||||
# isolated cookie jar), so it must be closed here to release the
|
||||
# connector; nothing else owns it.
|
||||
if self.session is not None and not self.session.closed:
|
||||
await self.session.close()
|
||||
|
||||
@@ -1,20 +1,21 @@
|
||||
"""
|
||||
Config flow for HA text AI integration.
|
||||
|
||||
@license: CC BY-NC-SA 4.0 International
|
||||
@license: MIT (https://opensource.org/licenses/MIT)
|
||||
@author: SMKRV
|
||||
@github: https://github.com/smkrv/ha-text-ai
|
||||
@source: https://github.com/smkrv/ha-text-ai
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any
|
||||
|
||||
import voluptuous as vol
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.const import CONF_API_KEY, CONF_NAME
|
||||
from homeassistant.core import callback
|
||||
from homeassistant.data_entry_flow import FlowResult
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
from homeassistant.config_entries import ConfigFlowResult
|
||||
from homeassistant.helpers import selector
|
||||
|
||||
from .const import (
|
||||
@@ -24,37 +25,83 @@ from .const import (
|
||||
CONF_MAX_TOKENS,
|
||||
CONF_API_ENDPOINT,
|
||||
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_TEMPERATURE,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
DEFAULT_REQUEST_INTERVAL,
|
||||
DEFAULT_OPENAI_ENDPOINT,
|
||||
DEFAULT_ANTHROPIC_ENDPOINT,
|
||||
DEFAULT_API_TIMEOUT,
|
||||
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_INSTANCE_NAME,
|
||||
DEFAULT_MAX_HISTORY,
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
MIN_CONTEXT_MESSAGES,
|
||||
MAX_CONTEXT_MESSAGES,
|
||||
MIN_HISTORY_SIZE,
|
||||
MAX_HISTORY_SIZE,
|
||||
CONF_ALLOW_LOCAL_NETWORK,
|
||||
DEFAULT_ALLOW_LOCAL_NETWORK,
|
||||
CONF_DISABLE_THINKING,
|
||||
DEFAULT_DISABLE_THINKING,
|
||||
)
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from .utils import (
|
||||
create_pinned_session,
|
||||
normalize_name,
|
||||
safe_log_data,
|
||||
validate_endpoint,
|
||||
)
|
||||
from .providers import get_default_endpoint, get_default_model, build_auth_headers
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def normalize_name(name: str) -> str:
|
||||
"""Normalize name to conform to HA naming convention using underscores."""
|
||||
normalized = ''.join(c if c.isalnum() or c == '_' else '_' for c in name)
|
||||
normalized = '_'.join(filter(None, normalized.split('_')))
|
||||
return normalized.lower()
|
||||
|
||||
def _build_parameter_schema(data: dict[str, Any]) -> dict:
|
||||
"""Build shared parameter schema fields used by both ConfigFlow and OptionsFlow."""
|
||||
return {
|
||||
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=MIN_CONTEXT_MESSAGES, max=MAX_CONTEXT_MESSAGES)),
|
||||
vol.Optional(
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
default=data.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY),
|
||||
): vol.All(vol.Coerce(int), vol.Range(min=MIN_HISTORY_SIZE, max=MAX_HISTORY_SIZE)),
|
||||
vol.Optional(
|
||||
CONF_DISABLE_THINKING,
|
||||
default=data.get(CONF_DISABLE_THINKING, DEFAULT_DISABLE_THINKING),
|
||||
): bool,
|
||||
}
|
||||
|
||||
class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
"""Handle a config flow for HA text AI."""
|
||||
@@ -67,7 +114,7 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
self._data = {}
|
||||
self._provider = None
|
||||
|
||||
async def async_step_user(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
||||
async def async_step_user(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
|
||||
"""Handle the initial step."""
|
||||
if user_input is None:
|
||||
return self.async_show_form(
|
||||
@@ -85,70 +132,63 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
self._provider = user_input[CONF_API_PROVIDER]
|
||||
return await self.async_step_provider()
|
||||
|
||||
async def async_step_provider(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
||||
def _build_provider_schema(
|
||||
self, data: dict[str, Any] | None = None
|
||||
) -> vol.Schema:
|
||||
"""Build provider configuration schema with optional defaults from data."""
|
||||
defaults = data or {}
|
||||
schema_dict = {
|
||||
vol.Required(CONF_NAME, default=defaults.get(CONF_NAME, DEFAULT_INSTANCE_NAME)): str,
|
||||
vol.Required(CONF_API_KEY): selector.TextSelector(
|
||||
selector.TextSelectorConfig(type=selector.TextSelectorType.PASSWORD)
|
||||
),
|
||||
vol.Required(CONF_MODEL, default=defaults.get(CONF_MODEL, get_default_model(self._provider))): str,
|
||||
vol.Required(CONF_API_ENDPOINT, default=defaults.get(CONF_API_ENDPOINT, get_default_endpoint(self._provider))): str,
|
||||
vol.Optional(
|
||||
CONF_ALLOW_LOCAL_NETWORK,
|
||||
default=defaults.get(CONF_ALLOW_LOCAL_NETWORK, DEFAULT_ALLOW_LOCAL_NETWORK),
|
||||
): bool,
|
||||
}
|
||||
schema_dict.update(_build_parameter_schema(defaults))
|
||||
return vol.Schema(schema_dict)
|
||||
|
||||
async def async_step_provider(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
|
||||
"""Handle provider configuration step."""
|
||||
self._errors = {}
|
||||
|
||||
if user_input is None:
|
||||
default_endpoint = (
|
||||
DEFAULT_OPENAI_ENDPOINT if self._provider == API_PROVIDER_OPENAI
|
||||
else DEFAULT_ANTHROPIC_ENDPOINT
|
||||
)
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="provider",
|
||||
data_schema=vol.Schema({
|
||||
vol.Required(CONF_NAME, default="my_assistant"): str,
|
||||
vol.Required(CONF_API_KEY): str,
|
||||
vol.Required(CONF_MODEL, default=DEFAULT_MODEL): str,
|
||||
vol.Required(CONF_API_ENDPOINT, default=default_endpoint): str,
|
||||
vol.Optional(CONF_TEMPERATURE, default=DEFAULT_TEMPERATURE): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
||||
),
|
||||
vol.Optional(CONF_MAX_TOKENS, default=DEFAULT_MAX_TOKENS): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
|
||||
),
|
||||
vol.Optional(CONF_REQUEST_INTERVAL, default=DEFAULT_REQUEST_INTERVAL): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
default=DEFAULT_CONTEXT_MESSAGES
|
||||
): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=20)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
default=DEFAULT_MAX_HISTORY
|
||||
): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=100)
|
||||
),
|
||||
})
|
||||
data_schema=self._build_provider_schema(),
|
||||
)
|
||||
|
||||
_LOGGER.debug("Provider step input data: %s", safe_log_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("Missing name in configuration input: %s", safe_log_data(input_copy))
|
||||
input_copy[CONF_NAME] = f"assistant_{dt_util.utcnow().strftime('%Y%m%d_%H%M%S')}"
|
||||
_LOGGER.info("Auto-generated name: %s", 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=self._build_provider_schema(input_copy),
|
||||
errors=self._errors
|
||||
)
|
||||
|
||||
try:
|
||||
normalized_name = self._validate_and_normalize_name(input_copy[CONF_NAME])
|
||||
input_copy[CONF_NAME] = normalized_name
|
||||
except ValueError as e:
|
||||
return self.async_show_form(
|
||||
step_id="provider",
|
||||
data_schema=vol.Schema({
|
||||
vol.Required(CONF_NAME, default=input_copy[CONF_NAME]): str,
|
||||
vol.Required(CONF_API_KEY, default=input_copy[CONF_API_KEY]): str,
|
||||
vol.Required(CONF_MODEL, default=input_copy[CONF_MODEL]): str,
|
||||
vol.Required(CONF_API_ENDPOINT, default=input_copy[CONF_API_ENDPOINT]): str,
|
||||
vol.Optional(CONF_TEMPERATURE, default=input_copy.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
||||
),
|
||||
}),
|
||||
data_schema=self._build_provider_schema(input_copy),
|
||||
errors={"name": str(e)}
|
||||
)
|
||||
|
||||
@@ -156,120 +196,121 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
if not await self._async_validate_api(input_copy):
|
||||
return self.async_show_form(
|
||||
step_id="provider",
|
||||
data_schema=vol.Schema({
|
||||
}),
|
||||
data_schema=self._build_provider_schema(input_copy),
|
||||
errors=self._errors
|
||||
)
|
||||
except Exception as e:
|
||||
except Exception:
|
||||
_LOGGER.exception("Unexpected error during API validation")
|
||||
return self.async_show_form(
|
||||
step_id="provider",
|
||||
data_schema=vol.Schema({
|
||||
}),
|
||||
errors={"base": str(e)}
|
||||
data_schema=self._build_provider_schema(input_copy),
|
||||
errors={"base": "unknown"}
|
||||
)
|
||||
|
||||
return await self._create_entry(input_copy)
|
||||
|
||||
def _validate_and_normalize_name(self, name: str) -> str:
|
||||
"""
|
||||
Validate and normalize name with detailed error handling.
|
||||
"""Validate and normalize name.
|
||||
|
||||
Truncates before uniqueness check to prevent collisions.
|
||||
|
||||
Raises:
|
||||
ValueError: If name is invalid
|
||||
|
||||
Returns:
|
||||
Normalized name
|
||||
ValueError: If name is invalid or already exists.
|
||||
"""
|
||||
if not name:
|
||||
if not name or not name.strip():
|
||||
raise ValueError("empty")
|
||||
|
||||
name = name.strip()
|
||||
normalized = ''.join(
|
||||
c if c.isalnum() or c in ' _' else '_' # Only allow underscores
|
||||
for c in name
|
||||
)
|
||||
normalized = normalize_name(name.strip())[:50]
|
||||
|
||||
normalized = normalized.replace(' ', '_').lower()
|
||||
if not normalized:
|
||||
raise ValueError("empty")
|
||||
|
||||
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."""
|
||||
async def _async_validate_api(self, user_input: dict[str, Any]) -> bool:
|
||||
"""Validate API connection using provider registry."""
|
||||
try:
|
||||
session = async_get_clientsession(self.hass)
|
||||
headers = self._get_api_headers(user_input)
|
||||
endpoint = user_input[CONF_API_ENDPOINT].rstrip('/')
|
||||
if CONF_API_KEY not in user_input:
|
||||
_LOGGER.error("API validation error: 'api_key'")
|
||||
self._errors["base"] = "invalid_auth"
|
||||
return False
|
||||
|
||||
check_url = (
|
||||
f"{endpoint}/v1/models" if self._provider == API_PROVIDER_ANTHROPIC
|
||||
else f"{endpoint}/models"
|
||||
)
|
||||
try:
|
||||
allow_local = user_input.get(CONF_ALLOW_LOCAL_NETWORK, DEFAULT_ALLOW_LOCAL_NETWORK)
|
||||
endpoint, resolved_ips = await validate_endpoint(
|
||||
self.hass, user_input[CONF_API_ENDPOINT], allow_local=allow_local
|
||||
)
|
||||
except ValueError as err:
|
||||
_LOGGER.error("Endpoint validation failed: %s", err)
|
||||
self._errors["base"] = "cannot_connect"
|
||||
return False
|
||||
|
||||
async with session.get(check_url, headers=headers) as response:
|
||||
if response.status == 401:
|
||||
if self._provider == API_PROVIDER_GEMINI:
|
||||
if not user_input[CONF_API_KEY]:
|
||||
self._errors["base"] = "invalid_auth"
|
||||
return False
|
||||
elif response.status not in [200, 404]:
|
||||
self._errors["base"] = "cannot_connect"
|
||||
return False
|
||||
return True
|
||||
|
||||
headers = build_auth_headers(self._provider, user_input[CONF_API_KEY])
|
||||
|
||||
from .providers import get_provider_config
|
||||
check_path = get_provider_config(self._provider).get("check_path", "/models")
|
||||
check_url = f"{endpoint}{check_path}"
|
||||
|
||||
# Pinned session ensures the reachability check goes to the same
|
||||
# IP that will later be used by api_client (no DNS rebinding).
|
||||
session = create_pinned_session(endpoint, resolved_ips)
|
||||
try:
|
||||
async with session.get(
|
||||
check_url, headers=headers, allow_redirects=False
|
||||
) as response:
|
||||
if response.status == 401:
|
||||
self._errors["base"] = "invalid_auth"
|
||||
return False
|
||||
elif response.status != 200:
|
||||
self._errors["base"] = "cannot_connect"
|
||||
return False
|
||||
return True
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.error("API validation error: %s", str(err))
|
||||
self._errors["base"] = "cannot_connect"
|
||||
return False
|
||||
|
||||
def _get_api_headers(self, user_input: Dict[str, Any]) -> Dict[str, str]:
|
||||
"""Get API headers based on provider."""
|
||||
api_key = user_input[CONF_API_KEY]
|
||||
|
||||
if self._provider == API_PROVIDER_ANTHROPIC:
|
||||
return {
|
||||
"x-api-key": api_key,
|
||||
"anthropic-version": "2023-06-01",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
return {
|
||||
"Authorization": f"Bearer {api_key}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
async def _create_entry(self, user_input: Dict[str, Any]) -> FlowResult:
|
||||
"""Create the config entry with comprehensive data preservation."""
|
||||
async def _create_entry(self, user_input: dict[str, Any]) -> ConfigFlowResult:
|
||||
"""Create the config entry with unique_id deduplication."""
|
||||
instance_name = user_input[CONF_NAME]
|
||||
normalized_name = normalize_name(instance_name)
|
||||
|
||||
unique_id = f"{DOMAIN}_{normalized_name}_{self._provider}".lower()
|
||||
unique_id = f"{DOMAIN}_{normalized_name}_{self._provider}"
|
||||
await self.async_set_unique_id(unique_id)
|
||||
self._abort_if_unique_id_configured()
|
||||
|
||||
default_model = get_default_model(self._provider)
|
||||
|
||||
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_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),
|
||||
CONF_ALLOW_LOCAL_NETWORK: user_input.get(CONF_ALLOW_LOCAL_NETWORK, DEFAULT_ALLOW_LOCAL_NETWORK),
|
||||
CONF_DISABLE_THINKING: user_input.get(CONF_DISABLE_THINKING, DEFAULT_DISABLE_THINKING),
|
||||
}
|
||||
|
||||
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}")
|
||||
_LOGGER.debug("Creating config entry with data: %s", safe_log_data(entry_data))
|
||||
|
||||
return self.async_create_entry(
|
||||
title=instance_name,
|
||||
@@ -280,70 +321,201 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||
@callback
|
||||
def async_get_options_flow(config_entry: config_entries.ConfigEntry) -> config_entries.OptionsFlow:
|
||||
"""Get the options flow for this handler."""
|
||||
return OptionsFlowHandler(config_entry)
|
||||
|
||||
return OptionsFlowHandler()
|
||||
|
||||
class OptionsFlowHandler(config_entries.OptionsFlow):
|
||||
"""Handle options flow."""
|
||||
|
||||
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
|
||||
"""Initialize options flow."""
|
||||
self.config_entry = config_entry
|
||||
async def _async_validate_api(self, provider: str, api_key: str, endpoint: str, *, allow_local: bool = False) -> bool:
|
||||
"""Validate API connection using provider registry."""
|
||||
try:
|
||||
if not api_key:
|
||||
self._errors["base"] = "invalid_auth"
|
||||
return False
|
||||
|
||||
async def async_step_init(self, user_input: Optional[Dict[str, Any]] = None) -> FlowResult:
|
||||
"""Manage the options."""
|
||||
if user_input is not None:
|
||||
return self.async_create_entry(title="", data=user_input)
|
||||
try:
|
||||
endpoint, resolved_ips = await validate_endpoint(
|
||||
self.hass, endpoint, allow_local=allow_local
|
||||
)
|
||||
except ValueError as err:
|
||||
_LOGGER.error("Endpoint validation failed: %s", err)
|
||||
self._errors["base"] = "cannot_connect"
|
||||
return False
|
||||
|
||||
if provider == API_PROVIDER_GEMINI:
|
||||
return True
|
||||
|
||||
headers = build_auth_headers(provider, api_key)
|
||||
|
||||
from .providers import get_provider_config
|
||||
check_path = get_provider_config(provider).get("check_path", "/models")
|
||||
check_url = f"{endpoint}{check_path}"
|
||||
|
||||
session = create_pinned_session(endpoint, resolved_ips)
|
||||
try:
|
||||
async with session.get(
|
||||
check_url, headers=headers, allow_redirects=False
|
||||
) as response:
|
||||
if response.status == 401:
|
||||
self._errors["base"] = "invalid_auth"
|
||||
return False
|
||||
elif response.status != 200:
|
||||
self._errors["base"] = "cannot_connect"
|
||||
return False
|
||||
return True
|
||||
finally:
|
||||
await session.close()
|
||||
|
||||
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: dict[str, Any] | None = None) -> ConfigFlowResult:
|
||||
"""Handle provider selection step."""
|
||||
if not hasattr(self, "_errors"):
|
||||
self._errors: dict[str, str] = {}
|
||||
self._selected_provider: str | None = None
|
||||
current_data = {**self.config_entry.data, **self.config_entry.options}
|
||||
current_provider = current_data.get(CONF_API_PROVIDER, API_PROVIDER_OPENAI)
|
||||
|
||||
if user_input is not None:
|
||||
self._selected_provider = user_input.get(CONF_API_PROVIDER, current_provider)
|
||||
return await self.async_step_settings()
|
||||
|
||||
return self.async_show_form(
|
||||
step_id="init",
|
||||
data_schema=vol.Schema({
|
||||
vol.Optional(
|
||||
CONF_MODEL,
|
||||
default=current_data.get(CONF_MODEL, DEFAULT_MODEL)
|
||||
): str,
|
||||
vol.Optional(
|
||||
CONF_TEMPERATURE,
|
||||
default=current_data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
||||
): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_MAX_TOKENS,
|
||||
default=current_data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
||||
): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_REQUEST_INTERVAL,
|
||||
default=current_data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
||||
): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
default=current_data.get(
|
||||
CONF_CONTEXT_MESSAGES,
|
||||
DEFAULT_CONTEXT_MESSAGES
|
||||
vol.Required(
|
||||
CONF_API_PROVIDER,
|
||||
default=current_provider
|
||||
): selector.SelectSelector(
|
||||
selector.SelectSelectorConfig(
|
||||
options=API_PROVIDERS,
|
||||
translation_key="api_provider"
|
||||
)
|
||||
): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=20)
|
||||
),
|
||||
vol.Optional(
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
default=current_data.get(
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
DEFAULT_MAX_HISTORY
|
||||
)
|
||||
): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=100)
|
||||
),
|
||||
})
|
||||
}),
|
||||
description_placeholders={
|
||||
"current_provider": current_provider
|
||||
}
|
||||
)
|
||||
|
||||
async def async_step_settings(self, user_input: dict[str, Any] | None = None) -> ConfigFlowResult:
|
||||
"""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 = get_default_endpoint(provider)
|
||||
default_model = get_default_model(provider)
|
||||
else:
|
||||
default_endpoint = current_data.get(CONF_API_ENDPOINT, get_default_endpoint(provider))
|
||||
default_model = current_data.get(CONF_MODEL, get_default_model(provider))
|
||||
|
||||
if user_input is not None:
|
||||
api_key = user_input.get(CONF_API_KEY, "").strip()
|
||||
endpoint = user_input.get(CONF_API_ENDPOINT, default_endpoint)
|
||||
|
||||
# Require API key re-entry when endpoint or provider changed.
|
||||
# Why: reusing a stored key after provider/endpoint change could
|
||||
# ship credentials to a different service (e.g. OpenAI key to
|
||||
# api.anthropic.com). Always force explicit re-entry.
|
||||
stored_endpoint = current_data.get(CONF_API_ENDPOINT, "")
|
||||
endpoint_changed = endpoint != stored_endpoint
|
||||
if not api_key and (provider_changed or endpoint_changed):
|
||||
self._errors["base"] = "api_key_required"
|
||||
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,
|
||||
description_placeholders={
|
||||
"provider": provider
|
||||
}
|
||||
)
|
||||
|
||||
# Fall back to stored key only when neither provider nor endpoint changed.
|
||||
# Defensive: never silently reuse stored key across providers.
|
||||
if not api_key and not provider_changed and not endpoint_changed:
|
||||
api_key = current_data.get(CONF_API_KEY, "")
|
||||
|
||||
allow_local = user_input.get(CONF_ALLOW_LOCAL_NETWORK, DEFAULT_ALLOW_LOCAL_NETWORK)
|
||||
if await self._async_validate_api(provider, api_key, endpoint, allow_local=allow_local):
|
||||
final_data = {
|
||||
CONF_API_PROVIDER: provider,
|
||||
**user_input,
|
||||
CONF_API_KEY: api_key,
|
||||
}
|
||||
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,
|
||||
description_placeholders={
|
||||
"provider": provider
|
||||
}
|
||||
)
|
||||
|
||||
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: dict[str, Any] | None,
|
||||
default_endpoint: str,
|
||||
default_model: str,
|
||||
) -> vol.Schema:
|
||||
"""Build settings schema using shared parameter definitions."""
|
||||
data = user_input or current_data
|
||||
|
||||
schema_dict = {
|
||||
vol.Optional(CONF_API_KEY, default=""): selector.TextSelector(
|
||||
selector.TextSelectorConfig(type=selector.TextSelectorType.PASSWORD)
|
||||
),
|
||||
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_ALLOW_LOCAL_NETWORK,
|
||||
default=data.get(CONF_ALLOW_LOCAL_NETWORK, DEFAULT_ALLOW_LOCAL_NETWORK),
|
||||
): bool,
|
||||
}
|
||||
schema_dict.update(_build_parameter_schema(data))
|
||||
return vol.Schema(schema_dict)
|
||||
|
||||
@@ -1,33 +1,41 @@
|
||||
"""
|
||||
Constants for the HA text AI integration.
|
||||
|
||||
@license: CC BY-NC-SA 4.0 International
|
||||
@license: MIT (https://opensource.org/licenses/MIT)
|
||||
@author: SMKRV
|
||||
@github: https://github.com/smkrv/ha-text-ai
|
||||
@source: https://github.com/smkrv/ha-text-ai
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
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
|
||||
from homeassistant.const import Platform
|
||||
|
||||
# Domain and platforms
|
||||
DOMAIN: Final = "ha_text_ai"
|
||||
PLATFORMS: list[str] = ["sensor"]
|
||||
PLATFORMS: list[Platform] = [Platform.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_ANTHROPIC,
|
||||
API_PROVIDER_DEEPSEEK,
|
||||
API_PROVIDER_GEMINI
|
||||
]
|
||||
|
||||
VERSION: Final = "2.5.1"
|
||||
|
||||
# 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
|
||||
CONF_MODEL: Final = "model"
|
||||
@@ -35,32 +43,55 @@ CONF_TEMPERATURE: Final = "temperature"
|
||||
CONF_MAX_TOKENS: Final = "max_tokens"
|
||||
CONF_API_ENDPOINT: Final = "api_endpoint"
|
||||
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"
|
||||
CONF_ALLOW_LOCAL_NETWORK: Final = "allow_local_network"
|
||||
CONF_DISABLE_THINKING: Final = "disable_thinking"
|
||||
|
||||
ABSOLUTE_MAX_HISTORY_SIZE: Final = 200 # Hard cap; UI allows max MAX_HISTORY_SIZE (100)
|
||||
MAX_ATTRIBUTE_SIZE = 4 * 1024
|
||||
MAX_HISTORY_FILE_SIZE = 1 * 1024 * 1024
|
||||
# Default values
|
||||
DEFAULT_MODEL: Final = "gpt-4o-mini"
|
||||
DEFAULT_ANTHROPIC_MODEL: Final = "claude-sonnet-4-6"
|
||||
# deepseek-chat/deepseek-reasoner are discontinued 2026-07-24; V4 models
|
||||
# select thinking mode via a request parameter instead of the model name.
|
||||
DEFAULT_DEEPSEEK_MODEL: Final = "deepseek-v4-flash"
|
||||
# gemini-2.0-flash was shut down 2026-06-01; 2.5-flash follows 2026-10-16.
|
||||
DEFAULT_GEMINI_MODEL: Final = "gemini-3.5-flash"
|
||||
DEFAULT_TEMPERATURE: Final = 0.1
|
||||
DEFAULT_MAX_TOKENS: Final = 1000
|
||||
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_INSTANCE_NAME: Final = "my_assistant"
|
||||
DEFAULT_CONTEXT_MESSAGES: Final = 5
|
||||
DEFAULT_ALLOW_LOCAL_NETWORK: Final = False
|
||||
DEFAULT_DISABLE_THINKING: Final = False
|
||||
MIN_CONTEXT_MESSAGES: Final = 1
|
||||
MAX_CONTEXT_MESSAGES: Final = 20
|
||||
MIN_HISTORY_SIZE: Final = 1
|
||||
MAX_HISTORY_SIZE: Final = 100
|
||||
|
||||
TRUNCATION_INDICATOR = " ... "
|
||||
|
||||
# Parameter constraints
|
||||
MIN_TEMPERATURE: Final = 0.0
|
||||
MAX_TEMPERATURE: Final = 2.0
|
||||
MIN_MAX_TOKENS: Final = 1
|
||||
MAX_MAX_TOKENS: Final = 4096
|
||||
MAX_MAX_TOKENS: Final = 100000
|
||||
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
|
||||
API_RETRY_COUNT: Final = 3
|
||||
|
||||
# Service names
|
||||
@@ -142,68 +173,3 @@ STATE_DISCONNECTED: Final = "disconnected"
|
||||
EVENT_RESPONSE_RECEIVED: Final = f"{DOMAIN}_response_received"
|
||||
EVENT_ERROR_OCCURRED: Final = f"{DOMAIN}_error_occurred"
|
||||
EVENT_STATE_CHANGED: Final = f"{DOMAIN}_state_changed"
|
||||
|
||||
# Service schema constants
|
||||
SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
|
||||
vol.Required(CONF_INSTANCE): cv.string,
|
||||
vol.Required("question"): cv.string,
|
||||
vol.Optional("system_prompt"): cv.string,
|
||||
vol.Optional("model"): cv.string,
|
||||
vol.Optional("temperature"): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
||||
),
|
||||
vol.Optional("max_tokens"): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
|
||||
),
|
||||
vol.Optional("context_messages"): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=20)
|
||||
)
|
||||
})
|
||||
|
||||
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
|
||||
vol.Required(CONF_INSTANCE): cv.string,
|
||||
vol.Required("prompt"): cv.string
|
||||
})
|
||||
|
||||
SERVICE_SCHEMA_GET_HISTORY = vol.Schema({
|
||||
vol.Required(CONF_INSTANCE): cv.string,
|
||||
vol.Optional("limit", default=10): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=100),
|
||||
),
|
||||
vol.Optional("filter_model"): cv.string
|
||||
})
|
||||
|
||||
# Configuration schema
|
||||
CONFIG_SCHEMA = vol.Schema({
|
||||
DOMAIN: vol.Schema({
|
||||
vol.Required(CONF_NAME): cv.string,
|
||||
vol.Required(CONF_API_KEY): cv.string,
|
||||
vol.Required(CONF_API_PROVIDER): vol.In(API_PROVIDERS),
|
||||
vol.Optional(CONF_MODEL, default=DEFAULT_MODEL): cv.string,
|
||||
vol.Optional(CONF_TEMPERATURE, default=DEFAULT_TEMPERATURE): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
||||
),
|
||||
vol.Optional(CONF_MAX_TOKENS, default=DEFAULT_MAX_TOKENS): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
|
||||
),
|
||||
vol.Optional(CONF_API_ENDPOINT): cv.string,
|
||||
vol.Optional(CONF_REQUEST_INTERVAL, default=DEFAULT_REQUEST_INTERVAL): vol.All(
|
||||
vol.Coerce(float),
|
||||
vol.Range(min=MIN_REQUEST_INTERVAL, max=MAX_REQUEST_INTERVAL)
|
||||
),
|
||||
vol.Optional(CONF_MAX_HISTORY_SIZE, default=DEFAULT_MAX_HISTORY): vol.All( # Correct usage
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=100),
|
||||
),
|
||||
vol.Optional(CONF_CONTEXT_MESSAGES, default=DEFAULT_CONTEXT_MESSAGES): vol.All(
|
||||
vol.Coerce(int),
|
||||
vol.Range(min=1, max=20)
|
||||
)
|
||||
})
|
||||
}, extra=vol.ALLOW_EXTRA)
|
||||
|
||||
@@ -1,45 +1,47 @@
|
||||
"""
|
||||
The HA Text AI coordinator.
|
||||
|
||||
@license: CC BY-NC-SA 4.0 International
|
||||
@license: MIT (https://opensource.org/licenses/MIT)
|
||||
@author: SMKRV
|
||||
@github: https://github.com/smkrv/ha-text-ai
|
||||
@source: https://github.com/smkrv/ha-text-ai
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import traceback
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, List, Optional
|
||||
import os
|
||||
from datetime import timedelta
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator
|
||||
from homeassistant.util import dt as dt_util
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.const import CONF_NAME
|
||||
from .config_flow import normalize_name
|
||||
|
||||
from .const import (
|
||||
DOMAIN,
|
||||
STATE_READY,
|
||||
STATE_PROCESSING,
|
||||
STATE_ERROR,
|
||||
STATE_RATE_LIMITED,
|
||||
STATE_MAINTENANCE,
|
||||
DEFAULT_API_TIMEOUT,
|
||||
DEFAULT_CONTEXT_MESSAGES,
|
||||
DEFAULT_DISABLE_THINKING,
|
||||
DEFAULT_MAX_HISTORY,
|
||||
DEFAULT_MAX_TOKENS,
|
||||
DEFAULT_TEMPERATURE,
|
||||
DEFAULT_MAX_HISTORY,
|
||||
DEFAULT_CONTEXT_MESSAGES,
|
||||
DEFAULT_NAME_PREFIX,
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
STATE_ERROR,
|
||||
STATE_MAINTENANCE,
|
||||
STATE_PROCESSING,
|
||||
STATE_RATE_LIMITED,
|
||||
STATE_READY,
|
||||
TRUNCATION_INDICATOR,
|
||||
)
|
||||
from .history import HistoryManager
|
||||
from .metrics import MetricsManager
|
||||
from .utils import normalize_name
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class HATextAICoordinator(DataUpdateCoordinator):
|
||||
"""The HA Text AI coordinator."""
|
||||
"""Home Assistant Text AI Conversation Coordinator."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -48,515 +50,388 @@ class HATextAICoordinator(DataUpdateCoordinator):
|
||||
model: str,
|
||||
update_interval: int,
|
||||
instance_name: str,
|
||||
config_entry: ConfigEntry,
|
||||
max_tokens: int = DEFAULT_MAX_TOKENS,
|
||||
temperature: float = DEFAULT_TEMPERATURE,
|
||||
max_history_size: int = DEFAULT_MAX_HISTORY,
|
||||
context_messages: int = DEFAULT_CONTEXT_MESSAGES,
|
||||
is_anthropic: bool = False,
|
||||
api_timeout: int = DEFAULT_API_TIMEOUT,
|
||||
disable_thinking: bool = DEFAULT_DISABLE_THINKING,
|
||||
) -> None:
|
||||
"""Initialize coordinator."""
|
||||
self.instance_name = instance_name
|
||||
self.normalized_name = None
|
||||
|
||||
# Use the normalize_name function from config_flow to ensure consistency
|
||||
from .config_flow import normalize_name
|
||||
self.normalized_name = normalize_name(instance_name)
|
||||
|
||||
history_dir = os.path.join(
|
||||
hass.config.path(".storage"), "ha_text_ai_history"
|
||||
)
|
||||
metrics_file = os.path.join(
|
||||
history_dir,
|
||||
f"ha_text_ai_metrics_{self.normalized_name}.json",
|
||||
)
|
||||
|
||||
# Delegate history and metrics to dedicated managers
|
||||
self._history = HistoryManager(
|
||||
hass=hass,
|
||||
instance_name=instance_name,
|
||||
normalized_name=self.normalized_name,
|
||||
history_dir=history_dir,
|
||||
max_history_size=max_history_size,
|
||||
)
|
||||
self._metrics = MetricsManager(
|
||||
hass=hass,
|
||||
instance_name=instance_name,
|
||||
metrics_file=metrics_file,
|
||||
)
|
||||
|
||||
self.hass = hass
|
||||
self.client = client
|
||||
self.model = model
|
||||
self.temperature = temperature
|
||||
self.max_tokens = max_tokens
|
||||
self.max_history_size = max_history_size
|
||||
self.is_anthropic = is_anthropic
|
||||
self.api_timeout = api_timeout
|
||||
self.disable_thinking = disable_thinking
|
||||
|
||||
# Initialize with default state
|
||||
self._initial_state = {
|
||||
"state": STATE_READY,
|
||||
"metrics": {
|
||||
"total_tokens": 0,
|
||||
"prompt_tokens": 0,
|
||||
"completion_tokens": 0,
|
||||
"successful_requests": 0,
|
||||
"failed_requests": 0,
|
||||
"total_errors": 0,
|
||||
"average_latency": 0,
|
||||
"max_latency": 0,
|
||||
"min_latency": float("inf"),
|
||||
},
|
||||
"last_response": {
|
||||
"timestamp": dt_util.utcnow().isoformat(),
|
||||
"question": "",
|
||||
"response": "",
|
||||
"model": model,
|
||||
"instance": instance_name,
|
||||
"normalized_name": self.normalized_name,
|
||||
"error": None,
|
||||
},
|
||||
"is_processing": False,
|
||||
"is_rate_limited": False,
|
||||
"is_maintenance": False,
|
||||
"endpoint_status": "ready",
|
||||
"uptime": 0,
|
||||
"system_prompt": None,
|
||||
"history_size": 0,
|
||||
"conversation_history": [],
|
||||
# Concurrency control
|
||||
self._request_lock = asyncio.Lock()
|
||||
|
||||
# State flags
|
||||
self._is_processing = False
|
||||
self._is_rate_limited = False
|
||||
self._is_maintenance = False
|
||||
self.endpoint_status = "ready"
|
||||
self._system_prompt: str | None = None
|
||||
|
||||
self._last_response: dict[str, Any] = {
|
||||
"timestamp": dt_util.utcnow().isoformat(),
|
||||
"question": "",
|
||||
"response": "",
|
||||
"model": model,
|
||||
"instance": instance_name,
|
||||
"normalized_name": self.normalized_name,
|
||||
"error": None,
|
||||
}
|
||||
|
||||
update_interval_td = timedelta(seconds=update_interval)
|
||||
|
||||
super().__init__(
|
||||
hass,
|
||||
_LOGGER,
|
||||
name=instance_name,
|
||||
update_interval=update_interval_td,
|
||||
update_interval=timedelta(seconds=update_interval),
|
||||
config_entry=config_entry,
|
||||
)
|
||||
|
||||
# Register instance
|
||||
self.hass.data.setdefault(DOMAIN, {})
|
||||
self.hass.data[DOMAIN][instance_name] = self
|
||||
self.available = True
|
||||
self._state = STATE_READY
|
||||
self._start_time = dt_util.utcnow()
|
||||
self.context_messages = context_messages
|
||||
|
||||
self._system_prompt = None
|
||||
self._conversation_history = []
|
||||
self._performance_metrics = self._initial_state["metrics"].copy()
|
||||
self._is_processing = False
|
||||
self._is_rate_limited = False
|
||||
self._is_maintenance = False
|
||||
self.endpoint_status = "ready"
|
||||
self.last_response = self._initial_state["last_response"].copy()
|
||||
self._start_time = dt_util.utcnow()
|
||||
_LOGGER.info("Initialized HA Text AI coordinator: %s", instance_name)
|
||||
|
||||
_LOGGER.info(
|
||||
f"Initialized HA Text AI coordinator with instance: {instance_name}"
|
||||
)
|
||||
# ------------------------------------------------------------------
|
||||
# Convenience accessors for backward compatibility
|
||||
# ------------------------------------------------------------------
|
||||
@property
|
||||
def _conversation_history(self) -> list[dict[str, Any]]:
|
||||
return self._history.conversation_history
|
||||
|
||||
async def _async_update_data(self) -> Dict[str, Any]:
|
||||
"""Update data via library."""
|
||||
@property
|
||||
def max_history_size(self) -> int:
|
||||
return self._history.max_history_size
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Lifecycle
|
||||
# ------------------------------------------------------------------
|
||||
async def async_initialize(self) -> None:
|
||||
"""Initialize coordinator: directories, history, metrics. Must be awaited."""
|
||||
await self._history.async_initialize()
|
||||
await self._metrics.async_initialize()
|
||||
|
||||
async def async_shutdown(self) -> None:
|
||||
"""Shutdown coordinator."""
|
||||
_LOGGER.debug("Shutting down coordinator for %s", self.instance_name)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Last response
|
||||
# ------------------------------------------------------------------
|
||||
@property
|
||||
def last_response(self) -> dict[str, Any]:
|
||||
"""Get the last response."""
|
||||
return self._last_response
|
||||
|
||||
@last_response.setter
|
||||
def last_response(self, value: dict[str, Any]) -> None:
|
||||
self._last_response = value
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# HA state update
|
||||
# ------------------------------------------------------------------
|
||||
async def async_update_ha_state(self) -> None:
|
||||
"""Update Home Assistant state via coordinator refresh."""
|
||||
try:
|
||||
await self.async_request_refresh()
|
||||
except Exception as err:
|
||||
_LOGGER.error("Error updating HA state for %s: %s", self.instance_name, err)
|
||||
|
||||
async def _async_update_data(self) -> dict[str, Any]:
|
||||
"""Update coordinator data."""
|
||||
try:
|
||||
current_state = self._get_current_state()
|
||||
_LOGGER.debug(
|
||||
f"Updating data for {self.instance_name}, current state: {current_state}"
|
||||
)
|
||||
history_data = self._history.get_limited_history()
|
||||
metrics = await self._metrics.get_current_metrics()
|
||||
|
||||
data = {
|
||||
"state": current_state,
|
||||
"metrics": self._performance_metrics,
|
||||
"last_response": self.last_response,
|
||||
"metrics": metrics or {},
|
||||
"last_response": self._get_sanitized_last_response(),
|
||||
"is_processing": self._is_processing,
|
||||
"is_rate_limited": self._is_rate_limited,
|
||||
"is_maintenance": self._is_maintenance,
|
||||
"endpoint_status": self.endpoint_status,
|
||||
"uptime": (dt_util.utcnow() - self._start_time).total_seconds(),
|
||||
"system_prompt": self._system_prompt,
|
||||
"history_size": len(self._conversation_history),
|
||||
"conversation_history": self._conversation_history,
|
||||
"uptime": self._calculate_uptime(),
|
||||
"system_prompt": self._get_truncated_system_prompt(),
|
||||
"history_size": self._history.history_size,
|
||||
"conversation_history": history_data["entries"],
|
||||
"history_info": history_data["info"],
|
||||
"normalized_name": self.normalized_name,
|
||||
}
|
||||
|
||||
# Validate data
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("Invalid data format")
|
||||
|
||||
_LOGGER.debug(f"Updated data for {self.instance_name}: {data}")
|
||||
self._validate_update_data(data)
|
||||
return data
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.error(f"Error updating data for {self.instance_name}: {err}")
|
||||
return self._initial_state
|
||||
|
||||
async def async_update_ha_state(self) -> None:
|
||||
"""Update Home Assistant state."""
|
||||
try:
|
||||
_LOGGER.debug(
|
||||
f"Requesting state update for {self.instance_name} (normalized: {self.normalized_name})"
|
||||
)
|
||||
await self.async_request_refresh()
|
||||
|
||||
# Force update of all entities
|
||||
entity_id_base = f"sensor.ha_text_ai_{self.normalized_name.lower()}"
|
||||
for entity_id in self.hass.states.async_entity_ids():
|
||||
if entity_id.startswith(entity_id_base):
|
||||
self.hass.states.async_set(entity_id, self._get_current_state())
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.error(f"Error updating HA state for {self.instance_name}: {err}")
|
||||
|
||||
def _get_current_state(self) -> str:
|
||||
"""Get current state based on internal flags."""
|
||||
if self._is_processing:
|
||||
return STATE_PROCESSING
|
||||
elif self._is_rate_limited:
|
||||
return STATE_RATE_LIMITED
|
||||
elif self._is_maintenance:
|
||||
return STATE_MAINTENANCE
|
||||
elif self.last_response.get("error"):
|
||||
return STATE_ERROR
|
||||
return STATE_READY
|
||||
|
||||
def _calculate_context_tokens(self, messages: List[Dict[str, str]], model: str = None) -> int:
|
||||
"""
|
||||
Estimate tokens for conversation context.
|
||||
|
||||
Args:
|
||||
messages: List of message dictionaries
|
||||
model: Optional model name for provider-specific estimation
|
||||
|
||||
Returns:
|
||||
Estimated number of tokens
|
||||
"""
|
||||
try:
|
||||
# Anthropic specific token counting
|
||||
if self.is_anthropic and hasattr(self.client, 'count_tokens'):
|
||||
return sum(self.client.count_tokens(msg['content']) for msg in messages)
|
||||
|
||||
def estimate_tokens(text: str) -> int:
|
||||
"""
|
||||
Flexible token estimation algorithm.
|
||||
|
||||
Heuristics:
|
||||
- Count words
|
||||
- Estimate special characters
|
||||
- Fallback to character-based estimation
|
||||
"""
|
||||
# Word-based estimation
|
||||
words = len(text.split())
|
||||
|
||||
# Special character handling
|
||||
special_chars = sum(1 for char in text if not char.isalnum())
|
||||
|
||||
# Character-based fallback
|
||||
char_tokens = len(text) // 4
|
||||
|
||||
# Combine estimations with bias towards words
|
||||
total_tokens = (words * 1.5) + (special_chars * 0.5) + char_tokens
|
||||
|
||||
return max(int(total_tokens), words)
|
||||
|
||||
# Calculate total tokens across all messages
|
||||
total_tokens = sum(estimate_tokens(msg['content']) for msg in messages)
|
||||
|
||||
# Logging for debugging
|
||||
_LOGGER.debug(
|
||||
f"Token Estimation: "
|
||||
f"Messages: {len(messages)}, "
|
||||
f"Estimated Tokens: {total_tokens}"
|
||||
)
|
||||
|
||||
return total_tokens
|
||||
|
||||
except Exception as e:
|
||||
# Safe fallback with detailed logging
|
||||
_LOGGER.warning(
|
||||
f"Token estimation failed. "
|
||||
f"Error: {e}. "
|
||||
f"Using conservative estimation."
|
||||
)
|
||||
|
||||
# Conservative token estimation
|
||||
return len(messages) * 100
|
||||
_LOGGER.error("Error updating data: %s", err, exc_info=True)
|
||||
return self._get_safe_initial_state()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Question processing
|
||||
# ------------------------------------------------------------------
|
||||
async def async_ask_question(
|
||||
self,
|
||||
question: str,
|
||||
model: Optional[str] = None,
|
||||
temperature: Optional[float] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
system_prompt: Optional[str] = None,
|
||||
context_messages: Optional[int] = None,
|
||||
model: str | None = None,
|
||||
temperature: float | None = None,
|
||||
max_tokens: int | None = None,
|
||||
system_prompt: str | None = None,
|
||||
context_messages: int | None = None,
|
||||
structured_output: bool = False,
|
||||
json_schema: str | None = None,
|
||||
disable_thinking: bool | None = None,
|
||||
) -> dict:
|
||||
"""
|
||||
Process a question with optional parameters.
|
||||
"""Process question with context management."""
|
||||
if self.client is None:
|
||||
raise HomeAssistantError("AI client not initialized")
|
||||
|
||||
This method is a direct wrapper around async_process_question,
|
||||
allowing flexible AI interaction with optional model, temperature,
|
||||
and context customization.
|
||||
|
||||
Args:
|
||||
question: The input question or prompt
|
||||
model: Optional AI model to use
|
||||
temperature: Optional response creativity level
|
||||
max_tokens: Optional maximum response length
|
||||
system_prompt: Optional system-level instruction
|
||||
context_messages: Optional number of context messages to include
|
||||
|
||||
Returns:
|
||||
Full response dictionary from the AI
|
||||
"""
|
||||
return await self.async_process_question(
|
||||
question, model, temperature, max_tokens, system_prompt, context_messages
|
||||
)
|
||||
|
||||
async def async_process_question(
|
||||
self,
|
||||
question: str,
|
||||
model: Optional[str] = None,
|
||||
temperature: Optional[float] = None,
|
||||
max_tokens: Optional[int] = None,
|
||||
system_prompt: Optional[str] = None,
|
||||
context_messages: Optional[int] = None,
|
||||
) -> dict:
|
||||
"""
|
||||
Enhanced question processing with intelligent token management.
|
||||
"""
|
||||
async with self._request_lock:
|
||||
try:
|
||||
self._is_processing = True
|
||||
await self.async_update_ha_state()
|
||||
|
||||
temp_context_messages = context_messages or self.context_messages
|
||||
temp_model = model or self.model
|
||||
temp_temperature = temperature or self.temperature
|
||||
temp_max_tokens = max_tokens or self.max_tokens
|
||||
temp_system_prompt = system_prompt or self._system_prompt
|
||||
temp_context = context_messages if context_messages is not None else self.context_messages
|
||||
temp_model = model if model is not None else self.model
|
||||
temp_temperature = temperature if temperature is not None else self.temperature
|
||||
temp_max_tokens = max_tokens if max_tokens is not None else self.max_tokens
|
||||
temp_system_prompt = system_prompt if system_prompt is not None else self._system_prompt
|
||||
temp_disable_thinking = disable_thinking if disable_thinking is not None else self.disable_thinking
|
||||
|
||||
# Start timing
|
||||
start_time = dt_util.utcnow()
|
||||
|
||||
# Prepare messages with system prompt
|
||||
messages = []
|
||||
if temp_system_prompt:
|
||||
messages.append({"role": "system", "content": temp_system_prompt})
|
||||
|
||||
# Context history management
|
||||
context_history = self._conversation_history[-temp_context_messages:]
|
||||
|
||||
# Comprehensive token calculation
|
||||
context_tokens = self._calculate_context_tokens(
|
||||
[{"content": entry["question"]} for entry in context_history] +
|
||||
[{"content": entry["response"]} for entry in context_history] +
|
||||
[{"content": question}],
|
||||
temp_model
|
||||
)
|
||||
|
||||
# Dynamic token allocation
|
||||
available_tokens = max(0, temp_max_tokens - context_tokens)
|
||||
|
||||
# Context trimming if over token limit
|
||||
if context_tokens > temp_max_tokens:
|
||||
_LOGGER.warning(
|
||||
f"Token limit exceeded. "
|
||||
f"Context: {context_tokens}, "
|
||||
f"Max: {temp_max_tokens}"
|
||||
)
|
||||
|
||||
# Intelligent context reduction
|
||||
while context_tokens > temp_max_tokens // 2 and context_history:
|
||||
context_history.pop(0)
|
||||
context_tokens = self._calculate_context_tokens(
|
||||
[{"content": entry["question"]} for entry in context_history] +
|
||||
[{"content": entry["response"]} for entry in context_history] +
|
||||
[{"content": question}],
|
||||
temp_model
|
||||
)
|
||||
|
||||
# Rebuild messages with trimmed context
|
||||
context_history = self._conversation_history[-temp_context:]
|
||||
for entry in context_history:
|
||||
messages.append({"role": "user", "content": entry["question"]})
|
||||
messages.append({"role": "assistant", "content": entry["response"]})
|
||||
|
||||
messages.append({"role": "user", "content": question})
|
||||
|
||||
# Detailed token logging
|
||||
_LOGGER.debug(
|
||||
f"Token Analysis: "
|
||||
f"Context Tokens: {context_tokens}, "
|
||||
f"Max Tokens: {temp_max_tokens}, "
|
||||
f"Available Tokens: {available_tokens}"
|
||||
response = await self._send_to_api(
|
||||
question=question,
|
||||
model=temp_model,
|
||||
messages=messages,
|
||||
temperature=temp_temperature,
|
||||
max_tokens=temp_max_tokens,
|
||||
structured_output=structured_output,
|
||||
json_schema=json_schema,
|
||||
disable_thinking=temp_disable_thinking,
|
||||
)
|
||||
|
||||
# Prepare API call with dynamic token management
|
||||
kwargs = {
|
||||
"model": temp_model,
|
||||
"temperature": temp_temperature,
|
||||
"max_tokens": min(temp_max_tokens, available_tokens),
|
||||
"messages": messages,
|
||||
}
|
||||
|
||||
# Process message
|
||||
response = await self.async_process_message(question, **kwargs)
|
||||
|
||||
# Update metrics
|
||||
end_time = dt_util.utcnow()
|
||||
latency = (end_time - start_time).total_seconds()
|
||||
self._update_metrics(latency, response)
|
||||
|
||||
# Update history
|
||||
self._update_history(question, response)
|
||||
latency = (dt_util.utcnow() - start_time).total_seconds()
|
||||
await self._metrics.update_metrics(latency, response)
|
||||
await self._history.update_history(question, response)
|
||||
|
||||
return response
|
||||
|
||||
except Exception as err:
|
||||
self._handle_error(err)
|
||||
raise HomeAssistantError(f"Failed to process question: {err}")
|
||||
error_details = await self._metrics.handle_error(err, self.model)
|
||||
if error_details.get("is_connection_error"):
|
||||
self.endpoint_status = "unavailable"
|
||||
self.last_response = error_details
|
||||
raise HomeAssistantError(f"Failed to process question: {err}") from err
|
||||
|
||||
finally:
|
||||
self._is_processing = False
|
||||
await self.async_update_ha_state()
|
||||
|
||||
async def async_process_message(self, question: str, **kwargs) -> dict:
|
||||
"""Process message using the AI client."""
|
||||
async def _send_to_api(
|
||||
self,
|
||||
question: str,
|
||||
model: str,
|
||||
messages: list[dict[str, str]],
|
||||
temperature: float,
|
||||
max_tokens: int,
|
||||
structured_output: bool = False,
|
||||
json_schema: str | None = None,
|
||||
disable_thinking: bool = False,
|
||||
) -> dict:
|
||||
"""Send request to AI provider and return structured response.
|
||||
|
||||
Note: timeout is handled by APIClient via aiohttp ClientTimeout.
|
||||
No additional asyncio.timeout wrapper to avoid dual timeout stacking.
|
||||
"""
|
||||
try:
|
||||
if self.is_anthropic:
|
||||
response = await self._process_anthropic_message(question, **kwargs)
|
||||
else:
|
||||
response = await self._process_openai_message(question, **kwargs)
|
||||
response = await self.client.create(
|
||||
model=model,
|
||||
messages=messages,
|
||||
temperature=temperature,
|
||||
max_tokens=max_tokens,
|
||||
structured_output=structured_output,
|
||||
json_schema=json_schema,
|
||||
disable_thinking=disable_thinking,
|
||||
)
|
||||
|
||||
# Reset error state on success
|
||||
self._is_rate_limited = False
|
||||
self.endpoint_status = "ready"
|
||||
|
||||
timestamp = dt_util.utcnow().isoformat()
|
||||
content = response["choices"][0]["message"]["content"]
|
||||
tokens = {
|
||||
"prompt": response["usage"]["prompt_tokens"],
|
||||
"completion": response["usage"]["completion_tokens"],
|
||||
"total": response["usage"]["total_tokens"],
|
||||
}
|
||||
|
||||
self.last_response = {
|
||||
"timestamp": dt_util.utcnow().isoformat(),
|
||||
"timestamp": timestamp,
|
||||
"question": question,
|
||||
"response": response["content"],
|
||||
"model": kwargs.get("model", self.model),
|
||||
"response": content,
|
||||
"model": model,
|
||||
"instance": self.instance_name,
|
||||
"normalized_name": self.normalized_name,
|
||||
"error": None,
|
||||
}
|
||||
|
||||
return response
|
||||
return {
|
||||
"content": content,
|
||||
"tokens": tokens,
|
||||
"model": model,
|
||||
"timestamp": timestamp,
|
||||
"instance": self.instance_name,
|
||||
"question": question,
|
||||
"success": True,
|
||||
}
|
||||
|
||||
except Exception as err:
|
||||
self._handle_error(err)
|
||||
_LOGGER.error("Error in API call: %s", err)
|
||||
raise
|
||||
|
||||
async def _process_anthropic_message(self, question: str, **kwargs) -> dict:
|
||||
"""Process message using Anthropic API."""
|
||||
try:
|
||||
_LOGGER.debug(f"Anthropic API call: model={kwargs['model']}, max_tokens={kwargs['max_tokens']}")
|
||||
response = await self.client.messages.create(
|
||||
model=kwargs["model"],
|
||||
max_tokens=kwargs["max_tokens"],
|
||||
messages=kwargs["messages"],
|
||||
temperature=kwargs["temperature"],
|
||||
)
|
||||
_LOGGER.debug(f"Anthropic response: tokens={response.usage}")
|
||||
return {
|
||||
"content": response.content[0].text,
|
||||
"tokens": {
|
||||
"prompt": response.usage.input_tokens,
|
||||
"completion": response.usage.output_tokens,
|
||||
"total": response.usage.input_tokens + response.usage.output_tokens,
|
||||
},
|
||||
}
|
||||
except Exception as e:
|
||||
_LOGGER.error(f"Anthropic API error: {str(e)}")
|
||||
raise
|
||||
|
||||
async def _process_openai_message(self, question: str, **kwargs) -> dict:
|
||||
"""Process message using OpenAI API."""
|
||||
try:
|
||||
response = await self.client.create(
|
||||
model=kwargs["model"],
|
||||
messages=kwargs["messages"],
|
||||
temperature=kwargs["temperature"],
|
||||
max_tokens=kwargs["max_tokens"],
|
||||
)
|
||||
|
||||
return {
|
||||
"content": response["choices"][0]["message"]["content"],
|
||||
"tokens": {
|
||||
"prompt": response["usage"]["prompt_tokens"],
|
||||
"completion": response["usage"]["completion_tokens"],
|
||||
"total": response["usage"]["total_tokens"],
|
||||
},
|
||||
}
|
||||
except Exception as e:
|
||||
_LOGGER.error(f"Error in OpenAI API call: {str(e)}")
|
||||
raise
|
||||
|
||||
def _update_metrics(self, latency: float, response: dict) -> None:
|
||||
"""Update performance metrics."""
|
||||
metrics = self._performance_metrics
|
||||
tokens = response.get("tokens", {})
|
||||
|
||||
metrics["total_tokens"] += tokens.get("total", 0)
|
||||
metrics["prompt_tokens"] += tokens.get("prompt", 0)
|
||||
metrics["completion_tokens"] += tokens.get("completion", 0)
|
||||
metrics["successful_requests"] += 1
|
||||
|
||||
metrics["average_latency"] = (
|
||||
(metrics["average_latency"] * (metrics["successful_requests"] - 1) + latency)
|
||||
/ metrics["successful_requests"]
|
||||
)
|
||||
metrics["max_latency"] = max(metrics["max_latency"], latency)
|
||||
metrics["min_latency"] = min(metrics["min_latency"], latency)
|
||||
|
||||
def _update_history(self, question: str, response: dict) -> None:
|
||||
"""Update conversation history."""
|
||||
self._conversation_history.append(
|
||||
{
|
||||
"timestamp": dt_util.utcnow().isoformat(),
|
||||
"question": question,
|
||||
"response": response["content"],
|
||||
}
|
||||
)
|
||||
|
||||
while len(self._conversation_history) > self.max_history_size:
|
||||
self._conversation_history.pop(0)
|
||||
|
||||
def _handle_error(self, error: Exception) -> None:
|
||||
"""
|
||||
Enhanced error handling with comprehensive diagnostics.
|
||||
|
||||
Captures detailed error information, tracks error metrics,
|
||||
and provides context for troubleshooting AI processing issues.
|
||||
"""
|
||||
self._performance_metrics["total_errors"] += 1
|
||||
self._performance_metrics["failed_requests"] += 1
|
||||
|
||||
error_details = {
|
||||
"timestamp": dt_util.utcnow().isoformat(),
|
||||
"model": self.model,
|
||||
"instance": self.instance_name,
|
||||
"error_message": str(error),
|
||||
"error_type": type(error).__name__,
|
||||
"traceback": traceback.format_exc() if _LOGGER.isEnabledFor(logging.DEBUG) else None,
|
||||
}
|
||||
|
||||
# Specific error type handling
|
||||
error_mapping = {
|
||||
HomeAssistantError: {"is_ha_error": True},
|
||||
ConnectionError: {
|
||||
"is_connection_error": True,
|
||||
"is_rate_limited": True
|
||||
},
|
||||
TimeoutError: {"is_timeout": True},
|
||||
PermissionError: {"is_permission_denied": True},
|
||||
ValueError: {"is_validation_error": True}
|
||||
}
|
||||
|
||||
for error_type, error_flags in error_mapping.items():
|
||||
if isinstance(error, error_type):
|
||||
error_details.update(error_flags)
|
||||
break
|
||||
|
||||
# Update system state based on error type
|
||||
if error_details.get("is_rate_limited"):
|
||||
self._is_rate_limited = True
|
||||
_LOGGER.warning(f"Rate limit detected for {self.instance_name}")
|
||||
|
||||
if error_details.get("is_connection_error"):
|
||||
self.endpoint_status = "unavailable"
|
||||
|
||||
self.last_response = error_details
|
||||
_LOGGER.error(f"AI Processing Error: {error_details}")
|
||||
|
||||
# Optional: Add more sophisticated error tracking or notification logic
|
||||
if _LOGGER.isEnabledFor(logging.DEBUG):
|
||||
_LOGGER.debug(f"Full Error Traceback: {error_details['traceback']}")
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# History / prompt delegation
|
||||
# ------------------------------------------------------------------
|
||||
async def async_clear_history(self) -> None:
|
||||
"""Clear conversation history."""
|
||||
self._conversation_history = []
|
||||
await self._history.async_clear_history()
|
||||
await self.async_update_ha_state()
|
||||
|
||||
async def async_get_history(self) -> List[Dict[str, str]]:
|
||||
"""Get conversation history."""
|
||||
return self._conversation_history
|
||||
async def async_get_history(
|
||||
self,
|
||||
limit: int | None = None,
|
||||
filter_model: str | None = None,
|
||||
start_date: str | None = None,
|
||||
include_metadata: bool = False,
|
||||
sort_order: str = "newest",
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Get conversation history with optional filtering."""
|
||||
return await self._history.async_get_history(
|
||||
limit=limit,
|
||||
filter_model=filter_model,
|
||||
start_date=start_date,
|
||||
include_metadata=include_metadata,
|
||||
sort_order=sort_order,
|
||||
default_model=self.model,
|
||||
)
|
||||
|
||||
async def async_set_system_prompt(self, prompt: str) -> None:
|
||||
"""Set system prompt."""
|
||||
self._system_prompt = prompt
|
||||
await self.async_update_ha_state()
|
||||
|
||||
async def async_shutdown(self) -> None:
|
||||
"""Shutdown coordinator."""
|
||||
_LOGGER.debug(f"Shutting down coordinator for {self.instance_name}")
|
||||
self.hass.data[DOMAIN].pop(self.instance_name, None)
|
||||
# ------------------------------------------------------------------
|
||||
# Internal helpers
|
||||
# ------------------------------------------------------------------
|
||||
def _get_current_state(self) -> str:
|
||||
if self._is_processing:
|
||||
return STATE_PROCESSING
|
||||
if self._is_rate_limited:
|
||||
return STATE_RATE_LIMITED
|
||||
if self._is_maintenance:
|
||||
return STATE_MAINTENANCE
|
||||
if self.last_response.get("error") or self.last_response.get("error_message"):
|
||||
return STATE_ERROR
|
||||
return STATE_READY
|
||||
|
||||
def _get_safe_initial_state(self) -> dict[str, Any]:
|
||||
return {
|
||||
"state": STATE_ERROR,
|
||||
"metrics": {},
|
||||
"last_response": self.last_response,
|
||||
"is_processing": False,
|
||||
"is_rate_limited": False,
|
||||
"is_maintenance": False,
|
||||
"endpoint_status": "error",
|
||||
"uptime": self._calculate_uptime(),
|
||||
"system_prompt": None,
|
||||
"history_size": 0,
|
||||
"conversation_history": [],
|
||||
"history_info": {
|
||||
"total_entries": 0,
|
||||
"displayed_entries": 0,
|
||||
},
|
||||
"normalized_name": self.normalized_name,
|
||||
}
|
||||
|
||||
def _get_sanitized_last_response(self) -> dict[str, Any]:
|
||||
"""Get sanitized version of last response with truncation."""
|
||||
response = self.last_response.copy()
|
||||
|
||||
for field in ("response", "question"):
|
||||
if field in response and response[field]:
|
||||
original = response[field]
|
||||
truncated = len(original) > 4096
|
||||
response[field] = (
|
||||
original[:4096] + TRUNCATION_INDICATOR if truncated else original
|
||||
)
|
||||
response[f"is_{field}_truncated"] = truncated
|
||||
response[f"full_{field}_length"] = len(original)
|
||||
|
||||
return response
|
||||
|
||||
def _calculate_uptime(self) -> float:
|
||||
return (dt_util.utcnow() - self._start_time).total_seconds()
|
||||
|
||||
def _get_truncated_system_prompt(self) -> str | None:
|
||||
if not self._system_prompt:
|
||||
return None
|
||||
if len(self._system_prompt) <= 4096:
|
||||
return self._system_prompt
|
||||
return self._system_prompt[:4096] + TRUNCATION_INDICATOR
|
||||
|
||||
@staticmethod
|
||||
def _validate_update_data(data: dict[str, Any]) -> None:
|
||||
for key in ("state", "metrics", "last_response"):
|
||||
if key not in data:
|
||||
raise ValueError(f"Missing required key: {key}")
|
||||
if not isinstance(data["metrics"], dict):
|
||||
raise ValueError("Invalid metrics format")
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
"""
|
||||
History management for HA Text AI integration.
|
||||
|
||||
@license: MIT (https://opensource.org/licenses/MIT)
|
||||
@author: SMKRV
|
||||
@github: https://github.com/smkrv/ha-text-ai
|
||||
@source: https://github.com/smkrv/ha-text-ai
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import traceback
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
import aiofiles
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from .const import (
|
||||
ABSOLUTE_MAX_HISTORY_SIZE,
|
||||
MAX_ATTRIBUTE_SIZE,
|
||||
MAX_HISTORY_FILE_SIZE,
|
||||
TRUNCATION_INDICATOR,
|
||||
)
|
||||
|
||||
# Per-entry storage cap (32KB per field) to prevent disk exhaustion
|
||||
MAX_STORED_FIELD_SIZE = 32 * 1024
|
||||
MAX_ARCHIVE_FILES = 3
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
class AsyncFileHandler:
|
||||
"""Async context manager for file operations."""
|
||||
|
||||
def __init__(self, file_path: str, mode: str = "a"):
|
||||
self.file_path = file_path
|
||||
self.mode = mode
|
||||
|
||||
async def __aenter__(self):
|
||||
self.file = await aiofiles.open(self.file_path, self.mode)
|
||||
return self.file
|
||||
|
||||
async def __aexit__(self, exc_type, exc_val, exc_tb):
|
||||
await self.file.close()
|
||||
|
||||
def _assert_not_symlink(path: str) -> None:
|
||||
"""Refuse to operate on a path that resolves to a symlink.
|
||||
|
||||
Why: another component or an attacker with filesystem access could
|
||||
replace our history file with a symlink pointing at arbitrary disk
|
||||
locations. Then os.remove or shutil.move would hit the target
|
||||
instead of our managed file. Check before destructive ops.
|
||||
"""
|
||||
if os.path.islink(path):
|
||||
raise OSError(f"Refusing to operate on symlink: {path}")
|
||||
|
||||
class HistoryManager:
|
||||
"""Manages conversation history for an instance."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
instance_name: str,
|
||||
normalized_name: str,
|
||||
history_dir: str,
|
||||
max_history_size: int,
|
||||
) -> None:
|
||||
self.hass = hass
|
||||
self.instance_name = instance_name
|
||||
self.normalized_name = normalized_name
|
||||
self._history_dir = history_dir
|
||||
self.max_history_size = min(
|
||||
max(1, max_history_size), ABSOLUTE_MAX_HISTORY_SIZE
|
||||
)
|
||||
self._history_file = os.path.join(
|
||||
history_dir, f"{normalized_name}_history.json"
|
||||
)
|
||||
self._max_history_file_size = MAX_HISTORY_FILE_SIZE
|
||||
self._conversation_history: list[dict[str, Any]] = []
|
||||
|
||||
@property
|
||||
def conversation_history(self) -> list[dict[str, Any]]:
|
||||
return self._conversation_history
|
||||
|
||||
@property
|
||||
def history_size(self) -> int:
|
||||
return len(self._conversation_history)
|
||||
|
||||
async def async_initialize(self) -> None:
|
||||
"""Initialize history: directories, file, migration."""
|
||||
await self._create_history_dir()
|
||||
await self._check_history_directory()
|
||||
await self._initialize_history_file()
|
||||
await self._migrate_history_from_txt_to_json()
|
||||
|
||||
async def _file_exists(self, path: str) -> bool:
|
||||
try:
|
||||
return await self.hass.async_add_executor_job(os.path.exists, path)
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error checking file existence for %s: %s", path, e)
|
||||
return False
|
||||
|
||||
async def _create_history_dir(self) -> None:
|
||||
try:
|
||||
await self.hass.async_add_executor_job(
|
||||
os.makedirs, self._history_dir, 0o755, True
|
||||
)
|
||||
except PermissionError:
|
||||
_LOGGER.error("Permission denied creating history directory: %s", self._history_dir)
|
||||
raise
|
||||
except OSError as e:
|
||||
_LOGGER.error("Error creating history directory %s: %s", self._history_dir, e)
|
||||
raise
|
||||
|
||||
async def _check_history_directory(self) -> None:
|
||||
"""Check history directory permissions and writability."""
|
||||
try:
|
||||
test_file_path = os.path.join(self._history_dir, ".write_test")
|
||||
await self.hass.async_add_executor_job(
|
||||
self._sync_test_directory_write, test_file_path
|
||||
)
|
||||
except PermissionError:
|
||||
_LOGGER.error("No write permissions for history directory: %s", self._history_dir)
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error checking history directory: %s", e)
|
||||
|
||||
@staticmethod
|
||||
def _sync_test_directory_write(test_file_path: str) -> None:
|
||||
try:
|
||||
os.makedirs(os.path.dirname(test_file_path), mode=0o755, exist_ok=True)
|
||||
with open(test_file_path, "w") as f:
|
||||
f.write("Permission test")
|
||||
os.remove(test_file_path)
|
||||
except Exception as e:
|
||||
_LOGGER.error("Directory write test failed: %s", e)
|
||||
|
||||
async def _initialize_history_file(self) -> None:
|
||||
"""Initialize history file and load existing history."""
|
||||
try:
|
||||
if await self._file_exists(self._history_file):
|
||||
async with AsyncFileHandler(self._history_file, "r") as f:
|
||||
content = await f.read()
|
||||
if content:
|
||||
history = json.loads(content)
|
||||
if isinstance(history, list):
|
||||
self._conversation_history = history[
|
||||
-self.max_history_size :
|
||||
]
|
||||
_LOGGER.debug(
|
||||
"Loaded %d history entries for %s",
|
||||
len(self._conversation_history),
|
||||
self.instance_name,
|
||||
)
|
||||
else:
|
||||
async with AsyncFileHandler(self._history_file, "w") as f:
|
||||
await f.write(json.dumps([]))
|
||||
|
||||
await self._check_history_size()
|
||||
except Exception as e:
|
||||
_LOGGER.error("Could not initialize history file: %s", e)
|
||||
_LOGGER.debug(traceback.format_exc())
|
||||
|
||||
async def update_history(self, question: str, response: dict) -> None:
|
||||
"""Update conversation history.
|
||||
|
||||
In-memory history stores full text for context retrieval.
|
||||
On-disk storage caps per-field size to prevent disk exhaustion.
|
||||
Display truncation is handled by get_limited_history().
|
||||
"""
|
||||
try:
|
||||
content = response.get("content", "")
|
||||
history_entry = {
|
||||
"timestamp": dt_util.utcnow().isoformat(),
|
||||
"question": question[:MAX_STORED_FIELD_SIZE],
|
||||
"response": content[:MAX_STORED_FIELD_SIZE],
|
||||
}
|
||||
|
||||
self._conversation_history.append(history_entry)
|
||||
|
||||
while len(self._conversation_history) > self.max_history_size:
|
||||
self._conversation_history.pop(0)
|
||||
|
||||
await self._save_history_to_file()
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error updating history: %s", e)
|
||||
_LOGGER.debug(traceback.format_exc())
|
||||
|
||||
async def _save_history_to_file(self) -> None:
|
||||
"""Serialize in-memory history to file with rotation if needed."""
|
||||
try:
|
||||
data = json.dumps(self._conversation_history, indent=2)
|
||||
data_size = len(data.encode("utf-8"))
|
||||
|
||||
if data_size > MAX_HISTORY_FILE_SIZE:
|
||||
await self._rotate_history()
|
||||
|
||||
async with AsyncFileHandler(self._history_file, "w") as f:
|
||||
await f.write(data)
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error writing history file: %s", e)
|
||||
_LOGGER.debug(traceback.format_exc())
|
||||
|
||||
async def _check_history_size(self) -> None:
|
||||
if len(self._conversation_history) > self.max_history_size:
|
||||
_LOGGER.warning(
|
||||
"History size (%d) exceeds maximum (%d). Trimming...",
|
||||
len(self._conversation_history), self.max_history_size,
|
||||
)
|
||||
self._conversation_history = self._conversation_history[
|
||||
-self.max_history_size :
|
||||
]
|
||||
|
||||
async def _check_file_size(self, file_path: str) -> int:
|
||||
try:
|
||||
if await self._file_exists(file_path):
|
||||
return await self.hass.async_add_executor_job(
|
||||
os.path.getsize, file_path
|
||||
)
|
||||
return 0
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error checking file size for %s: %s", file_path, e)
|
||||
return 0
|
||||
|
||||
async def _rotate_history(self) -> None:
|
||||
try:
|
||||
_LOGGER.debug("Starting history rotation for %s", self._history_file)
|
||||
await self._rotate_history_files()
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error rotating history: %s", e)
|
||||
_LOGGER.debug(traceback.format_exc())
|
||||
|
||||
async def _rotate_history_files(self) -> None:
|
||||
"""Rotate history files with size validation."""
|
||||
try:
|
||||
if await self._file_exists(self._history_file):
|
||||
current_size = await self._check_file_size(self._history_file)
|
||||
|
||||
if current_size > MAX_HISTORY_FILE_SIZE:
|
||||
_LOGGER.info(
|
||||
"Rotating history file. Current size: %d, Max: %d",
|
||||
current_size, MAX_HISTORY_FILE_SIZE,
|
||||
)
|
||||
|
||||
archive_file = os.path.join(
|
||||
self._history_dir,
|
||||
f"{self.normalized_name}_history_{dt_util.utcnow().strftime('%Y%m%d_%H%M%S')}.json",
|
||||
)
|
||||
|
||||
await self.hass.async_add_executor_job(
|
||||
_assert_not_symlink, self._history_file
|
||||
)
|
||||
await self.hass.async_add_executor_job(
|
||||
shutil.move, self._history_file, archive_file
|
||||
)
|
||||
|
||||
async with AsyncFileHandler(self._history_file, "w") as f:
|
||||
await f.write(
|
||||
json.dumps(
|
||||
self._conversation_history[
|
||||
-self.max_history_size :
|
||||
],
|
||||
indent=2,
|
||||
)
|
||||
)
|
||||
|
||||
_LOGGER.info("History file rotated to: %s", archive_file)
|
||||
|
||||
# Clean up old archive files, keep only MAX_ARCHIVE_FILES
|
||||
await self._cleanup_archives()
|
||||
except Exception as e:
|
||||
_LOGGER.error("History rotation failed: %s", e)
|
||||
_LOGGER.debug(traceback.format_exc())
|
||||
|
||||
async def _cleanup_archives(self) -> None:
|
||||
"""Remove old archive files beyond MAX_ARCHIVE_FILES."""
|
||||
try:
|
||||
prefix = f"{self.normalized_name}_history_"
|
||||
|
||||
def find_archives():
|
||||
archives = []
|
||||
for f in os.listdir(self._history_dir):
|
||||
if f.startswith(prefix) and f.endswith(".json") and f != os.path.basename(self._history_file):
|
||||
archives.append(os.path.join(self._history_dir, f))
|
||||
archives.sort()
|
||||
return archives
|
||||
|
||||
archives = await self.hass.async_add_executor_job(find_archives)
|
||||
if len(archives) > MAX_ARCHIVE_FILES:
|
||||
for old_file in archives[:-MAX_ARCHIVE_FILES]:
|
||||
await self.hass.async_add_executor_job(
|
||||
_assert_not_symlink, old_file
|
||||
)
|
||||
await self.hass.async_add_executor_job(os.remove, old_file)
|
||||
_LOGGER.debug("Removed old archive: %s", old_file)
|
||||
except Exception as e:
|
||||
_LOGGER.warning("Archive cleanup error: %s", e)
|
||||
|
||||
async def _migrate_history_from_txt_to_json(self) -> None:
|
||||
"""Migrate old .txt history to .json format."""
|
||||
try:
|
||||
old_history_file = os.path.join(
|
||||
self._history_dir, f"{self.normalized_name}_history.txt"
|
||||
)
|
||||
|
||||
if not await self._file_exists(old_history_file):
|
||||
return
|
||||
|
||||
# Skip migration if JSON history already has entries
|
||||
if self._conversation_history:
|
||||
_LOGGER.debug(
|
||||
"JSON history already has %d entries for %s, skipping txt migration",
|
||||
len(self._conversation_history), self.instance_name,
|
||||
)
|
||||
return
|
||||
|
||||
_LOGGER.info(
|
||||
"Found old history file for %s, migrating to JSON", self.instance_name
|
||||
)
|
||||
|
||||
history_entries = []
|
||||
async with AsyncFileHandler(old_history_file, "r") as f:
|
||||
content = await f.read()
|
||||
|
||||
for line in content.split("\n"):
|
||||
if not line or line.startswith("History initialized at:"):
|
||||
continue
|
||||
try:
|
||||
parts = line.split(": ", 1)
|
||||
if len(parts) != 2:
|
||||
continue
|
||||
timestamp = parts[0]
|
||||
content_parts = parts[1].split(" - ")
|
||||
if len(content_parts) != 2:
|
||||
continue
|
||||
question = content_parts[0].replace("Question: ", "")
|
||||
response = content_parts[1].replace("Response: ", "")
|
||||
history_entries.append(
|
||||
{
|
||||
"timestamp": timestamp,
|
||||
"question": question,
|
||||
"response": response,
|
||||
}
|
||||
)
|
||||
except Exception as e:
|
||||
_LOGGER.warning("Error parsing history line: %s. Error: %s", line, e)
|
||||
continue
|
||||
|
||||
if history_entries:
|
||||
async with AsyncFileHandler(self._history_file, "w") as f:
|
||||
await f.write(json.dumps(history_entries, indent=2))
|
||||
|
||||
backup_file = old_history_file + ".backup"
|
||||
await self.hass.async_add_executor_job(
|
||||
shutil.move, old_history_file, backup_file
|
||||
)
|
||||
|
||||
_LOGGER.info(
|
||||
"Migrated %d entries from txt to JSON for %s. Old file: %s",
|
||||
len(history_entries), self.instance_name, backup_file,
|
||||
)
|
||||
|
||||
self._conversation_history = history_entries
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error during history migration for %s: %s", self.instance_name, e)
|
||||
_LOGGER.debug(traceback.format_exc())
|
||||
|
||||
async def async_clear_history(self) -> None:
|
||||
"""Clear conversation history."""
|
||||
try:
|
||||
self._conversation_history = []
|
||||
if await self._file_exists(self._history_file):
|
||||
await self.hass.async_add_executor_job(
|
||||
_assert_not_symlink, self._history_file
|
||||
)
|
||||
await self.hass.async_add_executor_job(os.remove, self._history_file)
|
||||
_LOGGER.info("History for %s cleared", self.instance_name)
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error clearing history: %s", e)
|
||||
_LOGGER.debug(traceback.format_exc())
|
||||
|
||||
async def async_get_history(
|
||||
self,
|
||||
limit: int | None = None,
|
||||
filter_model: str | None = None,
|
||||
start_date: str | None = None,
|
||||
include_metadata: bool = False,
|
||||
sort_order: str = "newest",
|
||||
default_model: str = "",
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Get conversation history with optional filtering and sorting."""
|
||||
try:
|
||||
history = self._conversation_history.copy()
|
||||
|
||||
if filter_model:
|
||||
history = [
|
||||
entry for entry in history if entry.get("model") == filter_model
|
||||
]
|
||||
|
||||
if start_date:
|
||||
try:
|
||||
start_dt = datetime.fromisoformat(
|
||||
start_date.replace("Z", "+00:00")
|
||||
)
|
||||
history = [
|
||||
entry
|
||||
for entry in history
|
||||
if datetime.fromisoformat(
|
||||
entry["timestamp"].replace("Z", "+00:00")
|
||||
)
|
||||
>= start_dt
|
||||
]
|
||||
except (ValueError, KeyError) as e:
|
||||
_LOGGER.warning("Invalid start_date format: %s. Error: %s", start_date, e)
|
||||
|
||||
if sort_order == "oldest":
|
||||
history.sort(key=lambda x: x.get("timestamp", ""))
|
||||
else:
|
||||
history.sort(key=lambda x: x.get("timestamp", ""), reverse=True)
|
||||
|
||||
# Clamp limit to ABSOLUTE_MAX_HISTORY_SIZE to prevent pathological
|
||||
# caller requests from producing multi-MB service payloads.
|
||||
if limit and limit > 0:
|
||||
effective_limit = min(int(limit), ABSOLUTE_MAX_HISTORY_SIZE)
|
||||
history = history[:effective_limit]
|
||||
|
||||
if include_metadata:
|
||||
enriched = []
|
||||
for entry in history:
|
||||
enriched_entry = dict(entry)
|
||||
enriched_entry["metadata"] = {
|
||||
"entry_size": len(str(entry)),
|
||||
"question_length": len(entry.get("question", "")),
|
||||
"response_length": len(entry.get("response", "")),
|
||||
"model_used": entry.get("model", default_model),
|
||||
"instance": self.instance_name,
|
||||
}
|
||||
enriched.append(enriched_entry)
|
||||
return enriched
|
||||
|
||||
return history
|
||||
except Exception as e:
|
||||
_LOGGER.error("Error getting history: %s", e)
|
||||
return []
|
||||
|
||||
def get_limited_history(self, max_display: int = 5) -> dict[str, Any]:
|
||||
"""Get limited conversation history for sensor attributes.
|
||||
|
||||
Returns last `max_display` entries with truncated text for HA state.
|
||||
"""
|
||||
recent = self._conversation_history[-max_display:]
|
||||
limited_history = [
|
||||
{
|
||||
"timestamp": entry["timestamp"],
|
||||
"question": self._truncate_text(entry["question"], 4096),
|
||||
"response": self._truncate_text(entry["response"], 4096),
|
||||
}
|
||||
for entry in recent
|
||||
]
|
||||
|
||||
return {
|
||||
"entries": limited_history,
|
||||
"info": {
|
||||
"total_entries": len(self._conversation_history),
|
||||
"displayed_entries": len(limited_history),
|
||||
},
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _truncate_text(text: str, max_length: int = MAX_ATTRIBUTE_SIZE) -> str:
|
||||
"""Safely truncate text to maximum length with indicator."""
|
||||
if not text:
|
||||
return ""
|
||||
if len(text) <= max_length:
|
||||
return text
|
||||
return text[:max_length] + TRUNCATION_INDICATOR
|
||||
|
After Width: | Height: | Size: 121 KiB |
|
After Width: | Height: | Size: 351 KiB |
|
After Width: | Height: | Size: 87 KiB |
|
After Width: | Height: | Size: 257 KiB |
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 117 KiB |
|
Before Width: | Height: | Size: 45 KiB After Width: | Height: | Size: 325 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 86 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 259 KiB |
@@ -2,7 +2,6 @@
|
||||
"domain": "ha_text_ai",
|
||||
"name": "HA Text AI",
|
||||
"after_dependencies": ["http"],
|
||||
"bluetooth": [],
|
||||
"codeowners": ["@smkrv"],
|
||||
"config_flow": true,
|
||||
"dependencies": [],
|
||||
@@ -11,18 +10,10 @@
|
||||
"iot_class": "cloud_polling",
|
||||
"issue_tracker": "https://github.com/smkrv/ha-text-ai/issues",
|
||||
"loggers": ["custom_components.ha_text_ai"],
|
||||
"mqtt": [],
|
||||
"quality_scale": "silver",
|
||||
"requirements": [
|
||||
"openai>=1.12.0",
|
||||
"anthropic>=0.8.0",
|
||||
"aiohttp>=3.8.0",
|
||||
"async-timeout>=4.0.0",
|
||||
"certifi>=2024.2.2"
|
||||
"aiofiles>=23.0.0,<25.0.0",
|
||||
"google-genai>=1.16.0,<2.0.0"
|
||||
],
|
||||
"single_config_entry": false,
|
||||
"ssdp": [],
|
||||
"usb": [],
|
||||
"version": "2.0.4-beta",
|
||||
"zeroconf": []
|
||||
"version": "2.5.1"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
"""
|
||||
Metrics management for HA Text AI integration.
|
||||
|
||||
@license: MIT (https://opensource.org/licenses/MIT)
|
||||
@author: SMKRV
|
||||
@github: https://github.com/smkrv/ha-text-ai
|
||||
@source: https://github.com/smkrv/ha-text-ai
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import traceback
|
||||
from typing import Any
|
||||
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
DEFAULT_METRICS: dict[str, Any] = {
|
||||
"total_tokens": 0,
|
||||
"prompt_tokens": 0,
|
||||
"completion_tokens": 0,
|
||||
"successful_requests": 0,
|
||||
"failed_requests": 0,
|
||||
"total_errors": 0,
|
||||
"average_latency": 0,
|
||||
"max_latency": 0,
|
||||
"min_latency": 0,
|
||||
}
|
||||
|
||||
class MetricsManager:
|
||||
"""Manages performance metrics for an instance."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
hass: HomeAssistant,
|
||||
instance_name: str,
|
||||
metrics_file: str,
|
||||
) -> None:
|
||||
self.hass = hass
|
||||
self.instance_name = instance_name
|
||||
self._metrics_file = metrics_file
|
||||
self._performance_metrics: dict[str, Any] = DEFAULT_METRICS.copy()
|
||||
|
||||
@property
|
||||
def metrics(self) -> dict[str, Any]:
|
||||
return self._performance_metrics
|
||||
|
||||
async def async_initialize(self) -> None:
|
||||
"""Load metrics from storage or create defaults."""
|
||||
loaded = await self._load_metrics()
|
||||
self._performance_metrics = loaded or DEFAULT_METRICS.copy()
|
||||
|
||||
async def _load_metrics(self) -> dict[str, Any] | None:
|
||||
try:
|
||||
exists = await self.hass.async_add_executor_job(
|
||||
os.path.exists, self._metrics_file
|
||||
)
|
||||
if exists:
|
||||
def read_metrics():
|
||||
with open(self._metrics_file, "r") as f:
|
||||
try:
|
||||
return json.load(f)
|
||||
except json.JSONDecodeError:
|
||||
_LOGGER.warning("Metrics file corrupted, creating new")
|
||||
return None
|
||||
|
||||
return await self.hass.async_add_executor_job(read_metrics)
|
||||
except Exception as e:
|
||||
_LOGGER.warning("Failed to load metrics: %s", e)
|
||||
return None
|
||||
|
||||
async def _save_metrics(self) -> None:
|
||||
try:
|
||||
def write_metrics():
|
||||
with open(self._metrics_file, "w") as f:
|
||||
json.dump(self._performance_metrics, f)
|
||||
|
||||
await self.hass.async_add_executor_job(write_metrics)
|
||||
except Exception as e:
|
||||
_LOGGER.warning("Failed to save metrics: %s", e)
|
||||
|
||||
async def update_metrics(self, latency: float, response: dict) -> None:
|
||||
"""Update performance metrics after a successful request."""
|
||||
metrics = self._performance_metrics
|
||||
tokens = response.get("tokens", {})
|
||||
|
||||
metrics["total_tokens"] += tokens.get("total", 0)
|
||||
metrics["prompt_tokens"] += tokens.get("prompt", 0)
|
||||
metrics["completion_tokens"] += tokens.get("completion", 0)
|
||||
metrics["successful_requests"] += 1
|
||||
|
||||
metrics["average_latency"] = (
|
||||
(metrics["average_latency"] * (metrics["successful_requests"] - 1) + latency)
|
||||
/ metrics["successful_requests"]
|
||||
)
|
||||
metrics["max_latency"] = max(metrics["max_latency"], latency)
|
||||
if metrics["min_latency"] == 0:
|
||||
metrics["min_latency"] = latency
|
||||
else:
|
||||
metrics["min_latency"] = min(metrics["min_latency"], latency)
|
||||
|
||||
await self._save_metrics()
|
||||
|
||||
async def get_current_metrics(self) -> dict[str, Any]:
|
||||
"""Get current performance metrics."""
|
||||
return self._performance_metrics.copy()
|
||||
|
||||
async def handle_error(
|
||||
self,
|
||||
error: Exception,
|
||||
model: str,
|
||||
) -> dict[str, Any]:
|
||||
"""Record an error in metrics and return error details."""
|
||||
self._performance_metrics["total_errors"] += 1
|
||||
self._performance_metrics["failed_requests"] += 1
|
||||
await self._save_metrics()
|
||||
|
||||
error_msg = str(error)
|
||||
# Strip URLs, API keys, tokens, and query parameters from error messages.
|
||||
# Patterns use word boundaries and explicit length bounds so that
|
||||
# overly greedy matches don't accidentally swallow adjacent text.
|
||||
error_msg = re.sub(r'https?://\S+', '[URL]', error_msg)
|
||||
error_msg = re.sub(r'[?&]key=[^\s&]+', '?key=***', error_msg)
|
||||
# Google API key: fixed prefix + 30+ url-safe chars, bounded by non-key char.
|
||||
error_msg = re.sub(
|
||||
r'AIza[A-Za-z0-9_\-]{30,}(?=[^A-Za-z0-9_\-]|$)', '***', error_msg
|
||||
)
|
||||
# Anthropic / OpenAI / DeepSeek format: "sk-..." (anchors on word boundary).
|
||||
error_msg = re.sub(r'\bsk-[A-Za-z0-9_\-]{20,}\b', '***', error_msg)
|
||||
# Bearer tokens: header-style and JSON-embedded ("Bearer xxx").
|
||||
error_msg = re.sub(r'[Bb]earer\s+[A-Za-z0-9_\-\.=]+', 'Bearer ***', error_msg)
|
||||
# x-api-key header in any case, both raw and JSON-serialized forms.
|
||||
error_msg = re.sub(
|
||||
r'"?x-api-key"?\s*[:=]\s*"?[A-Za-z0-9_\-\.]+"?',
|
||||
'x-api-key: ***',
|
||||
error_msg,
|
||||
flags=re.IGNORECASE,
|
||||
)
|
||||
if len(error_msg) > 256:
|
||||
error_msg = error_msg[:256] + "..."
|
||||
|
||||
error_details: dict[str, Any] = {
|
||||
"timestamp": dt_util.utcnow().isoformat(),
|
||||
"model": model,
|
||||
"instance": self.instance_name,
|
||||
"error_message": error_msg,
|
||||
"error_type": type(error).__name__,
|
||||
"traceback": traceback.format_exc()
|
||||
if _LOGGER.isEnabledFor(logging.DEBUG)
|
||||
else None,
|
||||
}
|
||||
|
||||
error_mapping = {
|
||||
HomeAssistantError: {"is_ha_error": True},
|
||||
ConnectionError: {"is_connection_error": True},
|
||||
TimeoutError: {"is_timeout": True},
|
||||
PermissionError: {"is_permission_denied": True},
|
||||
ValueError: {"is_validation_error": True},
|
||||
}
|
||||
|
||||
for error_type, error_flags in error_mapping.items():
|
||||
if isinstance(error, error_type):
|
||||
error_details.update(error_flags)
|
||||
break
|
||||
|
||||
_LOGGER.error("AI Processing Error: %s", error_details)
|
||||
if _LOGGER.isEnabledFor(logging.DEBUG):
|
||||
_LOGGER.debug("Full Error Traceback: %s", error_details.get("traceback"))
|
||||
|
||||
return error_details
|
||||
@@ -0,0 +1,93 @@
|
||||
"""
|
||||
Provider registry for HA Text AI integration.
|
||||
|
||||
Centralizes provider-specific configuration to avoid dispatch duplication
|
||||
across __init__.py, config_flow.py, and api_client.py.
|
||||
|
||||
@license: MIT (https://opensource.org/licenses/MIT)
|
||||
@author: SMKRV
|
||||
@github: https://github.com/smkrv/ha-text-ai
|
||||
@source: https://github.com/smkrv/ha-text-ai
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from .const import (
|
||||
API_PROVIDER_OPENAI,
|
||||
API_PROVIDER_ANTHROPIC,
|
||||
API_PROVIDER_DEEPSEEK,
|
||||
API_PROVIDER_GEMINI,
|
||||
DEFAULT_MODEL,
|
||||
DEFAULT_ANTHROPIC_MODEL,
|
||||
DEFAULT_DEEPSEEK_MODEL,
|
||||
DEFAULT_GEMINI_MODEL,
|
||||
DEFAULT_OPENAI_ENDPOINT,
|
||||
DEFAULT_ANTHROPIC_ENDPOINT,
|
||||
DEFAULT_DEEPSEEK_ENDPOINT,
|
||||
DEFAULT_GEMINI_ENDPOINT,
|
||||
)
|
||||
|
||||
PROVIDER_REGISTRY: dict[str, dict[str, Any]] = {
|
||||
API_PROVIDER_OPENAI: {
|
||||
"default_model": DEFAULT_MODEL,
|
||||
"default_endpoint": DEFAULT_OPENAI_ENDPOINT,
|
||||
"auth_header": "Authorization",
|
||||
"auth_prefix": "Bearer ",
|
||||
"check_path": "/models",
|
||||
},
|
||||
API_PROVIDER_ANTHROPIC: {
|
||||
"default_model": DEFAULT_ANTHROPIC_MODEL,
|
||||
"default_endpoint": DEFAULT_ANTHROPIC_ENDPOINT,
|
||||
"auth_header": "x-api-key",
|
||||
"auth_prefix": "",
|
||||
"check_path": "/v1/models",
|
||||
"extra_headers": {
|
||||
"anthropic-version": "2023-06-01",
|
||||
},
|
||||
},
|
||||
API_PROVIDER_DEEPSEEK: {
|
||||
"default_model": DEFAULT_DEEPSEEK_MODEL,
|
||||
"default_endpoint": DEFAULT_DEEPSEEK_ENDPOINT,
|
||||
"auth_header": "Authorization",
|
||||
"auth_prefix": "Bearer ",
|
||||
"check_path": "/models",
|
||||
},
|
||||
API_PROVIDER_GEMINI: {
|
||||
"default_model": DEFAULT_GEMINI_MODEL,
|
||||
"default_endpoint": DEFAULT_GEMINI_ENDPOINT,
|
||||
"auth_header": "Authorization",
|
||||
"auth_prefix": "Bearer ",
|
||||
"check_path": None, # Gemini does not support /models check
|
||||
},
|
||||
}
|
||||
|
||||
def get_provider_config(provider: str) -> dict[str, Any]:
|
||||
"""Get full provider configuration.
|
||||
|
||||
Raises ValueError for unknown providers to avoid sending
|
||||
credentials to the wrong endpoint.
|
||||
"""
|
||||
if provider not in PROVIDER_REGISTRY:
|
||||
raise ValueError(f"Unknown API provider: {provider}")
|
||||
return PROVIDER_REGISTRY[provider]
|
||||
|
||||
def get_default_endpoint(provider: str) -> str:
|
||||
"""Get default API endpoint for a provider."""
|
||||
return get_provider_config(provider)["default_endpoint"]
|
||||
|
||||
def get_default_model(provider: str) -> str:
|
||||
"""Get default model for a provider."""
|
||||
return get_provider_config(provider)["default_model"]
|
||||
|
||||
def build_auth_headers(provider: str, api_key: str) -> dict[str, str]:
|
||||
"""Build authentication headers for a provider."""
|
||||
config = get_provider_config(provider)
|
||||
headers = {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json",
|
||||
}
|
||||
headers[config["auth_header"]] = f"{config['auth_prefix']}{api_key}"
|
||||
if "extra_headers" in config:
|
||||
headers.update(config["extra_headers"])
|
||||
return headers
|
||||
@@ -1,22 +1,23 @@
|
||||
"""
|
||||
Sensor platform for HA Text AI.
|
||||
|
||||
@license: CC BY-NC-SA 4.0 International
|
||||
@license: MIT (https://opensource.org/licenses/MIT)
|
||||
@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 math
|
||||
from typing import Any, Dict
|
||||
|
||||
from typing import Any
|
||||
from homeassistant.components.sensor import (
|
||||
SensorEntity,
|
||||
SensorEntityDescription,
|
||||
)
|
||||
from homeassistant.config_entries import ConfigEntry
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.helpers.device_registry import DeviceInfo
|
||||
from homeassistant.helpers.device_registry import DeviceEntryType, DeviceInfo
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.typing import StateType
|
||||
from homeassistant.helpers.update_coordinator import CoordinatorEntity
|
||||
@@ -43,10 +44,8 @@ from .const import (
|
||||
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,
|
||||
@@ -67,12 +66,18 @@ from .const import (
|
||||
ENTITY_ICON_PROCESSING,
|
||||
DEFAULT_NAME_PREFIX,
|
||||
CONF_MAX_HISTORY_SIZE,
|
||||
VERSION,
|
||||
)
|
||||
|
||||
from .coordinator import HATextAICoordinator
|
||||
from .utils import safe_log_data
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# HA Recorder limit is 16384 bytes for state_attributes.
|
||||
# Budget per field to stay well within the limit.
|
||||
_ATTR_TEXT_LIMIT = 2048
|
||||
_ATTR_PROMPT_LIMIT = 512
|
||||
|
||||
async def async_setup_entry(
|
||||
hass: HomeAssistant,
|
||||
@@ -80,23 +85,23 @@ async def async_setup_entry(
|
||||
async_add_entities: AddEntitiesCallback,
|
||||
) -> None:
|
||||
"""Set up the HA Text AI sensor."""
|
||||
_LOGGER.debug(f"Starting sensor setup for entry: {entry.entry_id}")
|
||||
_LOGGER.debug("Starting sensor setup for entry: %s", entry.entry_id)
|
||||
|
||||
try:
|
||||
coordinator = hass.data[DOMAIN][entry.entry_id]
|
||||
_LOGGER.debug(f"Found coordinator for entry {entry.entry_id}")
|
||||
_LOGGER.debug("Found coordinator for entry %s", entry.entry_id)
|
||||
|
||||
instance_name = coordinator.instance_name
|
||||
_LOGGER.debug(f"Setting up sensor with instance: {instance_name}")
|
||||
_LOGGER.debug("Setting up sensor with instance: %s", instance_name)
|
||||
|
||||
sensor = HATextAISensor(coordinator, entry)
|
||||
_LOGGER.debug(f"Created sensor instance: {sensor.entity_id}")
|
||||
_LOGGER.debug("Created sensor instance: %s", sensor.entity_id)
|
||||
|
||||
async_add_entities([sensor], True)
|
||||
_LOGGER.debug(f"Added sensor entity: {sensor.entity_id}")
|
||||
_LOGGER.debug("Added sensor entity: %s", sensor.entity_id)
|
||||
|
||||
except Exception as err:
|
||||
_LOGGER.exception(f"Error setting up sensor: {err}")
|
||||
_LOGGER.exception("Error setting up sensor: %s", err)
|
||||
raise
|
||||
|
||||
class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||
@@ -110,7 +115,7 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||
config_entry: ConfigEntry,
|
||||
) -> None:
|
||||
"""Initialize the sensor."""
|
||||
_LOGGER.debug(f"Initializing sensor with config entry: {config_entry.data}")
|
||||
_LOGGER.debug("Initializing sensor with config entry: %s", safe_log_data(dict(config_entry.data)))
|
||||
|
||||
super().__init__(coordinator)
|
||||
|
||||
@@ -118,19 +123,20 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||
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}")
|
||||
_LOGGER.debug("Instance name: %s", self._instance_name)
|
||||
_LOGGER.debug("Normalized name: %s", self._normalized_name)
|
||||
|
||||
self._conversation_history = []
|
||||
self._system_prompt = None
|
||||
|
||||
self._attr_name = f"HA Text AI {self._instance_name}"
|
||||
self._attr_has_entity_name = True
|
||||
self._attr_name = 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 = config_entry.entry_id
|
||||
|
||||
_LOGGER.debug(f"Created sensor with entity_id: {self.entity_id}")
|
||||
_LOGGER.debug(f"Sensor name: {self._attr_name}")
|
||||
_LOGGER.debug(f"Unique ID: {self._attr_unique_id}")
|
||||
_LOGGER.debug("Created sensor with entity_id: %s", self.entity_id)
|
||||
_LOGGER.debug("Sensor name: %s", self._attr_name)
|
||||
_LOGGER.debug("Unique ID: %s", self._attr_unique_id)
|
||||
|
||||
self.entity_description = SensorEntityDescription(
|
||||
key=f"ha_text_ai_{self._normalized_name.lower()}",
|
||||
@@ -153,11 +159,13 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||
name=self._attr_name,
|
||||
manufacturer="Community",
|
||||
model=f"{model} ({api_provider} provider)",
|
||||
sw_version="1.0.0",
|
||||
sw_version=VERSION,
|
||||
entry_type=DeviceEntryType.SERVICE,
|
||||
)
|
||||
|
||||
_LOGGER.debug(
|
||||
f"Initialized sensor: {self.entity_id} for instance: {self._instance_name}"
|
||||
"Initialized sensor: %s for instance: %s",
|
||||
self.entity_id, self._instance_name,
|
||||
)
|
||||
|
||||
@property
|
||||
@@ -176,14 +184,31 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||
return None
|
||||
return value
|
||||
|
||||
def _sanitize_attributes(self, attributes: Dict[str, Any]) -> Dict[str, Any]:
|
||||
def _sanitize_attributes(self, attributes: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Sanitize all attributes for JSON serialization."""
|
||||
return {
|
||||
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("Metrics for %s: %s", self.entity_id, metrics_values)
|
||||
|
||||
return sanitized
|
||||
|
||||
@property
|
||||
def native_value(self) -> StateType:
|
||||
"""Return the native value of the sensor."""
|
||||
@@ -205,75 +230,70 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||
return ENTITY_ICON
|
||||
|
||||
@property
|
||||
def extra_state_attributes(self) -> Dict[str, Any]:
|
||||
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: self._error_count,
|
||||
ATTR_LAST_ERROR: self._last_error,
|
||||
ATTR_API_PROVIDER: self._config_entry.data.get(CONF_API_PROVIDER, "Unknown"),
|
||||
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"),
|
||||
ATTR_SYSTEM_PROMPT: (data.get("system_prompt", "")[:_ATTR_PROMPT_LIMIT]
|
||||
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: data.get("uptime", 0),
|
||||
ATTR_UPTIME: round(data.get("uptime", 0), 2),
|
||||
ATTR_HISTORY_SIZE: data.get("history_size", 0),
|
||||
ATTR_CONVERSATION_HISTORY: data.get("conversation_history", []),
|
||||
}
|
||||
|
||||
# Add metrics
|
||||
metrics = data.get("metrics", {})
|
||||
if isinstance(metrics, dict):
|
||||
self._metrics = metrics
|
||||
attributes.update(
|
||||
# Conversation history preview (compact: last 3, truncated to 256 chars).
|
||||
# Full history is available via ha_text_ai.get_history service.
|
||||
conversation_history = data.get("conversation_history", [])
|
||||
if conversation_history:
|
||||
preview = conversation_history[-3:]
|
||||
attributes["conversation_history"] = [
|
||||
{
|
||||
METRIC_TOTAL_TOKENS: metrics.get("total_tokens", 0),
|
||||
METRIC_PROMPT_TOKENS: metrics.get("prompt_tokens", 0),
|
||||
METRIC_COMPLETION_TOKENS: metrics.get("completion_tokens", 0),
|
||||
METRIC_SUCCESSFUL_REQUESTS: metrics.get(
|
||||
"successful_requests", 0
|
||||
),
|
||||
METRIC_FAILED_REQUESTS: metrics.get("failed_requests", 0),
|
||||
METRIC_AVERAGE_LATENCY: metrics.get("average_latency", 0),
|
||||
METRIC_MAX_LATENCY: metrics.get("max_latency", 0),
|
||||
METRIC_MIN_LATENCY: metrics.get("min_latency", float("inf")),
|
||||
"timestamp": entry["timestamp"],
|
||||
"question": entry["question"][:256],
|
||||
"response": entry["response"][:256],
|
||||
}
|
||||
)
|
||||
|
||||
# Add last response
|
||||
last_response = data.get("last_response", {})
|
||||
if isinstance(last_response, dict):
|
||||
self._last_response = last_response
|
||||
attributes.update(
|
||||
{
|
||||
ATTR_RESPONSE: last_response.get("response", ""),
|
||||
ATTR_QUESTION: last_response.get("question", ""),
|
||||
"last_model": last_response.get("model", ""),
|
||||
"last_timestamp": last_response.get("timestamp", ""),
|
||||
"last_error": last_response.get("error"),
|
||||
}
|
||||
)
|
||||
|
||||
# Add performance metrics if available
|
||||
if ATTR_PERFORMANCE_METRICS in data:
|
||||
attributes[ATTR_PERFORMANCE_METRICS] = data[
|
||||
ATTR_PERFORMANCE_METRICS
|
||||
for entry in preview
|
||||
]
|
||||
|
||||
# Add API version if available
|
||||
if ATTR_API_VERSION in data:
|
||||
attributes[ATTR_API_VERSION] = data[ATTR_API_VERSION]
|
||||
# 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", 0) or None,
|
||||
})
|
||||
|
||||
# Last response handling
|
||||
last_response = data.get("last_response", {})
|
||||
if isinstance(last_response, dict):
|
||||
attributes.update({
|
||||
ATTR_RESPONSE: last_response.get("response", "")[:_ATTR_TEXT_LIMIT],
|
||||
ATTR_QUESTION: last_response.get("question", "")[:_ATTR_TEXT_LIMIT],
|
||||
"last_model": last_response.get("model", ""),
|
||||
"last_timestamp": last_response.get("timestamp", ""),
|
||||
"last_error": (last_response.get("error", "")[:_ATTR_TEXT_LIMIT]
|
||||
if last_response.get("error") else None),
|
||||
})
|
||||
|
||||
return self._sanitize_attributes(attributes)
|
||||
|
||||
@@ -285,7 +305,7 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||
"""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")
|
||||
_LOGGER.debug("Entity %s added to Home Assistant", self.entity_id)
|
||||
|
||||
def _handle_coordinator_update(self) -> None:
|
||||
"""Handle updated data from the coordinator."""
|
||||
@@ -293,12 +313,18 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||
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}")
|
||||
_LOGGER.warning("No data available for %s", 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("Updated metrics for %s: %s", 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")
|
||||
@@ -321,8 +347,8 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||
self._last_update = dt_util.utcnow()
|
||||
|
||||
_LOGGER.debug(
|
||||
f"Updated {self.entity_id} state to: {self._current_state} "
|
||||
f"(available: {self.available})"
|
||||
"Updated %s state to: %s (available: %s)",
|
||||
self.entity_id, self._current_state, self.available,
|
||||
)
|
||||
|
||||
except Exception as err:
|
||||
|
||||
@@ -3,6 +3,7 @@ ask_question:
|
||||
description: >-
|
||||
Send a question to the AI model and receive a detailed response.
|
||||
The response will be stored in the conversation history and can be retrieved later.
|
||||
This service now returns response data directly, eliminating the need to read from sensors.
|
||||
fields:
|
||||
instance:
|
||||
name: Instance
|
||||
@@ -63,16 +64,43 @@ ask_question:
|
||||
|
||||
max_tokens:
|
||||
name: Max Tokens
|
||||
description: Maximum length of the response (1-4096 tokens)
|
||||
description: Maximum length of the response (tokens)
|
||||
required: false
|
||||
default: 1000
|
||||
selector:
|
||||
number:
|
||||
min: 1
|
||||
max: 4096
|
||||
max: 100000
|
||||
step: 1
|
||||
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
|
||||
|
||||
disable_thinking:
|
||||
name: Disable Thinking
|
||||
description: >-
|
||||
Disable model thinking/reasoning for this request.
|
||||
Overrides the integration-level setting when provided.
|
||||
required: false
|
||||
selector:
|
||||
boolean: {}
|
||||
|
||||
clear_history:
|
||||
name: Clear History
|
||||
description: >-
|
||||
@@ -134,7 +162,7 @@ get_history:
|
||||
required: false
|
||||
default: false
|
||||
selector:
|
||||
boolean:
|
||||
boolean: {}
|
||||
|
||||
sort_order:
|
||||
name: Sort Order
|
||||
|
||||
@@ -0,0 +1,336 @@
|
||||
{
|
||||
"config": {
|
||||
"step": {
|
||||
"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)",
|
||||
"allow_local_network": "Allow local network endpoints (for self-hosted proxies)",
|
||||
"disable_thinking": "Disable thinking/reasoning mode (Qwen /no_think, strips think blocks, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
},
|
||||
"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)",
|
||||
"allow_local_network": "Allow local network endpoints (for self-hosted proxies)",
|
||||
"disable_thinking": "Disable thinking/reasoning mode (Qwen /no_think, strips think blocks, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"history_storage_error": "Failed to initialize history storage. Check permissions.",
|
||||
"history_rotation_error": "Error during history file rotation.",
|
||||
"history_file_access_error": "Cannot access history storage directory.",
|
||||
"name_exists": "An instance with this name already exists",
|
||||
"invalid_name": "Invalid instance name",
|
||||
"invalid_auth": "Authentication failed - check your API key",
|
||||
"api_key_required": "API key is required when changing provider or endpoint",
|
||||
"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",
|
||||
"name_too_long": "Name must be 50 characters or less"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "Instance already configured"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "Select Provider",
|
||||
"description": "Choose the AI provider for this instance. The integration will reload after saving changes.",
|
||||
"data": {
|
||||
"api_provider": "API Provider"
|
||||
}
|
||||
},
|
||||
"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)",
|
||||
"allow_local_network": "Allow local network endpoints (for self-hosted proxies)",
|
||||
"disable_thinking": "Disable thinking/reasoning mode (Qwen /no_think, strips think blocks, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"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."
|
||||
},
|
||||
"disable_thinking": {
|
||||
"name": "Disable Thinking",
|
||||
"description": "Disable model thinking/reasoning for this request. Overrides the integration-level setting."
|
||||
}
|
||||
}
|
||||
},
|
||||
"clear_history": {
|
||||
"name": "Clear History",
|
||||
"description": "Delete all stored questions and responses from the conversation history",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Instance",
|
||||
"description": "Name of the HA Text AI instance to clear history for"
|
||||
}
|
||||
}
|
||||
},
|
||||
"get_history": {
|
||||
"name": "Get History",
|
||||
"description": "Retrieve conversation history with optional filtering and sorting",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Instance",
|
||||
"description": "Name of the HA Text AI instance to get history from"
|
||||
},
|
||||
"limit": {
|
||||
"name": "Limit",
|
||||
"description": "Number of conversations to return (1-100)"
|
||||
},
|
||||
"filter_model": {
|
||||
"name": "Filter Model",
|
||||
"description": "Filter conversations by specific AI model"
|
||||
},
|
||||
"start_date": {
|
||||
"name": "Start Date",
|
||||
"description": "Filter conversations starting from this date/time"
|
||||
},
|
||||
"include_metadata": {
|
||||
"name": "Include Metadata",
|
||||
"description": "Include additional information like tokens used, response time, etc."
|
||||
},
|
||||
"sort_order": {
|
||||
"name": "Sort Order",
|
||||
"description": "Sort order for results (newest or oldest first)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"set_system_prompt": {
|
||||
"name": "Set System Prompt",
|
||||
"description": "Set default system behavior instructions for all future conversations",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Instance",
|
||||
"description": "Name of the HA Text AI instance to set system prompt for"
|
||||
},
|
||||
"prompt": {
|
||||
"name": "System Prompt",
|
||||
"description": "Instructions that define how the AI should behave and respond"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"entity": {
|
||||
"sensor": {
|
||||
"ha_text_ai": {
|
||||
"name": "{name}",
|
||||
"state": {
|
||||
"ready": "Ready",
|
||||
"processing": "Processing",
|
||||
"error": "Error",
|
||||
"disconnected": "Disconnected",
|
||||
"rate_limited": "Rate Limited",
|
||||
"maintenance": "Maintenance",
|
||||
"initializing": "Initializing",
|
||||
"retrying": "Retrying"
|
||||
},
|
||||
"state_attributes": {
|
||||
"question": {
|
||||
"name": "Last Question"
|
||||
},
|
||||
"response": {
|
||||
"name": "Last Response"
|
||||
},
|
||||
"model": {
|
||||
"name": "Current Model"
|
||||
},
|
||||
"temperature": {
|
||||
"name": "Temperature"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "Max Tokens"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "System Prompt"
|
||||
},
|
||||
"response_time": {
|
||||
"name": "Last Response Time"
|
||||
},
|
||||
"total_responses": {
|
||||
"name": "Total Responses"
|
||||
},
|
||||
"error_count": {
|
||||
"name": "Error Count"
|
||||
},
|
||||
"last_error": {
|
||||
"name": "Last Error"
|
||||
},
|
||||
"api_status": {
|
||||
"name": "API Status"
|
||||
},
|
||||
"tokens_used": {
|
||||
"name": "Total Tokens Used"
|
||||
},
|
||||
"average_response_time": {
|
||||
"name": "Average Response Time"
|
||||
},
|
||||
"last_request_time": {
|
||||
"name": "Last Request Time"
|
||||
},
|
||||
"is_processing": {
|
||||
"name": "Processing Status"
|
||||
},
|
||||
"is_rate_limited": {
|
||||
"name": "Rate Limited Status"
|
||||
},
|
||||
"is_maintenance": {
|
||||
"name": "Maintenance Status"
|
||||
},
|
||||
"api_version": {
|
||||
"name": "API Version"
|
||||
},
|
||||
"endpoint_status": {
|
||||
"name": "Endpoint Status"
|
||||
},
|
||||
"performance_metrics": {
|
||||
"name": "Performance Metrics"
|
||||
},
|
||||
"history_size": {
|
||||
"name": "History Size"
|
||||
},
|
||||
"uptime": {
|
||||
"name": "Uptime"
|
||||
},
|
||||
"total_tokens": {
|
||||
"name": "Total Tokens"
|
||||
},
|
||||
"prompt_tokens": {
|
||||
"name": "Prompt Tokens"
|
||||
},
|
||||
"completion_tokens": {
|
||||
"name": "Completion Tokens"
|
||||
},
|
||||
"successful_requests": {
|
||||
"name": "Successful Requests"
|
||||
},
|
||||
"failed_requests": {
|
||||
"name": "Failed Requests"
|
||||
},
|
||||
"average_latency": {
|
||||
"name": "Average Latency"
|
||||
},
|
||||
"max_latency": {
|
||||
"name": "Maximum Latency"
|
||||
},
|
||||
"min_latency": {
|
||||
"name": "Minimum Latency"
|
||||
},
|
||||
"last_model": {
|
||||
"name": "Last Used Model"
|
||||
},
|
||||
"last_timestamp": {
|
||||
"name": "Last Response Time"
|
||||
},
|
||||
"instance_name": {
|
||||
"name": "Instance Name"
|
||||
},
|
||||
"normalized_name": {
|
||||
"name": "Normalized Name"
|
||||
},
|
||||
"last_error": {
|
||||
"name": "Last Error"
|
||||
},
|
||||
"conversation_history": {
|
||||
"name": "Conversation History"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,71 +2,112 @@
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "KI-Anbieter auswählen",
|
||||
"description": "Wählen Sie den KI-Dienstanbieter für diese Instanz aus.",
|
||||
"title": "Anbieter-Einstellungen",
|
||||
"description": "Geben Sie die Verbindungsdetails für Ihren gewählten AI-Anbieter an.",
|
||||
"data": {
|
||||
"api_provider": "API-Anbieter",
|
||||
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)"
|
||||
"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)",
|
||||
"allow_local_network": "Lokale Netzwerkendpunkte erlauben (für selbst gehostete Proxys)",
|
||||
"disable_thinking": "Thinking/Reasoning-Modus deaktivieren (Qwen /no_think, think-Blöcke entfernen, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "HA Text AI-Instanz konfigurieren",
|
||||
"description": "Richten Sie eine neue KI-Assistenteninstanz mit Ihrem ausgewählten Anbieter ein.",
|
||||
"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-Assistent', 'Claude-Helfer')",
|
||||
"name": "Instanzname (z. B. 'GPT Assistant', 'Claude Helper')",
|
||||
"api_key": "API-Schlüssel zur Authentifizierung",
|
||||
"model": "Zu verwendendes KI-Modell",
|
||||
"temperature": "Antwortkreativität (0-2, niedriger = fokussierter)",
|
||||
"max_tokens": "Maximale Antwortlänge (1-4096 Token)",
|
||||
"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": "Mindestzeit zwischen Anfragen (0,1-60 Sekunden)",
|
||||
"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 Konversationsverlaufs (1-100)"
|
||||
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)",
|
||||
"allow_local_network": "Lokale Netzwerkendpunkte erlauben (für selbst gehostete Proxys)",
|
||||
"disable_thinking": "Thinking/Reasoning-Modus deaktivieren (Qwen /no_think, think-Blöcke entfernen, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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 - überprüfen Sie Ihre Anmeldedaten",
|
||||
"api_key_required": "API-Schlüssel ist erforderlich, wenn Anbieter oder Endpunkt geändert wird",
|
||||
"invalid_api_key": "Ungültiger API-Schlüssel - bitte überprüfen Sie Ihre Anmeldeinformationen",
|
||||
"cannot_connect": "Verbindung zum API-Dienst fehlgeschlagen",
|
||||
"invalid_model": "Das ausgewählte Modell ist nicht verfügbar",
|
||||
"rate_limit": "Ratenlimit überschritten",
|
||||
"invalid_model": "Ausgewähltes Modell ist nicht verfügbar",
|
||||
"rate_limit": "Rate-Limit überschritten",
|
||||
"context_length": "Kontextlänge überschritten",
|
||||
"rate_limit_exceeded": "API-Ratenlimit überschritten",
|
||||
"maintenance": "Dienst befindet sich in der Wartung",
|
||||
"invalid_response": "Ungültige API-Antwort empfangen",
|
||||
"api_error": "Fehler im API-Dienst aufgetreten",
|
||||
"timeout": "Anfrage ist abgelaufen",
|
||||
"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": "Es ist ein unerwarteter Fehler aufgetreten",
|
||||
"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 maximal 50 Zeichen lang sein"
|
||||
"name_too_long": "Name darf höchstens 50 Zeichen lang sein"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "Instanz bereits konfiguriert"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "Instanzeinstellungen aktualisieren",
|
||||
"description": "Ändern Sie die Einstellungen für diese KI-Assistenteninstanz.",
|
||||
"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": {
|
||||
"model": "KI-Modell",
|
||||
"temperature": "Antwortkreativität (0-2)",
|
||||
"max_tokens": "Maximale Antwortlänge (1-4096)",
|
||||
"request_interval": "Mindestzeitraum zwischen Anfragen (0,1-60 Sekunden)",
|
||||
"context_messages": "Anzahl der vorherigen Nachrichten, die im Kontext enthalten sein sollen (1-20)",
|
||||
"max_history_size": "Maximale Größe des Konversationsverlaufs (1-100)"
|
||||
"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)",
|
||||
"allow_local_network": "Lokale Netzwerkendpunkte erlauben (für selbst gehostete Proxys)",
|
||||
"disable_thinking": "Thinking/Reasoning-Modus deaktivieren (Qwen /no_think, think-Blöcke entfernen, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"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": "Senden Sie eine Frage an das KI-Modell und erhalten Sie eine detaillierte Antwort. Die Antwort wird im Konversationsverlauf gespeichert und kann später abgerufen werden.",
|
||||
"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",
|
||||
@@ -74,43 +115,55 @@
|
||||
},
|
||||
"question": {
|
||||
"name": "Frage",
|
||||
"description": "Ihre Frage oder Aufforderung an den KI-Assistenten"
|
||||
"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": "Systemprompt",
|
||||
"description": "Optionaler Systemprompt, um den Kontext für diese spezielle Frage festzulegen"
|
||||
"name": "Systemaufforderung",
|
||||
"description": "Optionale Systemaufforderung zur Festlegung des Kontexts für diese spezifische Frage"
|
||||
},
|
||||
"model": {
|
||||
"name": "Modell",
|
||||
"description": "Wählen Sie das zu verwendende KI-Modell aus (optional, überschreibt die Standardeinstellung)"
|
||||
"description": "Wählen Sie das zu verwendende AI-Modell (optional, überschreibt die Standardeinstellung)"
|
||||
},
|
||||
"temperature": {
|
||||
"name": "Temperatur",
|
||||
"description": "Steuert die Antwortkreativität (0.0-2.0)"
|
||||
"description": "Steuert die Kreativität der Antwort (0,0-2,0)"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "Max. Token",
|
||||
"description": "Maximale Länge der Antwort (1-4096 Token)"
|
||||
"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."
|
||||
},
|
||||
"disable_thinking": {
|
||||
"name": "Thinking deaktivieren",
|
||||
"description": "Thinking/Reasoning-Modus für diese Anfrage deaktivieren. Überschreibt die Integrationseinstellung."
|
||||
}
|
||||
}
|
||||
},
|
||||
"clear_history": {
|
||||
"name": "Verlauf löschen",
|
||||
"description": "Alle gespeicherten Fragen und Antworten aus dem Konversationsverlauf 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, deren Verlauf gelöscht werden soll"
|
||||
"description": "Name der HA Text AI-Instanz, für die der Verlauf gelöscht werden soll"
|
||||
}
|
||||
}
|
||||
},
|
||||
"get_history": {
|
||||
"name": "Verlauf abrufen",
|
||||
"description": "Konversationsverlauf mit optionalem Filtern und Sortieren abrufen",
|
||||
"description": "Rufen Sie den Gesprächsverlauf mit optionaler Filterung und Sortierung ab",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Instanz",
|
||||
@@ -118,19 +171,19 @@
|
||||
},
|
||||
"limit": {
|
||||
"name": "Limit",
|
||||
"description": "Anzahl der zurückzugebenden Konversationen (1-100)"
|
||||
"description": "Anzahl der zurückzugebenden Gespräche (1-100)"
|
||||
},
|
||||
"filter_model": {
|
||||
"name": "Modell filtern",
|
||||
"description": "Konversationen nach einem bestimmten KI-Modell filtern"
|
||||
"description": "Gespräche nach spezifischem AI-Modell filtern"
|
||||
},
|
||||
"start_date": {
|
||||
"name": "Startdatum",
|
||||
"description": "Konversationen ab diesem Datum/Uhrzeit filtern"
|
||||
"description": "Gespräche ab diesem Datum/Zeit filtern"
|
||||
},
|
||||
"include_metadata": {
|
||||
"name": "Metadaten einschließen",
|
||||
"description": "Zusätzliche Informationen wie verwendete Token, Antwortzeit usw. einschließen"
|
||||
"name": "Metadaten einbeziehen",
|
||||
"description": "Zusätzliche Informationen wie verwendete Tokens, Antwortzeit usw. einbeziehen"
|
||||
},
|
||||
"sort_order": {
|
||||
"name": "Sortierreihenfolge",
|
||||
@@ -139,16 +192,16 @@
|
||||
}
|
||||
},
|
||||
"set_system_prompt": {
|
||||
"name": "Systemprompt festlegen",
|
||||
"description": "Legen Sie Standardanweisungen für das Systemverhalten für alle zukünftigen Konversationen fest",
|
||||
"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 der Systemprompt festgelegt werden soll"
|
||||
"description": "Name der HA Text AI-Instanz, für die die Systemaufforderung festgelegt werden soll"
|
||||
},
|
||||
"prompt": {
|
||||
"name": "Systemprompt",
|
||||
"description": "Anweisungen, die definieren, wie sich die KI verhalten und antworten soll"
|
||||
"name": "Systemaufforderung",
|
||||
"description": "Anweisungen, die definieren, wie die AI sich verhalten und antworten soll"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,11 +215,10 @@
|
||||
"processing": "Verarbeitung",
|
||||
"error": "Fehler",
|
||||
"disconnected": "Getrennt",
|
||||
"rate_limited": "Ratenlimit",
|
||||
"rate_limited": "Rate limitiert",
|
||||
"maintenance": "Wartung",
|
||||
"initializing": "Initialisierung",
|
||||
"retrying": "Wiederholen",
|
||||
"queued": "Warteschlange"
|
||||
"retrying": "Wiederholen"
|
||||
},
|
||||
"state_attributes": {
|
||||
"question": {
|
||||
@@ -182,16 +234,16 @@
|
||||
"name": "Temperatur"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "Max. Token"
|
||||
"name": "Max Tokens"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "Systemprompt"
|
||||
"name": "Systemaufforderung"
|
||||
},
|
||||
"response_time": {
|
||||
"name": "Letzte Antwortzeit"
|
||||
},
|
||||
"total_responses": {
|
||||
"name": "Gesamtzahl der Antworten"
|
||||
"name": "Gesamtantworten"
|
||||
},
|
||||
"error_count": {
|
||||
"name": "Fehleranzahl"
|
||||
@@ -203,19 +255,19 @@
|
||||
"name": "API-Status"
|
||||
},
|
||||
"tokens_used": {
|
||||
"name": "Verwendete Token insgesamt"
|
||||
"name": "Gesamte verwendete Tokens"
|
||||
},
|
||||
"average_response_time": {
|
||||
"name": "Durchschnittliche Antwortzeit"
|
||||
},
|
||||
"last_request_time": {
|
||||
"name": "Zeitpunkt der letzten Anfrage"
|
||||
"name": "Letzte Anfragezeit"
|
||||
},
|
||||
"is_processing": {
|
||||
"name": "Verarbeitungsstatus"
|
||||
},
|
||||
"is_rate_limited": {
|
||||
"name": "Ratenlimit-Status"
|
||||
"name": "Rate-limitiert Status"
|
||||
},
|
||||
"is_maintenance": {
|
||||
"name": "Wartungsstatus"
|
||||
@@ -224,25 +276,25 @@
|
||||
"name": "API-Version"
|
||||
},
|
||||
"endpoint_status": {
|
||||
"name": "Endpunkt-Status"
|
||||
"name": "Endpunktstatus"
|
||||
},
|
||||
"performance_metrics": {
|
||||
"name": "Leistungsmetriken"
|
||||
"name": "Leistungskennzahlen"
|
||||
},
|
||||
"history_size": {
|
||||
"name": "Verlaufsgröße"
|
||||
"name": "Größe des Verlaufs"
|
||||
},
|
||||
"uptime": {
|
||||
"name": "Betriebszeit"
|
||||
},
|
||||
"total_tokens": {
|
||||
"name": "Gesamtzahl der Token"
|
||||
"name": "Gesamte Tokens"
|
||||
},
|
||||
"prompt_tokens": {
|
||||
"name": "Prompt-Token"
|
||||
"name": "Eingabe Tokens"
|
||||
},
|
||||
"completion_tokens": {
|
||||
"name": "Completion-Token"
|
||||
"name": "Vervollständigungs Tokens"
|
||||
},
|
||||
"successful_requests": {
|
||||
"name": "Erfolgreiche Anfragen"
|
||||
@@ -258,6 +310,21 @@
|
||||
},
|
||||
"min_latency": {
|
||||
"name": "Minimale Latenz"
|
||||
},
|
||||
"last_model": {
|
||||
"name": "Zuletzt verwendetes Modell"
|
||||
},
|
||||
"last_timestamp": {
|
||||
"name": "Zeitpunkt der letzten Antwort"
|
||||
},
|
||||
"instance_name": {
|
||||
"name": "Instanzname"
|
||||
},
|
||||
"normalized_name": {
|
||||
"name": "Normalisierter Name"
|
||||
},
|
||||
"conversation_history": {
|
||||
"name": "Konversationsverlauf"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,21 @@
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "Select AI Provider",
|
||||
"description": "Choose which AI service provider to use for this instance.",
|
||||
"title": "Provider Settings",
|
||||
"description": "Provide connection details for your chosen AI provider.",
|
||||
"data": {
|
||||
"api_provider": "API Provider",
|
||||
"context_messages": "Number of context messages to retain (1-20)"
|
||||
"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)",
|
||||
"allow_local_network": "Allow local network endpoints (for self-hosted proxies)",
|
||||
"disable_thinking": "Disable thinking/reasoning mode (Qwen /no_think, strips think blocks, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
@@ -17,19 +27,26 @@
|
||||
"api_key": "API key for authentication",
|
||||
"model": "AI model to use",
|
||||
"temperature": "Response creativity (0-2, lower = more focused)",
|
||||
"max_tokens": "Maximum response length (1-4096 tokens)",
|
||||
"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)"
|
||||
"max_history_size": "Maximum conversation history size (1-100)",
|
||||
"allow_local_network": "Allow local network endpoints (for self-hosted proxies)",
|
||||
"disable_thinking": "Disable thinking/reasoning mode (Qwen /no_think, strips think blocks, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"history_storage_error": "Failed to initialize history storage. Check permissions.",
|
||||
"history_rotation_error": "Error during history file rotation.",
|
||||
"history_file_access_error": "Cannot access history storage directory.",
|
||||
"name_exists": "An instance with this name already exists",
|
||||
"invalid_name": "Invalid instance name",
|
||||
"invalid_auth": "Authentication failed - check your API key",
|
||||
"api_key_required": "API key is required when changing provider or endpoint",
|
||||
"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",
|
||||
@@ -43,30 +60,54 @@
|
||||
"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": {
|
||||
"already_configured": "Instance already configured"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "Update Instance Settings",
|
||||
"description": "Modify settings for this AI assistant instance.",
|
||||
"title": "Select Provider",
|
||||
"description": "Choose the AI provider for this instance. The integration will reload after saving changes.",
|
||||
"data": {
|
||||
"api_provider": "API Provider"
|
||||
}
|
||||
},
|
||||
"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-4096)",
|
||||
"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)"
|
||||
"max_history_size": "Maximum conversation history size (1-100)",
|
||||
"allow_local_network": "Allow local network endpoints (for self-hosted proxies)",
|
||||
"disable_thinking": "Disable thinking/reasoning mode (Qwen /no_think, strips think blocks, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"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. The response will be stored in the conversation history and can be retrieved later.",
|
||||
"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",
|
||||
@@ -94,7 +135,19 @@
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "Max Tokens",
|
||||
"description": "Maximum length of the response (1-4096 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."
|
||||
},
|
||||
"disable_thinking": {
|
||||
"name": "Disable Thinking",
|
||||
"description": "Disable model thinking/reasoning for this request. Overrides the integration-level setting."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -165,8 +218,7 @@
|
||||
"rate_limited": "Rate Limited",
|
||||
"maintenance": "Maintenance",
|
||||
"initializing": "Initializing",
|
||||
"retrying": "Retrying",
|
||||
"queued": "Queued"
|
||||
"retrying": "Retrying"
|
||||
},
|
||||
"state_attributes": {
|
||||
"question": {
|
||||
@@ -258,6 +310,24 @@
|
||||
},
|
||||
"min_latency": {
|
||||
"name": "Minimum Latency"
|
||||
},
|
||||
"last_model": {
|
||||
"name": "Last Used Model"
|
||||
},
|
||||
"last_timestamp": {
|
||||
"name": "Last Response Time"
|
||||
},
|
||||
"instance_name": {
|
||||
"name": "Instance Name"
|
||||
},
|
||||
"normalized_name": {
|
||||
"name": "Normalized Name"
|
||||
},
|
||||
"last_error": {
|
||||
"name": "Last Error"
|
||||
},
|
||||
"conversation_history": {
|
||||
"name": "Conversation History"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,152 +2,205 @@
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "Seleccionar proveedor de IA",
|
||||
"description": "Elige qué proveedor de servicios de IA usar para esta instancia.",
|
||||
"title": "Configuración del proveedor",
|
||||
"description": "Proporciona los detalles de conexión para tu proveedor de IA elegido.",
|
||||
"data": {
|
||||
"api_provider": "Proveedor de API",
|
||||
"context_messages": "Número de mensajes de contexto que conservar (1-20)"
|
||||
"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)",
|
||||
"allow_local_network": "Permitir endpoints de red local (para proxies autoalojados)",
|
||||
"disable_thinking": "Desactivar modo thinking/reasoning (Qwen /no_think, elimina bloques think, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "Configurar instancia de HA Text AI",
|
||||
"description": "Configura una nueva instancia de asistente de IA con el proveedor seleccionado.",
|
||||
"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 (p. ej., 'Asistente GPT', 'Ayudante de Claude')",
|
||||
"api_key": "Clave API para la autenticación",
|
||||
"model": "Modelo de IA a usar",
|
||||
"temperature": "Creatividad de la respuesta (0-2, cuanto menor, más enfocada)",
|
||||
"max_tokens": "Longitud máxima de la respuesta (1-4096 tokens)",
|
||||
"api_endpoint": "URL del punto final de la API personalizada (opcional)",
|
||||
"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)",
|
||||
"context_messages": "Número de mensajes de contexto que conservar (1-20)",
|
||||
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||
"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)",
|
||||
"allow_local_network": "Permitir endpoints de red local (para proxies autoalojados)",
|
||||
"disable_thinking": "Desactivar modo thinking/reasoning (Qwen /no_think, elimina bloques think, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"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": "Error de autenticación: comprueba tu clave API",
|
||||
"invalid_api_key": "Clave API no válida: verifica tus credenciales",
|
||||
"cannot_connect": "No se pudo conectar al servicio API",
|
||||
"invalid_auth": "La autenticación falló - verifica tu clave API",
|
||||
"api_key_required": "Se requiere la clave API al cambiar de proveedor o endpoint",
|
||||
"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 de contexto excedida",
|
||||
"context_length": "Longitud del contexto excedida",
|
||||
"rate_limit_exceeded": "Límite de tasa de API excedido",
|
||||
"maintenance": "El servicio está en mantenimiento",
|
||||
"invalid_response": "Se recibió una respuesta de API no válida",
|
||||
"api_error": "Se produjo un error en el servicio API",
|
||||
"timeout": "Tiempo de espera de la solicitud agotado",
|
||||
"invalid_instance": "Instancia especificada no válida",
|
||||
"unknown": "Se produjo un error inesperado",
|
||||
"invalid_response": "Respuesta de API no válida recibida",
|
||||
"api_error": "Ocurrió un error en el servicio de API",
|
||||
"timeout": "Se agotó el tiempo de la solicitud",
|
||||
"invalid_instance": "Instancia no válida especificada",
|
||||
"unknown": "Ocurrió un error inesperado",
|
||||
"empty": "El nombre no puede estar vacío",
|
||||
"invalid_characters": "El nombre solo puede contener letras, números, espacios, guiones bajos y guiones",
|
||||
"name_too_long": "El nombre debe tener 50 caracteres o menos"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "Instancia ya configurada"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "Actualizar configuración de la instancia",
|
||||
"description": "Modifica la configuración de esta instancia de asistente de IA.",
|
||||
"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-4096)",
|
||||
"request_interval": "Intervalo mínimo de solicitud (0,1-60 segundos)",
|
||||
"context_messages": "Número de mensajes anteriores que se incluirán en el contexto (1-20)",
|
||||
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||
"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)",
|
||||
"allow_local_network": "Permitir endpoints de red local (para proxies autoalojados)",
|
||||
"disable_thinking": "Desactivar modo thinking/reasoning (Qwen /no_think, elimina bloques think, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"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. La respuesta se almacenará en el historial de conversación y se podrá recuperar más tarde.",
|
||||
"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 HA Text AI a utilizar"
|
||||
"description": "Nombre de la instancia de IA de Texto de HA a utilizar"
|
||||
},
|
||||
"question": {
|
||||
"name": "Pregunta",
|
||||
"description": "Tu pregunta o indicación para el asistente de IA"
|
||||
"description": "Tu pregunta o solicitud para el asistente de IA"
|
||||
},
|
||||
"context_messages": {
|
||||
"name": "Mensajes de contexto",
|
||||
"description": "Número de mensajes anteriores que se incluirán en el contexto (1-20)"
|
||||
"name": "Mensajes de Contexto",
|
||||
"description": "Número de mensajes anteriores a incluir en el contexto (1-20)"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "Indicación del sistema",
|
||||
"description": "Indicación del sistema opcional para establecer el contexto de esta pregunta específica"
|
||||
"name": "Indicaciones del Sistema",
|
||||
"description": "Indicaciones opcionales para establecer contexto para esta pregunta específica"
|
||||
},
|
||||
"model": {
|
||||
"name": "Modelo",
|
||||
"description": "Selecciona el modelo de IA que se va a utilizar (opcional, anula la configuración predeterminada)"
|
||||
"description": "Selecciona el modelo de IA a utilizar (opcional, anula la configuración predeterminada)"
|
||||
},
|
||||
"temperature": {
|
||||
"name": "Temperatura",
|
||||
"description": "Controla la creatividad de la respuesta (0.0-2.0)"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "Máx. tokens",
|
||||
"description": "Longitud máxima de la respuesta (1-4096 tokens)"
|
||||
"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."
|
||||
},
|
||||
"disable_thinking": {
|
||||
"name": "Desactivar Thinking",
|
||||
"description": "Desactivar el modo thinking/reasoning para esta solicitud. Anula la configuración de la integración."
|
||||
}
|
||||
}
|
||||
},
|
||||
"clear_history": {
|
||||
"name": "Borrar historial",
|
||||
"name": "Borrar Historial",
|
||||
"description": "Elimina todas las preguntas y respuestas almacenadas del historial de conversación",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Instancia",
|
||||
"description": "Nombre de la instancia de HA Text AI para la que se va a borrar el historial"
|
||||
"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 conversaciones con filtrado y ordenación opcionales",
|
||||
"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 HA Text AI de la que se va a obtener el historial"
|
||||
"description": "Nombre de la instancia de IA de Texto de HA para obtener historial"
|
||||
},
|
||||
"limit": {
|
||||
"name": "Límite",
|
||||
"description": "Número de conversaciones que se van a devolver (1-100)"
|
||||
"description": "Número de conversaciones a devolver (1-100)"
|
||||
},
|
||||
"filter_model": {
|
||||
"name": "Filtrar modelo",
|
||||
"description": "Filtra las conversaciones por un modelo de IA específico"
|
||||
"name": "Filtrar Modelo",
|
||||
"description": "Filtrar conversaciones por modelo de IA específico"
|
||||
},
|
||||
"start_date": {
|
||||
"name": "Fecha de inicio",
|
||||
"description": "Filtra las conversaciones a partir de esta fecha/hora"
|
||||
"name": "Fecha de Inicio",
|
||||
"description": "Filtrar conversaciones a partir de esta fecha/hora"
|
||||
},
|
||||
"include_metadata": {
|
||||
"name": "Incluir metadatos",
|
||||
"description": "Incluir información adicional como los tokens utilizados, el tiempo de respuesta, etc."
|
||||
"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 de los resultados (más recientes o más antiguos primero)"
|
||||
"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 indicación del sistema",
|
||||
"description": "Establece instrucciones predeterminadas de comportamiento del sistema para todas las conversaciones futuras",
|
||||
"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 HA Text AI para la que se va a establecer la indicación del sistema"
|
||||
"description": "Nombre de la instancia de IA de Texto de HA para establecer indicaciones del sistema"
|
||||
},
|
||||
"prompt": {
|
||||
"name": "Indicación del sistema",
|
||||
"name": "Indicaciones del Sistema",
|
||||
"description": "Instrucciones que definen cómo debe comportarse y responder la IA"
|
||||
}
|
||||
}
|
||||
@@ -162,102 +215,116 @@
|
||||
"processing": "Procesando",
|
||||
"error": "Error",
|
||||
"disconnected": "Desconectado",
|
||||
"rate_limited": "Límite de tasa alcanzado",
|
||||
"rate_limited": "Limitado por tasa",
|
||||
"maintenance": "Mantenimiento",
|
||||
"initializing": "Inicializando",
|
||||
"retrying": "Reintentando",
|
||||
"queued": "En cola"
|
||||
"retrying": "Reintentando"
|
||||
},
|
||||
"state_attributes": {
|
||||
"question": {
|
||||
"name": "Última pregunta"
|
||||
"name": "Última Pregunta"
|
||||
},
|
||||
"response": {
|
||||
"name": "Última respuesta"
|
||||
"name": "Última Respuesta"
|
||||
},
|
||||
"model": {
|
||||
"name": "Modelo actual"
|
||||
"name": "Modelo Actual"
|
||||
},
|
||||
"temperature": {
|
||||
"name": "Temperatura"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "Máx. tokens"
|
||||
"name": "Máx. Tokens"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "Indicación del sistema"
|
||||
"name": "Indicaciones del Sistema"
|
||||
},
|
||||
"response_time": {
|
||||
"name": "Tiempo de la última respuesta"
|
||||
"name": "Último Tiempo de Respuesta"
|
||||
},
|
||||
"total_responses": {
|
||||
"name": "Total de respuestas"
|
||||
"name": "Total de Respuestas"
|
||||
},
|
||||
"error_count": {
|
||||
"name": "Recuento de errores"
|
||||
"name": "Conteo de Errores"
|
||||
},
|
||||
"last_error": {
|
||||
"name": "Último error"
|
||||
"name": "Último Error"
|
||||
},
|
||||
"api_status": {
|
||||
"name": "Estado de la API"
|
||||
"name": "Estado de API"
|
||||
},
|
||||
"tokens_used": {
|
||||
"name": "Total de tokens usados"
|
||||
"name": "Total de Tokens Usados"
|
||||
},
|
||||
"average_response_time": {
|
||||
"name": "Tiempo medio de respuesta"
|
||||
"name": "Tiempo de Respuesta Promedio"
|
||||
},
|
||||
"last_request_time": {
|
||||
"name": "Tiempo de la última solicitud"
|
||||
"name": "Último Tiempo de Solicitud"
|
||||
},
|
||||
"is_processing": {
|
||||
"name": "Estado de procesamiento"
|
||||
"name": "Estado de Procesamiento"
|
||||
},
|
||||
"is_rate_limited": {
|
||||
"name": "Estado de límite de tasa"
|
||||
"name": "Estado Limitado por Tasa"
|
||||
},
|
||||
"is_maintenance": {
|
||||
"name": "Estado de mantenimiento"
|
||||
"name": "Estado de Mantenimiento"
|
||||
},
|
||||
"api_version": {
|
||||
"name": "Versión de la API"
|
||||
"name": "Versión de API"
|
||||
},
|
||||
"endpoint_status": {
|
||||
"name": "Estado del punto final"
|
||||
"name": "Estado del Endpoint"
|
||||
},
|
||||
"performance_metrics": {
|
||||
"name": "Métricas de rendimiento"
|
||||
"name": "Métricas de Rendimiento"
|
||||
},
|
||||
"history_size": {
|
||||
"name": "Tamaño del historial"
|
||||
"name": "Tamaño del Historial"
|
||||
},
|
||||
"uptime": {
|
||||
"name": "Tiempo de actividad"
|
||||
"name": "Tiempo de Actividad"
|
||||
},
|
||||
"total_tokens": {
|
||||
"name": "Total de tokens"
|
||||
"name": "Total de Tokens"
|
||||
},
|
||||
"prompt_tokens": {
|
||||
"name": "Tokens de indicación"
|
||||
"name": "Tokens de Solicitud"
|
||||
},
|
||||
"completion_tokens": {
|
||||
"name": "Tokens de compleción"
|
||||
"name": "Tokens de Finalización"
|
||||
},
|
||||
"successful_requests": {
|
||||
"name": "Solicitudes exitosas"
|
||||
"name": "Solicitudes Exitosas"
|
||||
},
|
||||
"failed_requests": {
|
||||
"name": "Solicitudes fallidas"
|
||||
"name": "Solicitudes Fallidas"
|
||||
},
|
||||
"average_latency": {
|
||||
"name": "Latencia media"
|
||||
"name": "Latencia Promedio"
|
||||
},
|
||||
"max_latency": {
|
||||
"name": "Latencia máxima"
|
||||
"name": "Latencia Máxima"
|
||||
},
|
||||
"min_latency": {
|
||||
"name": "Latencia mínima"
|
||||
"name": "Latencia Mínima"
|
||||
},
|
||||
"last_model": {
|
||||
"name": "Último modelo utilizado"
|
||||
},
|
||||
"last_timestamp": {
|
||||
"name": "Hora de la última respuesta"
|
||||
},
|
||||
"instance_name": {
|
||||
"name": "Nombre de instancia"
|
||||
},
|
||||
"normalized_name": {
|
||||
"name": "Nombre normalizado"
|
||||
},
|
||||
"conversation_history": {
|
||||
"name": "Historial de conversación"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,79 +2,120 @@
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "AI प्रदाता का चयन करें",
|
||||
"description": "इस उदाहरण के लिए उपयोग करने के लिए AI सेवा प्रदाता चुनें।",
|
||||
"title": "प्रदाता सेटिंग्स",
|
||||
"description": "आपके द्वारा चुने गए एआई प्रदाता के लिए कनेक्शन विवरण प्रदान करें।",
|
||||
"data": {
|
||||
"api_provider": "API प्रदाता",
|
||||
"context_messages": "बनाए रखने के लिए संदर्भ संदेशों की संख्या (1-20)"
|
||||
"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)",
|
||||
"allow_local_network": "स्थानीय नेटवर्क एंडपॉइंट की अनुमति दें (सेल्फ-होस्टेड प्रॉक्सी के लिए)",
|
||||
"disable_thinking": "thinking/reasoning मोड बंद करें (Qwen /no_think, think ब्लॉक हटाता है, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "HA टेक्स्ट AI उदाहरण को कॉन्फ़िगर करें",
|
||||
"description": "अपने चयनित प्रदाता के साथ एक नया AI सहायक उदाहरण सेट करें।",
|
||||
"title": "एचए टेक्स्ट एआई उदाहरण कॉन्फ़िगर करें",
|
||||
"description": "अपने चुने हुए प्रदाता के साथ एक नया एआई सहायक उदाहरण सेट करें।",
|
||||
"data": {
|
||||
"name": "उदाहरण का नाम (जैसे, 'GPT सहायक', 'क्लाउड सहायक')",
|
||||
"api_key": "प्रमाणीकरण के लिए API कुंजी",
|
||||
"model": "उपयोग करने के लिए AI मॉडल",
|
||||
"temperature": "प्रतिक्रिया रचनात्मकता (0-2, कम = अधिक केंद्रित)",
|
||||
"max_tokens": "अधिकतम प्रतिक्रिया लंबाई (1-4096 टोकन)",
|
||||
"api_endpoint": "कस्टम API एंडपॉइंट URL (वैकल्पिक)",
|
||||
"api_provider": "API प्रदाता",
|
||||
"name": "उदाहरण का नाम (जैसे, 'जीपीटी सहायक', 'क्लॉड सहायक')",
|
||||
"api_key": "प्रमाणीकरण के लिए एपीआई कुंजी",
|
||||
"model": "उपयोग करने के लिए एआई मॉडल",
|
||||
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)",
|
||||
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)",
|
||||
"api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)",
|
||||
"api_provider": "एपीआई प्रदाता",
|
||||
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
|
||||
"context_messages": "बनाए रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
||||
"max_history_size": "अधिकतम वार्तालाप इतिहास आकार (1-100)"
|
||||
"api_timeout": "एपीआई अनुरोध टाइमआउट सेकंड में (5-600)",
|
||||
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
||||
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)",
|
||||
"allow_local_network": "स्थानीय नेटवर्क एंडपॉइंट की अनुमति दें (सेल्फ-होस्टेड प्रॉक्सी के लिए)",
|
||||
"disable_thinking": "thinking/reasoning मोड बंद करें (Qwen /no_think, think ब्लॉक हटाता है, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"name_exists": "इस नाम का एक उदाहरण पहले से मौजूद है",
|
||||
"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_auth": "प्रमाणीकरण विफल - अपनी एपीआई कुंजी की जांच करें",
|
||||
"api_key_required": "प्रदाता या endpoint बदलते समय API कुंजी आवश्यक है",
|
||||
"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 वर्ण या उससे कम होना चाहिए"
|
||||
"name_too_long": "नाम 50 अक्षरों या उससे कम होना चाहिए"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "उदाहरण पहले से कॉन्फ़िगर किया गया है"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "उदाहरण सेटिंग्स अपडेट करें",
|
||||
"description": "इस AI सहायक उदाहरण के लिए सेटिंग्स संशोधित करें।",
|
||||
"title": "प्रदाता चुनें",
|
||||
"description": "इस उदाहरण के लिए एआई प्रदाता चुनें। परिवर्तन सहेजने के बाद एकीकरण पुनः लोड होगा।",
|
||||
"data": {
|
||||
"model": "AI मॉडल",
|
||||
"temperature": "प्रतिक्रिया रचनात्मकता (0-2)",
|
||||
"max_tokens": "अधिकतम प्रतिक्रिया लंबाई (1-4096)",
|
||||
"request_interval": "न्यूनतम अनुरोध अंतराल (0.1-60 सेकंड)",
|
||||
"context_messages": "संदर्भ में शामिल करने के लिए पिछले संदेशों की संख्या (1-20)",
|
||||
"max_history_size": "अधिकतम वार्तालाप इतिहास आकार (1-100)"
|
||||
"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)",
|
||||
"allow_local_network": "स्थानीय नेटवर्क एंडपॉइंट की अनुमति दें (सेल्फ-होस्टेड प्रॉक्सी के लिए)",
|
||||
"disable_thinking": "thinking/reasoning मोड बंद करें (Qwen /no_think, think ब्लॉक हटाता है, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"selector": {
|
||||
"api_provider": {
|
||||
"options": {
|
||||
"openai": "OpenAI (अनुकूलित)",
|
||||
"anthropic": "Anthropic (अनुकूलित)",
|
||||
"deepseek": "DeepSeek",
|
||||
"gemini": "Google Gemini"
|
||||
}
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "प्रश्न पूछें (HA टेक्स्ट AI)",
|
||||
"description": "AI मॉडल को एक प्रश्न भेजें और एक विस्तृत प्रतिक्रिया प्राप्त करें। प्रतिक्रिया वार्तालाप इतिहास में संग्रहीत की जाएगी और बाद में पुनर्प्राप्त की जा सकती है।",
|
||||
"name": "प्रश्न पूछें (HA Text AI)",
|
||||
"description": "AI मॉडल को प्रश्न भेजें और विस्तृत उत्तर प्राप्त करें। यह सेवा अब प्रत्यक्ष रूप से प्रतिक्रिया डेटा वापस करती है, अलग टेक्स्ट सेंसर की आवश्यकता और 255 वर्ण की सीमा को समाप्त करती है। प्रतिक्रिया को बातचीत के इतिहास में भी संग्रहीत किया जाएगा।",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "उदाहरण",
|
||||
"description": "उपयोग करने के लिए HA टेक्स्ट AI उदाहरण का नाम"
|
||||
"description": "उपयोग करने के लिए एचए टेक्स्ट एआई उदाहरण का नाम"
|
||||
},
|
||||
"question": {
|
||||
"name": "प्रश्न",
|
||||
"description": "AI सहायक के लिए आपका प्रश्न या संकेत"
|
||||
"description": "आपका प्रश्न या एआई सहायक के लिए प्रॉम्प्ट"
|
||||
},
|
||||
"context_messages": {
|
||||
"name": "संदर्भ संदेश",
|
||||
@@ -82,73 +123,85 @@
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "सिस्टम प्रॉम्प्ट",
|
||||
"description": "इस विशिष्ट प्रश्न के लिए संदर्भ सेट करने के लिए वैकल्पिक सिस्टम प्रॉम्प्ट"
|
||||
"description": "इस विशेष प्रश्न के लिए संदर्भ सेट करने के लिए वैकल्पिक सिस्टम प्रॉम्प्ट"
|
||||
},
|
||||
"model": {
|
||||
"name": "मॉडल",
|
||||
"description": "उपयोग करने के लिए AI मॉडल का चयन करें (वैकल्पिक, डिफ़ॉल्ट सेटिंग को ओवरराइड करता है)"
|
||||
"description": "उपयोग करने के लिए एआई मॉडल का चयन करें (वैकल्पिक, डिफ़ॉल्ट सेटिंग को ओवरराइड करता है)"
|
||||
},
|
||||
"temperature": {
|
||||
"name": "तापमान",
|
||||
"description": "प्रतिक्रिया रचनात्मकता को नियंत्रित करता है (0.0-2.0)"
|
||||
"description": "प्रतिक्रिया की रचनात्मकता को नियंत्रित करता है (0.0-2.0)"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "अधिकतम टोकन",
|
||||
"description": "प्रतिक्रिया की अधिकतम लंबाई (1-4096 टोकन)"
|
||||
"description": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)"
|
||||
},
|
||||
"structured_output": {
|
||||
"name": "संरचित आउटपुट",
|
||||
"description": "JSON संरचित आउटपुट मोड सक्षम करें। सक्षम होने पर, AI प्रदान किए गए स्कीमा से मेल खाने वाले वैध JSON के साथ प्रतिक्रिया देगा।"
|
||||
},
|
||||
"json_schema": {
|
||||
"name": "JSON स्कीमा",
|
||||
"description": "अपेक्षित प्रतिक्रिया की संरचना को परिभाषित करने वाला JSON स्कीमा। structured_output सक्षम होने पर आवश्यक।"
|
||||
},
|
||||
"disable_thinking": {
|
||||
"name": "Thinking बंद करें",
|
||||
"description": "इस अनुरोध के लिए thinking/reasoning मोड बंद करें। एकीकरण सेटिंग को ओवरराइड करता है।"
|
||||
}
|
||||
}
|
||||
},
|
||||
"clear_history": {
|
||||
"name": "इतिहास साफ़ करें",
|
||||
"description": "वार्तालाप इतिहास से सभी संग्रहीत प्रश्न और प्रतिक्रियाएँ हटाएँ",
|
||||
"name": "इतिहास साफ करें",
|
||||
"description": "बातचीत के इतिहास से सभी संग्रहीत प्रश्नों और प्रतिक्रियाओं को हटाएं",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "उदाहरण",
|
||||
"description": "इतिहास साफ़ करने के लिए HA टेक्स्ट AI उदाहरण का नाम"
|
||||
"description": "इतिहास साफ़ करने के लिए एचए टेक्स्ट एआई उदाहरण का नाम"
|
||||
}
|
||||
}
|
||||
},
|
||||
"get_history": {
|
||||
"name": "इतिहास प्राप्त करें",
|
||||
"description": "वैकल्पिक फ़िल्टरिंग और सॉर्टिंग के साथ वार्तालाप इतिहास पुनर्प्राप्त करें",
|
||||
"description": "वैकल्पिक फ़िल्टरिंग और छंटाई के साथ बातचीत का इतिहास प्राप्त करें",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "उदाहरण",
|
||||
"description": "इतिहास प्राप्त करने के लिए HA टेक्स्ट AI उदाहरण का नाम"
|
||||
"description": "इतिहास प्राप्त करने के लिए एचए टेक्स्ट एआई उदाहरण का नाम"
|
||||
},
|
||||
"limit": {
|
||||
"name": "सीमा",
|
||||
"description": "वापस करने के लिए वार्तालापों की संख्या (1-100)"
|
||||
"description": "वापस करने के लिए बातचीत की संख्या (1-100)"
|
||||
},
|
||||
"filter_model": {
|
||||
"name": "फ़िल्टर मॉडल",
|
||||
"description": "विशिष्ट AI मॉडल द्वारा वार्तालापों को फ़िल्टर करें"
|
||||
"name": "फिल्टर मॉडल",
|
||||
"description": "विशिष्ट एआई मॉडल द्वारा बातचीत को फ़िल्टर करें"
|
||||
},
|
||||
"start_date": {
|
||||
"name": "प्रारंभ तिथि",
|
||||
"description": "इस तिथि/समय से शुरू होने वाले वार्तालापों को फ़िल्टर करें"
|
||||
"name": "शुरुआत की तारीख",
|
||||
"description": "इस दिन/समय से शुरू होने वाली बातचीत को फ़िल्टर करें"
|
||||
},
|
||||
"include_metadata": {
|
||||
"name": "मेटाडेटा शामिल करें",
|
||||
"description": "उपयोग किए गए टोकन, प्रतिक्रिया समय, आदि जैसी अतिरिक्त जानकारी शामिल करें।"
|
||||
"description": "उपयोग किए गए टोकन, प्रतिक्रिया समय आदि जैसी अतिरिक्त जानकारी शामिल करें।"
|
||||
},
|
||||
"sort_order": {
|
||||
"name": "क्रमबद्ध करें",
|
||||
"description": "परिणामों के लिए क्रमबद्ध क्रम (नवीनतम या सबसे पुराना पहले)"
|
||||
"name": "छंटाई क्रम",
|
||||
"description": "परिणामों के लिए छंटाई क्रम (नवीनतम या सबसे पुराना पहले)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"set_system_prompt": {
|
||||
"name": "सिस्टम प्रॉम्प्ट सेट करें",
|
||||
"description": "सभी भविष्य के वार्तालापों के लिए डिफ़ॉल्ट सिस्टम व्यवहार निर्देश सेट करें",
|
||||
"description": "सभी भविष्य की बातचीत के लिए डिफ़ॉल्ट सिस्टम व्यवहार निर्देश सेट करें",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "उदाहरण",
|
||||
"description": "सिस्टम प्रॉम्प्ट सेट करने के लिए HA टेक्स्ट AI उदाहरण का नाम"
|
||||
"description": "सिस्टम प्रॉम्प्ट सेट करने के लिए एचए टेक्स्ट एआई उदाहरण का नाम"
|
||||
},
|
||||
"prompt": {
|
||||
"name": "सिस्टम प्रॉम्प्ट",
|
||||
"description": "निर्देश जो परिभाषित करते हैं कि AI को कैसे व्यवहार करना चाहिए और जवाब देना चाहिए"
|
||||
"description": "निर्देश जो यह परिभाषित करते हैं कि एआई को कैसे व्यवहार करना चाहिए और प्रतिक्रिया देनी चाहिए"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -159,14 +212,13 @@
|
||||
"name": "{name}",
|
||||
"state": {
|
||||
"ready": "तैयार",
|
||||
"processing": "प्रक्रियाधीन",
|
||||
"processing": "प्रसंस्करण",
|
||||
"error": "त्रुटि",
|
||||
"disconnected": "डिस्कनेक्टेड",
|
||||
"rate_limited": "दर सीमित",
|
||||
"disconnected": "असंयुक्त",
|
||||
"rate_limited": "रेट सीमित",
|
||||
"maintenance": "रखरखाव",
|
||||
"initializing": "आरंभिकरण",
|
||||
"retrying": "पुनः प्रयास कर रहा है",
|
||||
"queued": "कतारबद्ध"
|
||||
"initializing": "प्रारंभिककरण",
|
||||
"retrying": "पुनः प्रयास कर रहा है"
|
||||
},
|
||||
"state_attributes": {
|
||||
"question": {
|
||||
@@ -188,46 +240,46 @@
|
||||
"name": "सिस्टम प्रॉम्प्ट"
|
||||
},
|
||||
"response_time": {
|
||||
"name": "अंतिम प्रतिक्रिया समय"
|
||||
"name": "अंतिम प्रतिक्रिया का समय"
|
||||
},
|
||||
"total_responses": {
|
||||
"name": "कुल प्रतिक्रियाएँ"
|
||||
"name": "कुल प्रतिक्रियाएं"
|
||||
},
|
||||
"error_count": {
|
||||
"name": "त्रुटि गणना"
|
||||
"name": "त्रुटियों की संख्या"
|
||||
},
|
||||
"last_error": {
|
||||
"name": "अंतिम त्रुटि"
|
||||
},
|
||||
"api_status": {
|
||||
"name": "API स्थिति"
|
||||
"name": "एपीआई स्थिति"
|
||||
},
|
||||
"tokens_used": {
|
||||
"name": "कुल टोकन उपयोग किए गए"
|
||||
"name": "कुल उपयोग किए गए टोकन"
|
||||
},
|
||||
"average_response_time": {
|
||||
"name": "औसत प्रतिक्रिया समय"
|
||||
},
|
||||
"last_request_time": {
|
||||
"name": "अंतिम अनुरोध समय"
|
||||
"name": "अंतिम अनुरोध का समय"
|
||||
},
|
||||
"is_processing": {
|
||||
"name": "प्रसंस्करण स्थिति"
|
||||
},
|
||||
"is_rate_limited": {
|
||||
"name": "दर सीमित स्थिति"
|
||||
"name": "रेट सीमित स्थिति"
|
||||
},
|
||||
"is_maintenance": {
|
||||
"name": "रखरखाव स्थिति"
|
||||
},
|
||||
"api_version": {
|
||||
"name": "API संस्करण"
|
||||
"name": "एपीआई संस्करण"
|
||||
},
|
||||
"endpoint_status": {
|
||||
"name": "एंडपॉइंट स्थिति"
|
||||
},
|
||||
"performance_metrics": {
|
||||
"name": "प्रदर्शन मेट्रिक्स"
|
||||
"name": "प्रदर्शन मैट्रिक्स"
|
||||
},
|
||||
"history_size": {
|
||||
"name": "इतिहास का आकार"
|
||||
@@ -242,13 +294,13 @@
|
||||
"name": "प्रॉम्प्ट टोकन"
|
||||
},
|
||||
"completion_tokens": {
|
||||
"name": "पूर्ण टोकन"
|
||||
"name": "पूर्णता टोकन"
|
||||
},
|
||||
"successful_requests": {
|
||||
"name": "सफल अनुरोध"
|
||||
},
|
||||
"failed_requests": {
|
||||
"name": "असफल अनुरोध"
|
||||
"name": "विफल अनुरोध"
|
||||
},
|
||||
"average_latency": {
|
||||
"name": "औसत विलंबता"
|
||||
@@ -258,6 +310,21 @@
|
||||
},
|
||||
"min_latency": {
|
||||
"name": "न्यूनतम विलंबता"
|
||||
},
|
||||
"last_model": {
|
||||
"name": "अंतिम उपयोग किया गया मॉडल"
|
||||
},
|
||||
"last_timestamp": {
|
||||
"name": "अंतिम प्रतिक्रिया समय"
|
||||
},
|
||||
"instance_name": {
|
||||
"name": "इंस्टेंस नाम"
|
||||
},
|
||||
"normalized_name": {
|
||||
"name": "सामान्यीकृत नाम"
|
||||
},
|
||||
"conversation_history": {
|
||||
"name": "वार्तालाप इतिहास"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,86 +2,127 @@
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "Seleziona Provider AI",
|
||||
"description": "Scegli quale provider di servizio AI utilizzare per questa istanza.",
|
||||
"title": "Impostazioni fornitore",
|
||||
"description": "Fornisci i dettagli di connessione per il tuo fornitore di AI scelto.",
|
||||
"data": {
|
||||
"api_provider": "Provider API",
|
||||
"context_messages": "Numero di messaggi di contesto da conservare (1-20)"
|
||||
"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)",
|
||||
"allow_local_network": "Consenti endpoint di rete locale (per proxy self-hosted)",
|
||||
"disable_thinking": "Disabilita la modalità thinking/reasoning (Qwen /no_think, rimuove i blocchi think, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "Configura Istanza HA Text AI",
|
||||
"description": "Configura una nuova istanza di assistente AI con il provider selezionato.",
|
||||
"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', 'Aiutante Claude')",
|
||||
"name": "Nome dell'istanza (es. 'Assistente GPT', 'Aiuto Claude')",
|
||||
"api_key": "Chiave API per l'autenticazione",
|
||||
"model": "Modello AI da utilizzare",
|
||||
"temperature": "Creatività della risposta (0-2, più basso = più focalizzato)",
|
||||
"max_tokens": "Lunghezza massima della risposta (1-4096 token)",
|
||||
"api_endpoint": "URL endpoint API personalizzato (opzionale)",
|
||||
"api_provider": "Provider API",
|
||||
"request_interval": "Tempo minimo tra le richieste (0,1-60 secondi)",
|
||||
"context_messages": "Numero di messaggi di contesto da conservare (1-20)",
|
||||
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||
"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)",
|
||||
"allow_local_network": "Consenti endpoint di rete locale (per proxy self-hosted)",
|
||||
"disable_thinking": "Disabilita la modalità thinking/reasoning (Qwen /no_think, rimuove i blocchi think, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"name_exists": "Un'istanza con questo nome esiste già",
|
||||
"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",
|
||||
"api_key_required": "La chiave API è obbligatoria quando si cambia provider o endpoint",
|
||||
"invalid_api_key": "Chiave API non valida - verifica le tue credenziali",
|
||||
"cannot_connect": "Impossibile connettersi al servizio API",
|
||||
"invalid_model": "Il modello selezionato non è disponibile",
|
||||
"rate_limit": "Limite di velocità superato",
|
||||
"rate_limit": "Limite di frequenza superato",
|
||||
"context_length": "Lunghezza del contesto superata",
|
||||
"rate_limit_exceeded": "Limite di velocità API superato",
|
||||
"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 del servizio API",
|
||||
"api_error": "Si è verificato un errore nel servizio API",
|
||||
"timeout": "Richiesta scaduta",
|
||||
"invalid_instance": "Istanza non valida specificata",
|
||||
"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 non può superare i 50 caratteri"
|
||||
"name_too_long": "Il nome deve essere lungo 50 caratteri o meno"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "Istanze già configurata"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "Aggiorna Impostazioni Istanza",
|
||||
"description": "Modifica le impostazioni per questa istanza di assistente AI.",
|
||||
"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-4096)",
|
||||
"request_interval": "Intervallo minimo tra le richieste (0,1-60 secondi)",
|
||||
"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)"
|
||||
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)",
|
||||
"allow_local_network": "Consenti endpoint di rete locale (per proxy self-hosted)",
|
||||
"disable_thinking": "Disabilita la modalità thinking/reasoning (Qwen /no_think, rimuove i blocchi think, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"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. La risposta verrà memorizzata nella cronologia delle conversazioni e potrà essere recuperata in seguito.",
|
||||
"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": "Istanza",
|
||||
"name": "Istanze",
|
||||
"description": "Nome dell'istanza HA Text AI da utilizzare"
|
||||
},
|
||||
"question": {
|
||||
"name": "Domanda",
|
||||
"description": "La tua domanda o prompt per l'assistente AI"
|
||||
"description": "La tua domanda o richiesta per l'assistente AI"
|
||||
},
|
||||
"context_messages": {
|
||||
"name": "Messaggi di Contesto",
|
||||
"name": "Messaggi di contesto",
|
||||
"description": "Numero di messaggi precedenti da includere nel contesto (1-20)"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "Prompt di Sistema",
|
||||
"name": "Prompt di sistema",
|
||||
"description": "Prompt di sistema opzionale per impostare il contesto per questa specifica domanda"
|
||||
},
|
||||
"model": {
|
||||
@@ -93,62 +134,74 @@
|
||||
"description": "Controlla la creatività della risposta (0.0-2.0)"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "Max Token",
|
||||
"description": "Lunghezza massima della risposta (1-4096 token)"
|
||||
"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."
|
||||
},
|
||||
"disable_thinking": {
|
||||
"name": "Disabilita Thinking",
|
||||
"description": "Disabilita la modalità thinking/reasoning per questa richiesta. Sovrascrive l'impostazione dell'integrazione."
|
||||
}
|
||||
}
|
||||
},
|
||||
"clear_history": {
|
||||
"name": "Cancella Cronologia",
|
||||
"description": "Elimina tutte le domande e le risposte memorizzate dalla cronologia delle conversazioni",
|
||||
"name": "Cancella cronologia",
|
||||
"description": "Elimina tutte le domande e risposte memorizzate dalla cronologia delle conversazioni",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Istanza",
|
||||
"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 filtro e ordinamento opzionali",
|
||||
"name": "Ottieni cronologia",
|
||||
"description": "Recupera la cronologia delle conversazioni con opzioni di filtro e ordinamento",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Istanza",
|
||||
"description": "Nome dell'istanza HA Text AI da cui ottenere la cronologia"
|
||||
"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": "Filtro Modello",
|
||||
"description": "Filtra le conversazioni per specifico modello AI"
|
||||
"name": "Filtra modello",
|
||||
"description": "Filtra le conversazioni per modello AI specifico"
|
||||
},
|
||||
"start_date": {
|
||||
"name": "Data di Inizio",
|
||||
"name": "Data di inizio",
|
||||
"description": "Filtra le conversazioni a partire da questa data/ora"
|
||||
},
|
||||
"include_metadata": {
|
||||
"name": "Includi Metadati",
|
||||
"name": "Includi metadati",
|
||||
"description": "Includi informazioni aggiuntive come token utilizzati, tempo di risposta, ecc."
|
||||
},
|
||||
"sort_order": {
|
||||
"name": "Ordine di Ordinamento",
|
||||
"description": "Ordine di ordinamento per i risultati (più recente o più vecchio per primo)"
|
||||
"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 del sistema per tutte le future conversazioni",
|
||||
"name": "Imposta prompt di sistema",
|
||||
"description": "Imposta le istruzioni di comportamento predefinite per tutte le future conversazioni",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Istanza",
|
||||
"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'IA dovrebbe comportarsi e rispondere"
|
||||
"name": "Prompt di sistema",
|
||||
"description": "Istruzioni che definiscono come l'AI dovrebbe comportarsi e rispondere"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -159,108 +212,122 @@
|
||||
"name": "{name}",
|
||||
"state": {
|
||||
"ready": "Pronto",
|
||||
"processing": "In elaborazione",
|
||||
"processing": "Elaborazione",
|
||||
"error": "Errore",
|
||||
"disconnected": "Disconnesso",
|
||||
"rate_limited": "Limite di Velocità Raggiunto",
|
||||
"rate_limited": "Limite di frequenza",
|
||||
"maintenance": "Manutenzione",
|
||||
"initializing": "Inizializzazione",
|
||||
"retrying": "Riprovando",
|
||||
"queued": "In coda"
|
||||
"retrying": "Riprova"
|
||||
},
|
||||
"state_attributes": {
|
||||
"question": {
|
||||
"name": "Ultima Domanda"
|
||||
"name": "Ultima domanda"
|
||||
},
|
||||
"response": {
|
||||
"name": "Ultima Risposta"
|
||||
"name": "Ultima risposta"
|
||||
},
|
||||
"model": {
|
||||
"name": "Modello Attuale"
|
||||
"name": "Modello attuale"
|
||||
},
|
||||
"temperature": {
|
||||
"name": "Temperatura"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "Max Token"
|
||||
"name": "Token massimi"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "Prompt di Sistema"
|
||||
"name": "Prompt di sistema"
|
||||
},
|
||||
"response_time": {
|
||||
"name": "Tempo di Risposta Ultima"
|
||||
"name": "Ultimo tempo di risposta"
|
||||
},
|
||||
"total_responses": {
|
||||
"name": "Totale Risposte"
|
||||
"name": "Risposte totali"
|
||||
},
|
||||
"error_count": {
|
||||
"name": "Numero di Errori"
|
||||
"name": "Conteggio errori"
|
||||
},
|
||||
"last_error": {
|
||||
"name": "Ultimo Errore"
|
||||
"name": "Ultimo errore"
|
||||
},
|
||||
"api_status": {
|
||||
"name": "Stato API"
|
||||
},
|
||||
"tokens_used": {
|
||||
"name": "Totale Token Utilizzati"
|
||||
"name": "Token totali utilizzati"
|
||||
},
|
||||
"average_response_time": {
|
||||
"name": "Tempo di Risposta Medio"
|
||||
"name": "Tempo medio di risposta"
|
||||
},
|
||||
"last_request_time": {
|
||||
"name": "Tempo Ultima Richiesta"
|
||||
"name": "Ultimo tempo di richiesta"
|
||||
},
|
||||
"is_processing": {
|
||||
"name": "Stato Elaborazione"
|
||||
"name": "Stato di elaborazione"
|
||||
},
|
||||
"is_rate_limited": {
|
||||
"name": "Stato Limite Velocità"
|
||||
"name": "Stato limite di frequenza"
|
||||
},
|
||||
"is_maintenance": {
|
||||
"name": "Stato Manutenzione"
|
||||
"name": "Stato di manutenzione"
|
||||
},
|
||||
"api_version": {
|
||||
"name": "Versione API"
|
||||
},
|
||||
"endpoint_status": {
|
||||
"name": "Stato Endpoint"
|
||||
"name": "Stato dell'endpoint"
|
||||
},
|
||||
"performance_metrics": {
|
||||
"name": "Metriche Prestazioni"
|
||||
"name": "Metriche di prestazione"
|
||||
},
|
||||
"history_size": {
|
||||
"name": "Dimensione Cronologia"
|
||||
"name": "Dimensione della cronologia"
|
||||
},
|
||||
"uptime": {
|
||||
"name": "Tempo di Funzionamento"
|
||||
"name": "Tempo di attività"
|
||||
},
|
||||
"total_tokens": {
|
||||
"name": "Totale Token"
|
||||
"name": "Token totali"
|
||||
},
|
||||
"prompt_tokens": {
|
||||
"name": "Token Prompt"
|
||||
"name": "Token di prompt"
|
||||
},
|
||||
"completion_tokens": {
|
||||
"name": "Token Completamento"
|
||||
"name": "Token di completamento"
|
||||
},
|
||||
"successful_requests": {
|
||||
"name": "Richieste Riuscite"
|
||||
"name": "Richieste riuscite"
|
||||
},
|
||||
"failed_requests": {
|
||||
"name": "Richieste Fallite"
|
||||
"name": "Richieste fallite"
|
||||
},
|
||||
"average_latency": {
|
||||
"name": "Latency Media"
|
||||
"name": "Latenza media"
|
||||
},
|
||||
"max_latency": {
|
||||
"name": "Latency Massima"
|
||||
"name": "Latenza massima"
|
||||
},
|
||||
"min_latency": {
|
||||
"name": "Latency Minima"
|
||||
}
|
||||
"name": "Latenza minima"
|
||||
},
|
||||
"last_model": {
|
||||
"name": "Ultimo modello utilizzato"
|
||||
},
|
||||
"last_timestamp": {
|
||||
"name": "Ora dell'ultima risposta"
|
||||
},
|
||||
"instance_name": {
|
||||
"name": "Nome istanza"
|
||||
},
|
||||
"normalized_name": {
|
||||
"name": "Nome normalizzato"
|
||||
},
|
||||
"conversation_history": {
|
||||
"name": "Cronologia conversazione"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,99 +2,152 @@
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "Выбор поставщика ИИ",
|
||||
"description": "Выберите поставщика услуг ИИ для этой инстанции.",
|
||||
"title": "Настройки провайдера",
|
||||
"description": "Укажите параметры подключения для выбранного провайдера ИИ.",
|
||||
"data": {
|
||||
"api_provider": "Поставщик API",
|
||||
"context_messages": "Количество контекстных сообщений для сохранения (1-20)"
|
||||
"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)",
|
||||
"allow_local_network": "Разрешить локальные сетевые адреса (для self-hosted прокси)",
|
||||
"disable_thinking": "Отключить режим thinking/reasoning (Qwen /no_think, срезание блоков think, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "Настройка инстанции HA Text AI",
|
||||
"description": "Настройте новую инстанцию помощника ИИ с выбранным вами поставщиком.",
|
||||
"title": "Настройка экземпляра текстового ИИ для Home Assistant",
|
||||
"description": "Настройте новый экземпляр ИИ-помощника с выбранным провайдером.",
|
||||
"data": {
|
||||
"name": "Имя инстанции (например, 'GPT Assistant', 'Claude Helper')",
|
||||
"name": "Название экземпляра (например, 'GPT Помощник', 'Клод Ассистент')",
|
||||
"api_key": "API-ключ для аутентификации",
|
||||
"model": "Используемая модель ИИ",
|
||||
"temperature": "Креативность ответа (0-2, чем ниже, тем больше фокусировки)",
|
||||
"max_tokens": "Максимальная длина ответа (1-4096 токенов)",
|
||||
"model": "Модель ИИ для использования",
|
||||
"temperature": "Креативность ответа (0-2, меньше = более сфокусированно)",
|
||||
"max_tokens": "Максимальная длина ответа (1-100000 токенов)",
|
||||
"api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)",
|
||||
"api_provider": "Поставщик API",
|
||||
"request_interval": "Минимальное время между запросами (0,1-60 секунд)",
|
||||
"context_messages": "Количество контекстных сообщений для сохранения (1-20)",
|
||||
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||
"api_provider": "Провайдер API",
|
||||
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
||||
"max_history_size": "Максимальный размер истории разговора (1-100)",
|
||||
"allow_local_network": "Разрешить локальные сетевые адреса (для self-hosted прокси)",
|
||||
"disable_thinking": "Отключить режим thinking/reasoning (Qwen /no_think, срезание блоков think, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"name_exists": "Инстанция с таким именем уже существует",
|
||||
"invalid_name": "Некорректное имя инстанции",
|
||||
"invalid_auth": "Аутентификация не удалась - проверьте ваш API-ключ",
|
||||
"invalid_api_key": "Неверный API-ключ - проверьте ваши учетные данные",
|
||||
"cannot_connect": "Не удалось подключиться к службе API",
|
||||
"history_storage_error": "Не удалось инициализировать хранилище истории. Проверьте разрешения.",
|
||||
"history_rotation_error": "Ошибка при ротации файла истории.",
|
||||
"history_file_access_error": "Невозможно получить доступ к директории хранения истории.",
|
||||
"name_exists": "Экземпляр с таким именем уже существует",
|
||||
"invalid_name": "Недопустимое имя экземпляра",
|
||||
"invalid_auth": "Ошибка аутентификации - проверьте API-ключ",
|
||||
"api_key_required": "Необходимо ввести 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": "Указана неверная инстанция",
|
||||
"invalid_response": "Получен некорректный ответ API",
|
||||
"api_error": "Произошла ошибка сервиса API",
|
||||
"timeout": "Время ожидания запроса истекло",
|
||||
"invalid_instance": "Указан некорректный экземпляр",
|
||||
"unknown": "Произошла непредвиденная ошибка",
|
||||
"empty": "Имя не может быть пустым",
|
||||
"invalid_characters": "Имя может содержать только буквы, цифры, пробелы, подчеркивания и дефисы",
|
||||
"name_too_long": "Имя должно быть не более 50 символов"
|
||||
"name_too_long": "Имя должно быть не длиннее 50 символов"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "Экземпляр уже настроен"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "Обновление настроек инстанции",
|
||||
"description": "Измените настройки для этой инстанции помощника ИИ.",
|
||||
"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-4096)",
|
||||
"request_interval": "Минимальный интервал между запросами (0,1-60 секунд)",
|
||||
"max_tokens": "Максимальная длина ответа (1-100000)",
|
||||
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||
"context_messages": "Количество предыдущих сообщений для включения в контекст (1-20)",
|
||||
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||
"max_history_size": "Максимальный размер истории разговора (1-100)",
|
||||
"allow_local_network": "Разрешить локальные сетевые адреса (для self-hosted прокси)",
|
||||
"disable_thinking": "Отключить режим thinking/reasoning (Qwen /no_think, срезание блоков think, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"selector": {
|
||||
"api_provider": {
|
||||
"options": {
|
||||
"openai": "OpenAI (совместимый)",
|
||||
"anthropic": "Anthropic (совместимый)",
|
||||
"deepseek": "DeepSeek",
|
||||
"gemini": "Google Gemini"
|
||||
}
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "Задать вопрос (HA Text AI)",
|
||||
"description": "Отправьте вопрос модели ИИ и получите подробный ответ. Ответ будет сохранен в истории разговора и может быть извлечен позже.",
|
||||
"description": "Отправить вопрос модели ИИ и получить подробный ответ. Сервис теперь возвращает данные ответа напрямую, устраняя необходимость в отдельных текстовых сенсорах и ограничение в 255 символов. Ответ также будет сохранен в истории разговора.",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Инстанция",
|
||||
"description": "Имя используемой инстанции HA Text AI"
|
||||
"name": "Экземпляр",
|
||||
"description": "Название экземпляра текстового ИИ для использования"
|
||||
},
|
||||
"question": {
|
||||
"name": "Вопрос",
|
||||
"description": "Ваш вопрос или запрос к помощнику ИИ"
|
||||
"description": "Ваш вопрос или запрос к ИИ-помощнику"
|
||||
},
|
||||
"context_messages": {
|
||||
"name": "Контекстные сообщения",
|
||||
"description": "Количество предыдущих сообщений для включения в контекст (1-20)"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "Системный запрос",
|
||||
"description": "Необязательный системный запрос для установки контекста для этого конкретного вопроса"
|
||||
"name": "Системный промпт",
|
||||
"description": "Необязательный системный промпт для установки контекста для этого конкретного вопроса"
|
||||
},
|
||||
"model": {
|
||||
"name": "Модель",
|
||||
"description": "Выберите модель ИИ для использования (необязательно, переопределяет настройку по умолчанию)"
|
||||
"description": "Выберите модель ИИ для использования (необязательно, переопределяет настройки по умолчанию)"
|
||||
},
|
||||
"temperature": {
|
||||
"name": "Температура",
|
||||
"description": "Управляет креативностью ответа (0.0-2.0)"
|
||||
"description": "Управление креативностью ответа (0.0-2.0)"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "Макс. токенов",
|
||||
"description": "Максимальная длина ответа (1-4096 токенов)"
|
||||
"name": "Максимум токенов",
|
||||
"description": "Максимальная длина ответа (1-100000 токенов)"
|
||||
},
|
||||
"structured_output": {
|
||||
"name": "Структурированный вывод",
|
||||
"description": "Включить режим структурированного JSON-вывода. При включении ИИ будет отвечать валидным JSON, соответствующим указанной схеме."
|
||||
},
|
||||
"json_schema": {
|
||||
"name": "JSON Schema",
|
||||
"description": "JSON-схема, определяющая структуру ожидаемого ответа. Обязательна при включении structured_output."
|
||||
},
|
||||
"disable_thinking": {
|
||||
"name": "Отключить thinking",
|
||||
"description": "Отключить режим thinking/reasoning для этого запроса. Переопределяет настройку интеграции."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -103,18 +156,18 @@
|
||||
"description": "Удалить все сохраненные вопросы и ответы из истории разговора",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Инстанция",
|
||||
"description": "Имя инстанции HA Text AI, для которой нужно очистить историю"
|
||||
"name": "Экземпляр",
|
||||
"description": "Название экземпляра текстового ИИ для очистки истории"
|
||||
}
|
||||
}
|
||||
},
|
||||
"get_history": {
|
||||
"name": "Получить историю",
|
||||
"description": "Извлечь историю разговора с возможностью фильтрации и сортировки",
|
||||
"description": "Получить историю разговора с дополнительной фильтрацией и сортировкой",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Инстанция",
|
||||
"description": "Имя инстанции HA Text AI, из которой нужно получить историю"
|
||||
"name": "Экземпляр",
|
||||
"description": "Название экземпляра текстового ИИ для получения истории"
|
||||
},
|
||||
"limit": {
|
||||
"name": "Лимит",
|
||||
@@ -122,33 +175,33 @@
|
||||
},
|
||||
"filter_model": {
|
||||
"name": "Фильтр модели",
|
||||
"description": "Фильтрация разговоров по определенной модели ИИ"
|
||||
"description": "Фильтрация разговоров по конкретной модели ИИ"
|
||||
},
|
||||
"start_date": {
|
||||
"name": "Дата начала",
|
||||
"description": "Фильтрация разговоров, начиная с этой даты/времени"
|
||||
"name": "Начальная дата",
|
||||
"description": "Фильтрация разговоров, начиная с указанной даты/времени"
|
||||
},
|
||||
"include_metadata": {
|
||||
"name": "Включить метаданные",
|
||||
"description": "Включить дополнительную информацию, такую как использованные токены, время ответа и т.д."
|
||||
"description": "Включить дополнительную информацию, например, использованные токены, время ответа и т.д."
|
||||
},
|
||||
"sort_order": {
|
||||
"name": "Порядок сортировки",
|
||||
"description": "Порядок сортировки результатов (самые новые или самые старые)"
|
||||
"description": "Порядок сортировки результатов (сначала новые или старые)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"set_system_prompt": {
|
||||
"name": "Установить системный запрос",
|
||||
"description": "Установить инструкции по умолчанию для поведения системы для всех будущих разговоров",
|
||||
"name": "Установить системный промпт",
|
||||
"description": "Установить инструкции по умолчанию для поведения ИИ во всех будущих разговорах",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Инстанция",
|
||||
"description": "Имя инстанции HA Text AI, для которой нужно установить системный запрос"
|
||||
"name": "Экземпляр",
|
||||
"description": "Название экземпляра текстового ИИ для установки системного промпта"
|
||||
},
|
||||
"prompt": {
|
||||
"name": "Системный запрос",
|
||||
"description": "Инструкции, определяющие, как ИИ должен себя вести и отвечать"
|
||||
"name": "Системный промпт",
|
||||
"description": "Инструкции, определяющие, как ИИ должен вести себя и отвечать"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -165,8 +218,7 @@
|
||||
"rate_limited": "Лимит запросов",
|
||||
"maintenance": "Техническое обслуживание",
|
||||
"initializing": "Инициализация",
|
||||
"retrying": "Повторная попытка",
|
||||
"queued": "В очереди"
|
||||
"retrying": "Повторная попытка"
|
||||
},
|
||||
"state_attributes": {
|
||||
"question": {
|
||||
@@ -182,10 +234,10 @@
|
||||
"name": "Температура"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "Макс. токенов"
|
||||
"name": "Максимум токенов"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "Системный запрос"
|
||||
"name": "Системный промпт"
|
||||
},
|
||||
"response_time": {
|
||||
"name": "Время последнего ответа"
|
||||
@@ -203,7 +255,7 @@
|
||||
"name": "Статус API"
|
||||
},
|
||||
"tokens_used": {
|
||||
"name": "Использовано токенов всего"
|
||||
"name": "Всего использовано токенов"
|
||||
},
|
||||
"average_response_time": {
|
||||
"name": "Среднее время ответа"
|
||||
@@ -215,10 +267,10 @@
|
||||
"name": "Статус обработки"
|
||||
},
|
||||
"is_rate_limited": {
|
||||
"name": "Статус ограничения запросов"
|
||||
"name": "Статус лимита запросов"
|
||||
},
|
||||
"is_maintenance": {
|
||||
"name": "Статус технического обслуживания"
|
||||
"name": "Статус обслуживания"
|
||||
},
|
||||
"api_version": {
|
||||
"name": "Версия API"
|
||||
@@ -227,7 +279,7 @@
|
||||
"name": "Статус конечной точки"
|
||||
},
|
||||
"performance_metrics": {
|
||||
"name": "Метрики производительности"
|
||||
"name": "Показатели производительности"
|
||||
},
|
||||
"history_size": {
|
||||
"name": "Размер истории"
|
||||
@@ -239,16 +291,16 @@
|
||||
"name": "Всего токенов"
|
||||
},
|
||||
"prompt_tokens": {
|
||||
"name": "Токены запроса"
|
||||
"name": "Токены промпта"
|
||||
},
|
||||
"completion_tokens": {
|
||||
"name": "Токены завершения"
|
||||
},
|
||||
"successful_requests": {
|
||||
"name": "Успешных запросов"
|
||||
"name": "Успешные запросы"
|
||||
},
|
||||
"failed_requests": {
|
||||
"name": "Неудачных запросов"
|
||||
"name": "Неудачные запросы"
|
||||
},
|
||||
"average_latency": {
|
||||
"name": "Средняя задержка"
|
||||
@@ -258,6 +310,24 @@
|
||||
},
|
||||
"min_latency": {
|
||||
"name": "Минимальная задержка"
|
||||
},
|
||||
"last_model": {
|
||||
"name": "Последняя использованная модель"
|
||||
},
|
||||
"last_timestamp": {
|
||||
"name": "Время последнего ответа"
|
||||
},
|
||||
"instance_name": {
|
||||
"name": "Имя экземпляра"
|
||||
},
|
||||
"normalized_name": {
|
||||
"name": "Нормализованное имя"
|
||||
},
|
||||
"last_error": {
|
||||
"name": "Последняя ошибка"
|
||||
},
|
||||
"conversation_history": {
|
||||
"name": "История разговоров"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,153 +2,206 @@
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "Изаберите добављача вештачке интелигенције",
|
||||
"description": "Изаберите добављача услуга вештачке интелигенције који ћете користити за ову инстанцу.",
|
||||
"title": "Подешавања провајдера",
|
||||
"description": "Обезбедите детаље о вези за изабраног AI провајдера.",
|
||||
"data": {
|
||||
"api_provider": "Добављач API-ја",
|
||||
"context_messages": "Број порука контекста које треба задржати (1-20)"
|
||||
"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)",
|
||||
"allow_local_network": "Дозволи локалне мрежне адресе (за self-hosted проксије)",
|
||||
"disable_thinking": "Онемогући thinking/reasoning режим (Qwen /no_think, уклања think блокове, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "Конфигуришите инстанцу HA Text AI",
|
||||
"description": "Поставите нову инстанцу асистента вештачке интелигенције са изабраним добављачем.",
|
||||
"title": "Конфигуришите HA Text AI инстанцу",
|
||||
"description": "Подесите нову AI асистент инстанцу са изабраним провајдером.",
|
||||
"data": {
|
||||
"name": "Назив инстанце (нпр. 'GPT Assistant', 'Claude Helper')",
|
||||
"name": "Име инстанце (нпр. 'GPT Асистент', 'Claude Помоћник')",
|
||||
"api_key": "API кључ за аутентификацију",
|
||||
"model": "Модел вештачке интелигенције који треба користити",
|
||||
"temperature": "Креативност одговора (0-2, нижа = више фокусирана)",
|
||||
"max_tokens": "Максимална дужина одговора (1-4096 токена)",
|
||||
"api_endpoint": "Прилагођени URL завршног тачка API-ја (опционо)",
|
||||
"api_provider": "Добављач API-ја",
|
||||
"model": "AI модел који ће се користити",
|
||||
"temperature": "Креативност одговора (0-2, нижа = фокусираније)",
|
||||
"max_tokens": "Максимална дужина одговора (1-100000 токена)",
|
||||
"api_endpoint": "Прилагођени URL API крајње тачке (опционо)",
|
||||
"api_provider": "API провајдер",
|
||||
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
||||
"context_messages": "Број порука контекста које треба задржати (1-20)",
|
||||
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||
"api_timeout": "Временско ограничење API захтева у секундама (5-600)",
|
||||
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
||||
"max_history_size": "Максимална величина историје разговора (1-100)",
|
||||
"allow_local_network": "Дозволи локалне мрежне адресе (за self-hosted проксије)",
|
||||
"disable_thinking": "Онемогући thinking/reasoning режим (Qwen /no_think, уклања think блокове, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"name_exists": "Инстанца са овим називом већ постоји",
|
||||
"invalid_name": "Неважећи назив инстанце",
|
||||
"invalid_auth": "Аутентификација није успела - проверите свој API кључ",
|
||||
"invalid_api_key": "Неважећи API кључ - проверите своје податке о верификацији",
|
||||
"cannot_connect": "Није могуће успоставити везу са услугом API-ја",
|
||||
"history_storage_error": "Неуспела инициализација складишта историје. Проверите дозволе.",
|
||||
"history_rotation_error": "Грешка током ротације историјских датотека.",
|
||||
"history_file_access_error": "Немогуће приступити директоријуму складишта историје.",
|
||||
"name_exists": "Инстанца са овим именом већ постоји",
|
||||
"invalid_name": "Неважеће име инстанце",
|
||||
"invalid_auth": "Аутентификација није успела - проверите ваш API кључ",
|
||||
"api_key_required": "API кључ је обавезан при промени провајдера или endpoint-а",
|
||||
"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 карактера или мање"
|
||||
"rate_limit": "Пређена граница захтева",
|
||||
"context_length": "Дужина контекста пређена",
|
||||
"rate_limit_exceeded": "Пређена граница API захтева",
|
||||
"maintenance": "Сервис је у одржавању",
|
||||
"invalid_response": "Примљен неважећи API одговор",
|
||||
"api_error": "Дошло је до грешке у API сервису",
|
||||
"timeout": "Време захтева је истекло",
|
||||
"invalid_instance": "Неважећа инстанца је назначена",
|
||||
"unknown": "Дошло је до неочекиване грешке",
|
||||
"empty": "Име не може бити празно",
|
||||
"name_too_long": "Име мора бити 50 знакова или мање"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "Инстанца је већ конфигурисана"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "Ажурирајте подешавања инстанце",
|
||||
"description": "Измените подешавања за ову инстанцу асистента вештачке интелигенције.",
|
||||
"title": "Изаберите провајдера",
|
||||
"description": "Изаберите AI провајдера за ову инстанцу. Интеграција ће се поново учитати након чувања измена.",
|
||||
"data": {
|
||||
"model": "Модел вештачке интелигенције",
|
||||
"temperature": "Креативност одговора (0-2)",
|
||||
"max_tokens": "Максимална дужина одговора (1-4096)",
|
||||
"request_interval": "Минимални интервал захтева (0.1-60 секунди)",
|
||||
"context_messages": "Број претходних порука које треба укључити у контекст (1-20)",
|
||||
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||
"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)",
|
||||
"allow_local_network": "Дозволи локалне мрежне адресе (за self-hosted проксије)",
|
||||
"disable_thinking": "Онемогући thinking/reasoning режим (Qwen /no_think, уклања think блокове, Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"selector": {
|
||||
"api_provider": {
|
||||
"options": {
|
||||
"openai": "OpenAI (компатибилан)",
|
||||
"anthropic": "Anthropic (компатибилан)",
|
||||
"deepseek": "DeepSeek",
|
||||
"gemini": "Google Gemini"
|
||||
}
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "Поставите питање (HA Text AI)",
|
||||
"description": "Пошаљите питање моделу вештачке интелигенције и добијте детаљан одговор. Одговор ће бити сачуван у историји разговора и може се касније преузети.",
|
||||
"description": "Пошаљите питање AI моделу и добијте детаљан одговор. Овај сервис сада враћа податке одговора директно, елиминишући потребу за засебним текстуалним сензорима и ограничење од 255 карактера. Одговор ће такође бити сачуван у историји разговора.",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Инстанца",
|
||||
"description": "Назив инстанце HA Text AI коју треба користити"
|
||||
"description": "Име HA Text AI инстанце коју ћете користити"
|
||||
},
|
||||
"question": {
|
||||
"name": "Питање",
|
||||
"description": "Ваше питање или наговештај за асистента вештачке интелигенције"
|
||||
"description": "Ваше питање или упит за AI асистента"
|
||||
},
|
||||
"context_messages": {
|
||||
"name": "Поруке контекста",
|
||||
"name": "Контекстуалне поруке",
|
||||
"description": "Број претходних порука које треба укључити у контекст (1-20)"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "Системски наговештај",
|
||||
"description": "Опциони системски наговештај за постављање контекста за ово одређено питање"
|
||||
"name": "Системски упит",
|
||||
"description": "Опционални системски упит за постављање контекста за ово конкретно питање"
|
||||
},
|
||||
"model": {
|
||||
"name": "Модел",
|
||||
"description": "Изаберите модел вештачке интелигенције који треба користити (опционо, преклапа подразумевано подешавање)"
|
||||
"description": "Изаберите AI модел који ћете користити (опционо, надмашује подразумевану поставку)"
|
||||
},
|
||||
"temperature": {
|
||||
"name": "Температура",
|
||||
"description": "Контролише креативност одговора (0.0-2.0)"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "Макс. токени",
|
||||
"description": "Максимална дужина одговора (1-4096 токена)"
|
||||
"name": "Максимални токени",
|
||||
"description": "Максимална дужина одговора (1-100000 токена)"
|
||||
},
|
||||
"structured_output": {
|
||||
"name": "Структурисани излаз",
|
||||
"description": "Омогући JSON структурисани излаз. Када је омогућено, AI ће одговарати валидним JSON-ом који одговара датој шеми."
|
||||
},
|
||||
"json_schema": {
|
||||
"name": "JSON шема",
|
||||
"description": "JSON шема која дефинише структуру очекиваног одговора. Обавезна када је structured_output омогућен."
|
||||
},
|
||||
"disable_thinking": {
|
||||
"name": "Онемогући thinking",
|
||||
"description": "Онемогући thinking/reasoning режим за овај захтев. Надмашује поставку интеграције."
|
||||
}
|
||||
}
|
||||
},
|
||||
"clear_history": {
|
||||
"name": "Обриши историју",
|
||||
"description": "Обришите сва сачувана питања и одговоре из историје разговора",
|
||||
"description": "Избришите све сачуване питања и одговоре из историје разговора",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Инстанца",
|
||||
"description": "Назив инстанце HA Text AI за коју треба очистити историју"
|
||||
"description": "Име HA Text AI инстанце за коју желите да обришете историју"
|
||||
}
|
||||
}
|
||||
},
|
||||
"get_history": {
|
||||
"name": "Добиј историју",
|
||||
"description": "Преузмите историју разговора са опционом филтрацијом и сортирањем",
|
||||
"name": "Добијте историју",
|
||||
"description": "Повратите историју разговора уз опционално филтрирање и сортирање",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Инстанца",
|
||||
"description": "Назив инстанце HA Text AI из које треба добити историју"
|
||||
"description": "Име HA Text AI инстанце из које желите да добијете историју"
|
||||
},
|
||||
"limit": {
|
||||
"name": "Лимит",
|
||||
"description": "Број разговора који треба вратити (1-100)"
|
||||
"description": "Број разговора које треба вратити (1-100)"
|
||||
},
|
||||
"filter_model": {
|
||||
"name": "Филтер модела",
|
||||
"description": "Филтрирајте разговоре по одређеном моделу вештачке интелигенције"
|
||||
"name": "Филтер модел",
|
||||
"description": "Филтрирајте разговоре по одређеном AI моделу"
|
||||
},
|
||||
"start_date": {
|
||||
"name": "Почетни датум",
|
||||
"description": "Филтрирајте разговоре почев од овог датума/времена"
|
||||
"name": "Датум почетка",
|
||||
"description": "Филтрирајте разговоре који почињу од овог датума/времена"
|
||||
},
|
||||
"include_metadata": {
|
||||
"name": "Укључи метаподатке",
|
||||
"description": "Укључите додатне информације попут коришћених токена, времена одговора и слично."
|
||||
"description": "Укључите додатне информације као што су коришћени токени, време одговора итд."
|
||||
},
|
||||
"sort_order": {
|
||||
"name": "Редослед сортирања",
|
||||
"description": "Редослед сортирања за резултате (најновији или најстарији прво)"
|
||||
"description": "Редослед сортирања за резултате (најновији или најстарији први)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"set_system_prompt": {
|
||||
"name": "Поставите системски наговештај",
|
||||
"description": "Поставите подразумевана упутства за понашање система за све будуће разговоре",
|
||||
"name": "Поставите системски упит",
|
||||
"description": "Поставите подразумеване инструкције за системско понашање за све будуће разговоре",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "Инстанца",
|
||||
"description": "Назив инстанце HA Text AI за коју треба поставити системски наговештај"
|
||||
"description": "Име HA Text AI инстанце за коју желите да поставите системски упит"
|
||||
},
|
||||
"prompt": {
|
||||
"name": "Системски наговештај",
|
||||
"description": "Упутства која дефинишу како би се вештачка интелигенција требала понашати и одговарати"
|
||||
"name": "Системски упит",
|
||||
"description": "Инструкције које дефинишу како AI треба да се понаша и одговара"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -162,11 +215,10 @@
|
||||
"processing": "Обрада",
|
||||
"error": "Грешка",
|
||||
"disconnected": "Искључено",
|
||||
"rate_limited": "Лимит стопе",
|
||||
"rate_limited": "Ограничење захтева",
|
||||
"maintenance": "Одржавање",
|
||||
"initializing": "Иницијализација",
|
||||
"retrying": "Понављање",
|
||||
"queued": "У реду чекања"
|
||||
"initializing": "Инициализује се",
|
||||
"retrying": "Покушава поново"
|
||||
},
|
||||
"state_attributes": {
|
||||
"question": {
|
||||
@@ -182,16 +234,16 @@
|
||||
"name": "Температура"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "Макс. токени"
|
||||
"name": "Максимални токени"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "Системски наговештај"
|
||||
"name": "Системски упит"
|
||||
},
|
||||
"response_time": {
|
||||
"name": "Време последњег одговора"
|
||||
},
|
||||
"total_responses": {
|
||||
"name": "Укупан број одговора"
|
||||
"name": "Укупно одговора"
|
||||
},
|
||||
"error_count": {
|
||||
"name": "Број грешака"
|
||||
@@ -200,10 +252,10 @@
|
||||
"name": "Последња грешка"
|
||||
},
|
||||
"api_status": {
|
||||
"name": "Статус API-ја"
|
||||
"name": "Статус API"
|
||||
},
|
||||
"tokens_used": {
|
||||
"name": "Укупно коришћених токена"
|
||||
"name": "Укупно коришћени токени"
|
||||
},
|
||||
"average_response_time": {
|
||||
"name": "Просечно време одговора"
|
||||
@@ -215,34 +267,34 @@
|
||||
"name": "Статус обраде"
|
||||
},
|
||||
"is_rate_limited": {
|
||||
"name": "Статус ограничења стопе"
|
||||
"name": "Статус ограничења захтева"
|
||||
},
|
||||
"is_maintenance": {
|
||||
"name": "Статус одржавања"
|
||||
},
|
||||
"api_version": {
|
||||
"name": "Верзија API-ја"
|
||||
"name": "Верзија API"
|
||||
},
|
||||
"endpoint_status": {
|
||||
"name": "Статус завршне тачке"
|
||||
"name": "Статус крајње тачке"
|
||||
},
|
||||
"performance_metrics": {
|
||||
"name": "Метрике перформанси"
|
||||
"name": "Перформансне метрике"
|
||||
},
|
||||
"history_size": {
|
||||
"name": "Величина историје"
|
||||
},
|
||||
"uptime": {
|
||||
"name": "Време рада"
|
||||
"name": "Уптиме"
|
||||
},
|
||||
"total_tokens": {
|
||||
"name": "Укупан број токена"
|
||||
"name": "Укупно токена"
|
||||
},
|
||||
"prompt_tokens": {
|
||||
"name": "Токени наговештаја"
|
||||
"name": "Токени упита"
|
||||
},
|
||||
"completion_tokens": {
|
||||
"name": "Токени довршетака"
|
||||
"name": "Токени завршетка"
|
||||
},
|
||||
"successful_requests": {
|
||||
"name": "Успешни захтеви"
|
||||
@@ -258,6 +310,21 @@
|
||||
},
|
||||
"min_latency": {
|
||||
"name": "Минимална латенција"
|
||||
},
|
||||
"last_model": {
|
||||
"name": "Последњи коришћени модел"
|
||||
},
|
||||
"last_timestamp": {
|
||||
"name": "Време последњег одговора"
|
||||
},
|
||||
"instance_name": {
|
||||
"name": "Назив инстанце"
|
||||
},
|
||||
"normalized_name": {
|
||||
"name": "Нормализовани назив"
|
||||
},
|
||||
"conversation_history": {
|
||||
"name": "Историја разговора"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,153 +2,206 @@
|
||||
"config": {
|
||||
"step": {
|
||||
"provider": {
|
||||
"title": "选择 AI 提供商",
|
||||
"description": "选择要用于此实例的 AI 服务提供商。",
|
||||
"title": "提供者设置",
|
||||
"description": "提供所选AI提供者的连接详细信息。",
|
||||
"data": {
|
||||
"api_provider": "API 提供商",
|
||||
"context_messages": "要保留的上下文消息数量 (1-20)"
|
||||
"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)",
|
||||
"allow_local_network": "允许本地网络端点(用于自托管代理)",
|
||||
"disable_thinking": "禁用思考/推理模式(Qwen /no_think,移除 think 块,Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
},
|
||||
"user": {
|
||||
"title": "配置 HA Text AI 实例",
|
||||
"description": "使用您选择的提供商设置新的 AI 助手实例。",
|
||||
"title": "配置HA文本AI实例",
|
||||
"description": "使用所选提供者设置新的AI助手实例。",
|
||||
"data": {
|
||||
"name": "实例名称(例如,“GPT 助手”、“Claude 助手”)",
|
||||
"api_key": "用于身份验证的 API 密钥",
|
||||
"model": "要使用的 AI 模型",
|
||||
"temperature": "回复创意度 (0-2,数值越低,回复越聚焦)",
|
||||
"max_tokens": "最大回复长度(1-4096 个 Token)",
|
||||
"api_endpoint": "自定义 API 端点 URL(可选)",
|
||||
"api_provider": "API 提供商",
|
||||
"request_interval": "请求之间的最短时间间隔(0.1-60 秒)",
|
||||
"context_messages": "要保留的上下文消息数量 (1-20)",
|
||||
"max_history_size": "最大对话历史记录大小 (1-100)"
|
||||
"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)",
|
||||
"allow_local_network": "允许本地网络端点(用于自托管代理)",
|
||||
"disable_thinking": "禁用思考/推理模式(Qwen /no_think,移除 think 块,Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"error": {
|
||||
"name_exists": "已存在具有此名称的实例",
|
||||
"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_auth": "身份验证失败 - 检查您的API密钥",
|
||||
"api_key_required": "更改提供商或端点时需要输入 API 密钥",
|
||||
"invalid_api_key": "无效的API密钥 - 请验证您的凭据",
|
||||
"cannot_connect": "无法连接到API服务",
|
||||
"invalid_model": "所选模型不可用",
|
||||
"rate_limit": "超出速率限制",
|
||||
"context_length": "上下文长度超出限制",
|
||||
"rate_limit_exceeded": "API 速率限制已超出",
|
||||
"rate_limit_exceeded": "API速率限制超出",
|
||||
"maintenance": "服务正在维护中",
|
||||
"invalid_response": "收到无效的 API 响应",
|
||||
"api_error": "发生 API 服务错误",
|
||||
"invalid_response": "收到无效的API响应",
|
||||
"api_error": "发生API服务错误",
|
||||
"timeout": "请求超时",
|
||||
"invalid_instance": "指定的实例无效",
|
||||
"unknown": "发生意外错误",
|
||||
"empty": "名称不能为空",
|
||||
"invalid_characters": "名称只能包含字母、数字、空格、下划线和连字符",
|
||||
"name_too_long": "名称必须为 50 个字符或更少"
|
||||
"name_too_long": "名称必须少于50个字符"
|
||||
},
|
||||
"abort": {
|
||||
"already_configured": "实例已配置"
|
||||
}
|
||||
},
|
||||
"options": {
|
||||
"step": {
|
||||
"init": {
|
||||
"title": "更新实例设置",
|
||||
"description": "修改此 AI 助手实例的设置。",
|
||||
"title": "选择提供者",
|
||||
"description": "选择此实例的AI提供者。保存更改后集成将重新加载。",
|
||||
"data": {
|
||||
"model": "AI 模型",
|
||||
"temperature": "回复创意度 (0-2)",
|
||||
"max_tokens": "最大回复长度 (1-4096)",
|
||||
"request_interval": "最短请求间隔 (0.1-60 秒)",
|
||||
"context_messages": "包含在上下文中的先前消息数 (1-20)",
|
||||
"max_history_size": "最大对话历史记录大小 (1-100)"
|
||||
"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)",
|
||||
"allow_local_network": "允许本地网络端点(用于自托管代理)",
|
||||
"disable_thinking": "禁用思考/推理模式(Qwen /no_think,移除 think 块,Gemini 2.5 thinking_budget=0)"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"selector": {
|
||||
"api_provider": {
|
||||
"options": {
|
||||
"openai": "OpenAI(兼容)",
|
||||
"anthropic": "Anthropic(兼容)",
|
||||
"deepseek": "DeepSeek",
|
||||
"gemini": "Google Gemini"
|
||||
}
|
||||
}
|
||||
},
|
||||
"services": {
|
||||
"ask_question": {
|
||||
"name": "提问 (HA Text AI)",
|
||||
"description": "向 AI 模型发送问题并接收详细的回复。回复将存储在对话历史记录中,以后可以检索。",
|
||||
"description": "向AI模型发送问题并获得详细回答。此服务现在直接返回响应数据,消除了对单独文本传感器的需要和255字符限制。响应也将存储在对话历史中。",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "实例",
|
||||
"description": "要使用的 HA Text AI 实例的名称"
|
||||
"description": "要使用的HA文本AI实例名称"
|
||||
},
|
||||
"question": {
|
||||
"name": "问题",
|
||||
"description": "您要向 AI 助手提出的问题或提示"
|
||||
"description": "您对AI助手的问题或提示"
|
||||
},
|
||||
"context_messages": {
|
||||
"name": "上下文消息",
|
||||
"description": "包含在上下文中的先前消息数 (1-20)"
|
||||
"description": "要包含在上下文中的先前消息数量(1-20)"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "系统提示",
|
||||
"description": "可选系统提示,用于为特定问题设置上下文"
|
||||
"description": "可选的系统提示,用于为此特定问题设置上下文"
|
||||
},
|
||||
"model": {
|
||||
"name": "模型",
|
||||
"description": "选择要使用的 AI 模型(可选,覆盖默认设置)"
|
||||
"description": "选择要使用的AI模型(可选,覆盖默认设置)"
|
||||
},
|
||||
"temperature": {
|
||||
"name": "温度",
|
||||
"description": "控制回复创意度 (0.0-2.0)"
|
||||
"description": "控制响应创造力(0.0-2.0)"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "最大 Token 数",
|
||||
"description": "回复的最大长度(1-4096 个 Token)"
|
||||
"name": "最大标记数",
|
||||
"description": "响应的最大长度(1-100000个标记)"
|
||||
},
|
||||
"structured_output": {
|
||||
"name": "结构化输出",
|
||||
"description": "启用JSON结构化输出模式。启用后,AI将以符合提供的模式的有效JSON进行响应。"
|
||||
},
|
||||
"json_schema": {
|
||||
"name": "JSON模式",
|
||||
"description": "定义预期响应结构的JSON模式。启用structured_output时必需。"
|
||||
},
|
||||
"disable_thinking": {
|
||||
"name": "禁用思考",
|
||||
"description": "为此请求禁用思考/推理模式。覆盖集成级别的设置。"
|
||||
}
|
||||
}
|
||||
},
|
||||
"clear_history": {
|
||||
"name": "清除历史记录",
|
||||
"description": "删除对话历史记录中所有存储的问题和回复",
|
||||
"name": "清除历史",
|
||||
"description": "删除对话历史中存储的所有问题和响应",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "实例",
|
||||
"description": "要清除历史记录的 HA Text AI 实例的名称"
|
||||
"description": "要清除历史的HA文本AI实例名称"
|
||||
}
|
||||
}
|
||||
},
|
||||
"get_history": {
|
||||
"name": "获取历史记录",
|
||||
"description": "检索对话历史记录,并可选择进行过滤和排序",
|
||||
"name": "获取历史",
|
||||
"description": "检索对话历史,可选的过滤和排序",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "实例",
|
||||
"description": "要从中获取历史记录的 HA Text AI 实例的名称"
|
||||
"description": "要获取历史的HA文本AI实例名称"
|
||||
},
|
||||
"limit": {
|
||||
"name": "限制",
|
||||
"description": "要返回的对话数量 (1-100)"
|
||||
"description": "要返回的对话数量(1-100)"
|
||||
},
|
||||
"filter_model": {
|
||||
"name": "筛选模型",
|
||||
"description": "按特定 AI 模型筛选对话"
|
||||
"name": "过滤模型",
|
||||
"description": "按特定AI模型过滤对话"
|
||||
},
|
||||
"start_date": {
|
||||
"name": "开始日期",
|
||||
"description": "从该日期/时间开始筛选对话"
|
||||
"description": "过滤从此日期/时间开始的对话"
|
||||
},
|
||||
"include_metadata": {
|
||||
"name": "包含元数据",
|
||||
"description": "包含其他信息,例如使用的 Token 数、响应时间等。"
|
||||
"description": "包括额外信息,如使用的标记、响应时间等。"
|
||||
},
|
||||
"sort_order": {
|
||||
"name": "排序顺序",
|
||||
"description": "结果的排序顺序(最新的或最早的优先)"
|
||||
"description": "结果的排序顺序(最新或最旧优先)"
|
||||
}
|
||||
}
|
||||
},
|
||||
"set_system_prompt": {
|
||||
"name": "设置系统提示",
|
||||
"description": "为所有将来的对话设置默认系统行为说明",
|
||||
"description": "为所有未来的对话设置默认的系统行为指令",
|
||||
"fields": {
|
||||
"instance": {
|
||||
"name": "实例",
|
||||
"description": "要为其设置系统提示的 HA Text AI 实例的名称"
|
||||
"description": "要设置系统提示的HA文本AI实例名称"
|
||||
},
|
||||
"prompt": {
|
||||
"name": "系统提示",
|
||||
"description": "定义 AI 如何行为和响应的说明"
|
||||
"description": "定义AI应如何行为和响应的指令"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -158,22 +211,21 @@
|
||||
"ha_text_ai": {
|
||||
"name": "{name}",
|
||||
"state": {
|
||||
"ready": "就绪",
|
||||
"ready": "准备就绪",
|
||||
"processing": "处理中",
|
||||
"error": "错误",
|
||||
"disconnected": "已断开连接",
|
||||
"rate_limited": "速率限制",
|
||||
"maintenance": "维护",
|
||||
"maintenance": "维护中",
|
||||
"initializing": "初始化中",
|
||||
"retrying": "重试中",
|
||||
"queued": "排队中"
|
||||
"retrying": "重试中"
|
||||
},
|
||||
"state_attributes": {
|
||||
"question": {
|
||||
"name": "最后一个问题"
|
||||
"name": "最后问题"
|
||||
},
|
||||
"response": {
|
||||
"name": "最后一个回复"
|
||||
"name": "最后响应"
|
||||
},
|
||||
"model": {
|
||||
"name": "当前模型"
|
||||
@@ -182,34 +234,34 @@
|
||||
"name": "温度"
|
||||
},
|
||||
"max_tokens": {
|
||||
"name": "最大 Token 数"
|
||||
"name": "最大标记数"
|
||||
},
|
||||
"system_prompt": {
|
||||
"name": "系统提示"
|
||||
},
|
||||
"response_time": {
|
||||
"name": "上次回复时间"
|
||||
"name": "最后响应时间"
|
||||
},
|
||||
"total_responses": {
|
||||
"name": "总回复次数"
|
||||
"name": "总响应数"
|
||||
},
|
||||
"error_count": {
|
||||
"name": "错误计数"
|
||||
},
|
||||
"last_error": {
|
||||
"name": "上次错误"
|
||||
"name": "最后错误"
|
||||
},
|
||||
"api_status": {
|
||||
"name": "API 状态"
|
||||
"name": "API状态"
|
||||
},
|
||||
"tokens_used": {
|
||||
"name": "已使用的 Token 总数"
|
||||
"name": "总使用标记数"
|
||||
},
|
||||
"average_response_time": {
|
||||
"name": "平均回复时间"
|
||||
"name": "平均响应时间"
|
||||
},
|
||||
"last_request_time": {
|
||||
"name": "上次请求时间"
|
||||
"name": "最后请求时间"
|
||||
},
|
||||
"is_processing": {
|
||||
"name": "处理状态"
|
||||
@@ -221,7 +273,7 @@
|
||||
"name": "维护状态"
|
||||
},
|
||||
"api_version": {
|
||||
"name": "API 版本"
|
||||
"name": "API版本"
|
||||
},
|
||||
"endpoint_status": {
|
||||
"name": "端点状态"
|
||||
@@ -230,19 +282,19 @@
|
||||
"name": "性能指标"
|
||||
},
|
||||
"history_size": {
|
||||
"name": "历史记录大小"
|
||||
"name": "历史大小"
|
||||
},
|
||||
"uptime": {
|
||||
"name": "正常运行时间"
|
||||
},
|
||||
"total_tokens": {
|
||||
"name": "总 Token 数"
|
||||
"name": "总标记数"
|
||||
},
|
||||
"prompt_tokens": {
|
||||
"name": "提示 Token 数"
|
||||
"name": "提示标记数"
|
||||
},
|
||||
"completion_tokens": {
|
||||
"name": "完成 Token 数"
|
||||
"name": "完成标记数"
|
||||
},
|
||||
"successful_requests": {
|
||||
"name": "成功请求数"
|
||||
@@ -258,6 +310,21 @@
|
||||
},
|
||||
"min_latency": {
|
||||
"name": "最小延迟"
|
||||
},
|
||||
"last_model": {
|
||||
"name": "最近使用的模型"
|
||||
},
|
||||
"last_timestamp": {
|
||||
"name": "最近响应时间"
|
||||
},
|
||||
"instance_name": {
|
||||
"name": "实例名称"
|
||||
},
|
||||
"normalized_name": {
|
||||
"name": "规范化名称"
|
||||
},
|
||||
"conversation_history": {
|
||||
"name": "对话历史"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
"""
|
||||
Utility functions for HA Text AI integration.
|
||||
|
||||
@license: MIT (https://opensource.org/licenses/MIT)
|
||||
@author: SMKRV
|
||||
@github: https://github.com/smkrv/ha-text-ai
|
||||
@source: https://github.com/smkrv/ha-text-ai
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import logging
|
||||
import socket
|
||||
from typing import Any
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import aiohttp
|
||||
from aiohttp.abc import AbstractResolver
|
||||
|
||||
from homeassistant.const import CONF_API_KEY
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
def normalize_name(name: str) -> str:
|
||||
"""Normalize name to conform to HA naming convention using underscores.
|
||||
|
||||
If the input collapses to an empty string (all non-alphanumeric or
|
||||
all underscores), fall back to a short hash of the original so that
|
||||
downstream entity IDs never end with a trailing underscore.
|
||||
"""
|
||||
normalized = ''.join(c if c.isalnum() or c == '_' else '_' for c in name)
|
||||
normalized = '_'.join(filter(None, normalized.split('_'))).lower()
|
||||
if not normalized:
|
||||
digest = hashlib.sha256(name.encode("utf-8", errors="replace")).hexdigest()[:8]
|
||||
normalized = f"instance_{digest}"
|
||||
return normalized
|
||||
|
||||
def safe_log_data(
|
||||
data: dict[str, Any],
|
||||
sensitive_keys: tuple[str, ...] = (CONF_API_KEY,),
|
||||
) -> dict[str, Any]:
|
||||
"""Filter sensitive keys from data for safe logging."""
|
||||
return {k: "***" if k in sensitive_keys else v for k, v in data.items()}
|
||||
|
||||
class _RestrictedIPError(ValueError):
|
||||
"""Raised when an IP address is in a restricted range."""
|
||||
|
||||
def _check_ip_restricted(addr: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
|
||||
"""Check if an IP address is in a restricted range."""
|
||||
return (
|
||||
addr.is_private
|
||||
or addr.is_reserved
|
||||
or addr.is_loopback
|
||||
or addr.is_link_local
|
||||
or addr.is_multicast
|
||||
or addr.is_unspecified
|
||||
)
|
||||
|
||||
def _is_cloud_metadata_or_unsafe(
|
||||
addr: ipaddress.IPv4Address | ipaddress.IPv6Address,
|
||||
) -> bool:
|
||||
"""Block link-local and cloud instance-metadata addresses.
|
||||
|
||||
These must be blocked even in allow_local_network mode:
|
||||
- IPv4 link-local (169.254.0.0/16) covers AWS/GCP/Azure IMDS 169.254.169.254.
|
||||
- IPv6 link-local (fe80::/10).
|
||||
- Multicast and unspecified addresses.
|
||||
Without this check, a self-hosted HA running on a cloud VM could be
|
||||
tricked into exfiltrating cloud credentials via IMDS.
|
||||
"""
|
||||
return addr.is_multicast or addr.is_unspecified or addr.is_link_local
|
||||
|
||||
class _PinnedResolver(AbstractResolver):
|
||||
"""aiohttp resolver that returns pre-validated IPs for a single hostname.
|
||||
|
||||
Why: prevents DNS-rebinding attacks. After validate_endpoint has
|
||||
confirmed the hostname resolves to a safe IP, we pin that IP in the
|
||||
resolver used by the aiohttp session. aiohttp then skips its own
|
||||
DNS lookup on each request and uses the pinned IP, closing the
|
||||
TOCTOU gap between validation and actual HTTP call.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
pinned: dict[str, list[tuple[str, int]]],
|
||||
) -> None:
|
||||
self._pinned = pinned
|
||||
|
||||
async def resolve(
|
||||
self,
|
||||
host: str,
|
||||
port: int = 0,
|
||||
family: int = socket.AF_INET,
|
||||
) -> list[dict[str, Any]]:
|
||||
entries = self._pinned.get(host.lower())
|
||||
if entries is None:
|
||||
# Every request on a pinned session must target the validated
|
||||
# host. Resolving anything else means a request escaped the pin
|
||||
# (a new call site or a config bug) — fail closed rather than
|
||||
# fall back to live, unvalidated DNS.
|
||||
raise OSError(f"Refusing to resolve unpinned host: {host}")
|
||||
return [
|
||||
{
|
||||
"hostname": host,
|
||||
"host": ip,
|
||||
"port": port or default_port,
|
||||
"family": _family_for(ip),
|
||||
"proto": 0,
|
||||
"flags": 0,
|
||||
}
|
||||
for ip, default_port in entries
|
||||
]
|
||||
|
||||
async def close(self) -> None:
|
||||
"""Nothing to close; the resolver holds only the pinned map."""
|
||||
|
||||
def _family_for(ip: str) -> int:
|
||||
"""Return AF_INET or AF_INET6 based on the IP literal."""
|
||||
try:
|
||||
return socket.AF_INET6 if ":" in ip else socket.AF_INET
|
||||
except Exception:
|
||||
return socket.AF_INET
|
||||
|
||||
async def resolve_hostname_ips(
|
||||
hass: HomeAssistant,
|
||||
hostname: str,
|
||||
) -> list[str]:
|
||||
"""Resolve hostname to all its IPs via the event-loop-safe executor.
|
||||
|
||||
Returns a list of IP strings (may contain both IPv4 and IPv6).
|
||||
Raises ValueError on resolution failure.
|
||||
"""
|
||||
try:
|
||||
addrinfos = await hass.async_add_executor_job(
|
||||
socket.getaddrinfo, hostname, None
|
||||
)
|
||||
except socket.gaierror as err:
|
||||
raise ValueError(f"Cannot resolve hostname: {hostname}") from err
|
||||
ips = []
|
||||
seen: set[str] = set()
|
||||
for _family, _type, _proto, _canonname, sockaddr in addrinfos:
|
||||
ip = sockaddr[0]
|
||||
if ip not in seen:
|
||||
seen.add(ip)
|
||||
ips.append(ip)
|
||||
if not ips:
|
||||
raise ValueError(f"No IPs for hostname: {hostname}")
|
||||
return ips
|
||||
|
||||
def create_pinned_session(
|
||||
endpoint: str,
|
||||
resolved_ips: list[str],
|
||||
) -> aiohttp.ClientSession:
|
||||
"""Create an isolated aiohttp session with pinned DNS and no cookie jar.
|
||||
|
||||
Addresses two issues at once:
|
||||
- DNS rebinding: aiohttp will reuse the pinned IPs from validate_endpoint
|
||||
rather than re-resolving the hostname on each request.
|
||||
- Cookie pollution: DummyCookieJar prevents cookies from leaking between
|
||||
this integration and other HA components sharing the same domain.
|
||||
|
||||
Built directly on aiohttp: HA's async_create_clientsession always
|
||||
injects its own pooled connector and rejects a caller-supplied one,
|
||||
so a custom resolver cannot go through the helper. The caller owns
|
||||
the session and must close it. Requests must pass
|
||||
allow_redirects=False so a 3xx response cannot route past the pinned
|
||||
resolver to an unvalidated host.
|
||||
"""
|
||||
parsed = urlparse(endpoint)
|
||||
hostname = (parsed.hostname or "").lower()
|
||||
port = parsed.port or (443 if parsed.scheme == "https" else 80)
|
||||
pinned: dict[str, list[tuple[str, int]]] = {
|
||||
hostname: [(ip, port) for ip in resolved_ips]
|
||||
}
|
||||
connector = aiohttp.TCPConnector(resolver=_PinnedResolver(pinned))
|
||||
return aiohttp.ClientSession(
|
||||
connector=connector,
|
||||
cookie_jar=aiohttp.DummyCookieJar(),
|
||||
)
|
||||
|
||||
async def validate_endpoint(
|
||||
hass: HomeAssistant,
|
||||
endpoint: str,
|
||||
*,
|
||||
allow_local: bool = False,
|
||||
) -> tuple[str, list[str]]:
|
||||
"""Validate API endpoint URL for security and pin resolved IPs.
|
||||
|
||||
Ensures HTTPS-only and blocks private/reserved IP ranges (SSRF protection).
|
||||
When allow_local is True, permits private IPs and HTTP scheme for self-hosted proxies.
|
||||
Uses async DNS resolution to avoid blocking the event loop.
|
||||
|
||||
Returns: (validated_endpoint_without_trailing_slash, resolved_ips).
|
||||
The resolved IPs are intended for pinning in aiohttp resolver via
|
||||
create_pinned_session(), closing the DNS-rebinding TOCTOU gap.
|
||||
|
||||
Raises:
|
||||
ValueError: If the endpoint fails validation.
|
||||
"""
|
||||
parsed = urlparse(endpoint)
|
||||
|
||||
if allow_local:
|
||||
if parsed.scheme not in ("https", "http"):
|
||||
raise ValueError("Only HTTPS and HTTP endpoints are allowed")
|
||||
else:
|
||||
if parsed.scheme not in ("https",):
|
||||
raise ValueError("Only HTTPS endpoints are allowed")
|
||||
|
||||
hostname = parsed.hostname
|
||||
if not hostname:
|
||||
raise ValueError("Invalid endpoint URL: no hostname")
|
||||
|
||||
resolved_ips: list[str] = []
|
||||
|
||||
# Collect and check all resolved IPs (or IP literal directly).
|
||||
def _collect(ips: list[str]) -> None:
|
||||
for ip in ips:
|
||||
if ip not in resolved_ips:
|
||||
resolved_ips.append(ip)
|
||||
|
||||
try:
|
||||
addr = ipaddress.ip_address(hostname)
|
||||
_is_ip_literal = True
|
||||
except ValueError:
|
||||
addr = None
|
||||
_is_ip_literal = False
|
||||
|
||||
if _is_ip_literal:
|
||||
_collect([hostname])
|
||||
else:
|
||||
try:
|
||||
addrinfos = await hass.async_add_executor_job(
|
||||
socket.getaddrinfo, hostname, None
|
||||
)
|
||||
except socket.gaierror as err:
|
||||
raise ValueError(f"Cannot resolve hostname: {hostname}") from err
|
||||
_collect([sockaddr[0] for (*_, sockaddr) in addrinfos])
|
||||
|
||||
if not resolved_ips:
|
||||
raise ValueError(f"No IPs resolved for hostname: {hostname}")
|
||||
|
||||
# Validate each resolved IP against the selected policy.
|
||||
for ip_str in resolved_ips:
|
||||
ip_obj = ipaddress.ip_address(ip_str)
|
||||
if allow_local:
|
||||
if _is_cloud_metadata_or_unsafe(ip_obj):
|
||||
raise ValueError(
|
||||
"Link-local/metadata/multicast addresses are not allowed"
|
||||
)
|
||||
else:
|
||||
if _check_ip_restricted(ip_obj):
|
||||
raise _RestrictedIPError(
|
||||
"Private/reserved IP addresses are not allowed"
|
||||
)
|
||||
|
||||
return endpoint.rstrip("/"), resolved_ips
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "HA text AI",
|
||||
"name": "HA Text AI",
|
||||
"render_readme": true,
|
||||
"homeassistant": "2024.11.0"
|
||||
"homeassistant": "2024.12.0"
|
||||
}
|
||||
|
||||
@@ -1,25 +1,35 @@
|
||||
```
|
||||
ha-text-ai/
|
||||
│
|
||||
├── custom_components/
|
||||
├── ha_text_ai/
|
||||
│ ├── __init__.py
|
||||
│ ├── config_flow.py
|
||||
│ ├── coordinator.py
|
||||
│ ├── manifest.json
|
||||
│ ├── sensor.py
|
||||
│ ├── services.yaml
|
||||
│ ├── const.py
|
||||
│ └── api_client.py
|
||||
│
|
||||
├── translations/
|
||||
│ ├── en.json
|
||||
│ ├── de.json
|
||||
│ └── ru.json
|
||||
│
|
||||
└── icons/
|
||||
├── icon.png
|
||||
├── icon@2x.png
|
||||
├── logo.png
|
||||
└── logo@2x.png
|
||||
custom_components/ha_text_ai/
|
||||
├── __init__.py
|
||||
├── api_client.py
|
||||
├── config_flow.py
|
||||
├── const.py
|
||||
├── coordinator.py
|
||||
├── history.py
|
||||
├── metrics.py
|
||||
├── providers.py
|
||||
├── sensor.py
|
||||
├── services.yaml
|
||||
├── strings.json
|
||||
├── utils.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
|
||||
└── translations
|
||||
├── de.json
|
||||
├── en.json
|
||||
├── es.json
|
||||
├── hi.json
|
||||
├── it.json
|
||||
├── ru.json
|
||||
├── sr.json
|
||||
└── zh.json
|
||||
|
||||
```
|
||||
|
||||