mirror of
https://github.com/smkrv/ha-text-ai.git
synced 2026-07-22 23:24:03 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
@@ -1,5 +1,6 @@
|
|||||||
name: Validate with hassfest
|
name: Validate with hassfest
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
name: Release
|
||||||
|
|
||||||
|
on:
|
||||||
|
release:
|
||||||
|
types: [created]
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
name: Build and upload release asset
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out code
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
with:
|
||||||
|
ref: ${{ github.event.release.tag_name }}
|
||||||
|
|
||||||
|
- name: Create zip archive
|
||||||
|
run: |
|
||||||
|
cd custom_components
|
||||||
|
zip -r ../ha_text_ai.zip ha_text_ai \
|
||||||
|
-x "ha_text_ai/__pycache__/*" \
|
||||||
|
-x "*.pyc" \
|
||||||
|
-x "*.pyo" \
|
||||||
|
-x "*/__pycache__/*" \
|
||||||
|
-x "*.DS_Store"
|
||||||
|
|
||||||
|
- name: Upload release asset
|
||||||
|
uses: softprops/action-gh-release@v2
|
||||||
|
with:
|
||||||
|
tag_name: ${{ github.event.release.tag_name }}
|
||||||
|
files: ha_text_ai.zip
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
@@ -1,4 +1,6 @@
|
|||||||
name: Validate
|
name: Validate
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
|
|||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*.egg-info/
|
||||||
|
dist/
|
||||||
|
build/
|
||||||
|
*.egg
|
||||||
|
|
||||||
|
# Virtual environments
|
||||||
|
.venv/
|
||||||
|
venv/
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
|
*.swp
|
||||||
|
*.swo
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
|
||||||
|
# Archives
|
||||||
|
*.zip
|
||||||
|
|
||||||
|
# Home Assistant
|
||||||
|
.storage/
|
||||||
|
|
||||||
|
# Claude Code working files
|
||||||
|
CLAUDE.md
|
||||||
|
docs/specs/
|
||||||
|
docs/superpowers/
|
||||||
@@ -1,437 +1,131 @@
|
|||||||
Attribution-NonCommercial-ShareAlike 4.0 International
|
# PolyForm Noncommercial License 1.0.0
|
||||||
|
|
||||||
=======================================================================
|
|
||||||
|
|
||||||
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
|
<https://polyformproject.org/licenses/noncommercial/1.0.0>
|
||||||
Adapted Material You produce, the following conditions also apply.
|
|
||||||
|
|
||||||
1. The Adapter's License You apply must be a Creative Commons
|
## Acceptance
|
||||||
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
|
In order to get any license under these terms, you must agree
|
||||||
Adapter's License You apply. You may satisfy this condition
|
to them as both strict obligations and conditions to all
|
||||||
in any reasonable manner based on the medium, means, and
|
your licenses.
|
||||||
context in which You Share Adapted Material.
|
|
||||||
|
|
||||||
3. You may not offer or impose any additional or different terms
|
## Copyright License
|
||||||
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.
|
|
||||||
|
|
||||||
|
The licensor grants you a copyright license for the
|
||||||
|
software to do everything you might do with the software
|
||||||
|
that would otherwise infringe the licensor's copyright
|
||||||
|
in it for any permitted purpose. However, you may
|
||||||
|
only distribute the software according to [Distribution
|
||||||
|
License](#distribution-license) and make changes or new works
|
||||||
|
based on the software according to [Changes and New Works
|
||||||
|
License](#changes-and-new-works-license).
|
||||||
|
|
||||||
Section 4 -- Sui Generis Database Rights.
|
## Distribution License
|
||||||
|
|
||||||
Where the Licensed Rights include Sui Generis Database Rights that
|
The licensor grants you an additional copyright license
|
||||||
apply to Your use of the Licensed Material:
|
to distribute copies of the software. Your license
|
||||||
|
to distribute covers distributing the software with
|
||||||
|
changes and new works permitted by [Changes and New Works
|
||||||
|
License](#changes-and-new-works-license).
|
||||||
|
|
||||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
## Notices
|
||||||
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
|
You must ensure that anyone who gets a copy of any part of
|
||||||
contents in a database in which You have Sui Generis Database
|
the software from you also gets a copy of these terms or the
|
||||||
Rights, then the database in which You have Sui Generis Database
|
URL for them above, as well as copies of any plain-text lines
|
||||||
Rights (but not its individual contents) is Adapted Material,
|
beginning with `Required Notice:` that the licensor provided
|
||||||
including for purposes of Section 3(b); and
|
with the software. For example:
|
||||||
|
|
||||||
c. You must comply with the conditions in Section 3(a) if You Share
|
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
|
||||||
all or a substantial portion of the contents of the database.
|
|
||||||
|
|
||||||
For the avoidance of doubt, this Section 4 supplements and does not
|
## Changes and New Works License
|
||||||
replace Your obligations under this Public License where the Licensed
|
|
||||||
Rights include other Copyright and Similar Rights.
|
|
||||||
|
|
||||||
|
The licensor grants you an additional copyright license to
|
||||||
|
make changes and new works based on the software for any
|
||||||
|
permitted purpose.
|
||||||
|
|
||||||
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
## Patent License
|
||||||
|
|
||||||
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
The licensor grants you a patent license for the software that
|
||||||
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
covers patent claims the licensor can license, or becomes able
|
||||||
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
to license, that you would infringe by using the software.
|
||||||
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
|
## Noncommercial Purposes
|
||||||
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
|
Any noncommercial purpose is a permitted purpose.
|
||||||
above shall be interpreted in a manner that, to the extent
|
|
||||||
possible, most closely approximates an absolute disclaimer and
|
|
||||||
waiver of all liability.
|
|
||||||
|
|
||||||
|
## Personal Uses
|
||||||
|
|
||||||
Section 6 -- Term and Termination.
|
Personal use for research, experiment, and testing for
|
||||||
|
the benefit of public knowledge, personal study, private
|
||||||
|
entertainment, hobby projects, amateur pursuits, or religious
|
||||||
|
observance, without any anticipated commercial application,
|
||||||
|
is use for a permitted purpose.
|
||||||
|
|
||||||
a. This Public License applies for the term of the Copyright and
|
## Noncommercial Organizations
|
||||||
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
|
Use by any charitable organization, educational institution,
|
||||||
License.
|
public research organization, public safety or health
|
||||||
|
organization, environmental protection organization,
|
||||||
|
or government institution is use for a permitted purpose
|
||||||
|
regardless of the source of funding or obligations resulting
|
||||||
|
from the funding.
|
||||||
|
|
||||||
|
## Fair Use
|
||||||
|
|
||||||
Section 7 -- Other Terms and Conditions.
|
You may have "fair use" rights for the software under the
|
||||||
|
law. These terms do not limit them.
|
||||||
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
|
## No Other Rights
|
||||||
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
|
These terms do not allow you to sublicense or transfer any of
|
||||||
deemed unenforceable, it shall be automatically reformed to the
|
your licenses to anyone else, or prevent the licensor from
|
||||||
minimum extent necessary to make it enforceable. If the provision
|
granting licenses to anyone else. These terms do not imply
|
||||||
cannot be reformed, it shall be severed from this Public License
|
any other licenses.
|
||||||
without affecting the enforceability of the remaining terms and
|
|
||||||
conditions.
|
## Patent Defense
|
||||||
|
|
||||||
c. No term or condition of this Public License will be waived and no
|
If you make any written claim that the software infringes or
|
||||||
failure to comply consented to unless expressly agreed to by the
|
contributes to infringement of any patent, your patent license
|
||||||
Licensor.
|
for the software granted under these terms ends immediately. If
|
||||||
|
your company makes such a claim, your patent license ends
|
||||||
d. Nothing in this Public License constitutes or may be interpreted
|
immediately for work on behalf of your company.
|
||||||
as a limitation upon, or waiver of, any privileges and immunities
|
|
||||||
that apply to the Licensor or You, including from the legal
|
## Violations
|
||||||
processes of any jurisdiction or authority.
|
|
||||||
|
The first time you are notified in writing that you have
|
||||||
=======================================================================
|
violated any of these terms, or done anything with the software
|
||||||
|
not covered by your licenses, your licenses can nonetheless
|
||||||
Creative Commons is not a party to its public
|
continue if you come into full compliance with these terms,
|
||||||
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
and take practical steps to correct past violations, within
|
||||||
its public licenses to material it publishes and in those instances
|
32 days of receiving notice. Otherwise, all your licenses
|
||||||
will be considered the “Licensor.” The text of the Creative Commons
|
end immediately.
|
||||||
public licenses is dedicated to the public domain under the CC0 Public
|
|
||||||
Domain Dedication. Except for the limited purpose of indicating that
|
## No Liability
|
||||||
material is shared under a Creative Commons public license or as
|
|
||||||
otherwise permitted by the Creative Commons policies published at
|
***As far as the law allows, the software comes as is, without
|
||||||
creativecommons.org/policies, Creative Commons does not authorize the
|
any warranty or condition, and the licensor will not be liable
|
||||||
use of the trademark "Creative Commons" or any other trademark or logo
|
to you for any damages arising out of these terms or the use
|
||||||
of Creative Commons without its prior written consent including,
|
or nature of the software, under any kind of legal claim.***
|
||||||
without limitation, in connection with any unauthorized modifications
|
|
||||||
to any of its public licenses or any other arrangements,
|
## Definitions
|
||||||
understandings, or agreements concerning use of licensed material. For
|
|
||||||
the avoidance of doubt, this paragraph does not form part of the
|
The **licensor** is the individual or entity offering these
|
||||||
public licenses.
|
terms, and the **software** is the software the licensor makes
|
||||||
|
available under these terms.
|
||||||
Creative Commons may be contacted at creativecommons.org.
|
|
||||||
|
**You** refers to the individual or entity agreeing to these
|
||||||
|
terms.
|
||||||
|
|
||||||
|
**Your company** is any legal entity, sole proprietorship,
|
||||||
|
or other kind of organization that you work for, plus all
|
||||||
|
organizations that have control over, are under the control of,
|
||||||
|
or are under common control with that organization. **Control**
|
||||||
|
means ownership of substantially all the assets of an entity,
|
||||||
|
or the power to direct its management and policies by vote,
|
||||||
|
contract, or otherwise. Control can be direct or indirect.
|
||||||
|
|
||||||
|
**Your licenses** are all the licenses granted to you for the
|
||||||
|
software under these terms.
|
||||||
|
|
||||||
|
**Use** means anything you do with the software requiring one
|
||||||
|
of your licenses.
|
||||||
|
|||||||
@@ -2,17 +2,17 @@
|
|||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
  [](https://creativecommons.org/licenses/by-nc-sa/4.0/) [](https://github.com/hacs/integration)
|
  [](https://polyformproject.org/licenses/noncommercial/1.0.0) [](https://github.com/hacs/integration)
|
||||||
       
|
       
|
||||||
|
|
||||||
|
|
||||||
<img src="https://github.com/smkrv/ha-text-ai/blob/15c717fcb0204bf4a0d4b4b4c6f0bb93e9f6c9a9/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;"/>
|
<img src="https://github.com/smkrv/ha-text-ai/blob/main/custom_components/ha_text_ai/icons/logo%402x.png" alt="HA Text AI" style="width: 50%; max-width: 256px; max-height: 128px; aspect-ratio: 2/1; object-fit: contain;"/>
|
||||||
|
|
||||||
### Advanced AI Integration for [Home Assistant](https://www.home-assistant.io/) with LLM multi-provider support
|
### Advanced AI Integration for [Home Assistant](https://www.home-assistant.io/) with LLM multi-provider support
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<p align="center">
|
<p align="center">
|
||||||
Transform your smart home experience with powerful AI assistance powered by multiple AI providers including OpenAI GPT, DeepSeek and Anthropic Claude models. Get intelligent responses, automate complex scenarios, and enhance your home automation with advanced natural language processing.
|
Transform your smart home experience with powerful AI assistance powered by multiple AI providers including OpenAI GPT, Anthropic Claude, DeepSeek and Google Gemini models. Get intelligent responses, automate complex scenarios, and enhance your home automation with advanced natural language processing.
|
||||||
|
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
|||||||
|
|
||||||
## 🌟 Features
|
## 🌟 Features
|
||||||
|
|
||||||
- 🧠 **Multi-Provider AI Integration**: Support for OpenAI GPT, DeepSeek and Anthropic Claude models
|
- 🧠 **Multi-Provider AI Integration**: Support for OpenAI GPT, Anthropic Claude, DeepSeek and Google Gemini models
|
||||||
- 💬 **Advanced Language Processing**: Context-aware, multi-turn conversations
|
- 💬 **Advanced Language Processing**: Context-aware, multi-turn conversations
|
||||||
- 📝 **Enhanced Memory Management**: Secure file-based history storage
|
- 📝 **Enhanced Memory Management**: Secure file-based history storage
|
||||||
- ⚡ **Performance Optimization**: Efficient token usage and smart rate limiting
|
- ⚡ **Performance Optimization**: Efficient token usage and smart rate limiting
|
||||||
@@ -44,6 +44,7 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
|||||||
- Support for OpenAI GPT models
|
- Support for OpenAI GPT models
|
||||||
- Anthropic Claude integration
|
- Anthropic Claude integration
|
||||||
- DeepSeek integration
|
- DeepSeek integration
|
||||||
|
- Google Gemini integration
|
||||||
- Custom API endpoints
|
- Custom API endpoints
|
||||||
- Flexible model selection
|
- Flexible model selection
|
||||||
|
|
||||||
@@ -106,7 +107,7 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
|||||||
|
|
||||||
## 📋 Prerequisites
|
## 📋 Prerequisites
|
||||||
|
|
||||||
- Home Assistant 2024.2.2 or later
|
- Home Assistant 2024.12.0 or later (recommended for best compatibility)
|
||||||
- Active API key from:
|
- Active API key from:
|
||||||
- OpenAI ([Get key](https://platform.openai.com/account/api-keys))
|
- OpenAI ([Get key](https://platform.openai.com/account/api-keys))
|
||||||
- Anthropic ([Get key](https://console.anthropic.com/))
|
- Anthropic ([Get key](https://console.anthropic.com/))
|
||||||
@@ -120,7 +121,7 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
|||||||
## Configuration Options
|
## Configuration Options
|
||||||
|
|
||||||
### 🔧 **Core Configuration Settings**
|
### 🔧 **Core Configuration Settings**
|
||||||
- 🌐 **API Provider**: OpenAI/Anthropic/DeepSeek
|
- 🌐 **API Provider**: OpenAI/Anthropic/DeepSeek/Gemini
|
||||||
- 🔑 **API Key**: Provider-specific authentication
|
- 🔑 **API Key**: Provider-specific authentication
|
||||||
- 🤖 **Model Selection**: Flexible, provider-specific models
|
- 🤖 **Model Selection**: Flexible, provider-specific models
|
||||||
- 🌡️ **Temperature**: Creativity control (0.0-2.0)
|
- 🌡️ **Temperature**: Creativity control (0.0-2.0)
|
||||||
@@ -129,6 +130,25 @@ Transform your smart home experience with powerful AI assistance powered by mult
|
|||||||
- 💾 **History Size**: Number of messages to retain
|
- 💾 **History Size**: Number of messages to retain
|
||||||
- 🌍 **Custom API Endpoint**: Optional advanced configuration
|
- 🌍 **Custom API Endpoint**: Optional advanced configuration
|
||||||
|
|
||||||
|
### 🤖 **Recommended Models**
|
||||||
|
|
||||||
|
#### OpenAI Models
|
||||||
|
- **GPT-5** - The latest flagship model, best for complex reasoning
|
||||||
|
- **GPT-5 mini** - A cost-effective and fast model, suitable for most tasks
|
||||||
|
|
||||||
|
#### Anthropic Claude Models
|
||||||
|
- **Claude Opus 4.6** - The most capable model for handling complex tasks
|
||||||
|
- **Claude Sonnet 4.6** - Offers a balance between performance and cost
|
||||||
|
- **Claude Haiku 4.5** - The fastest and most economical option in the series
|
||||||
|
|
||||||
|
#### DeepSeek Models
|
||||||
|
- **DeepSeek-V3** - A general-purpose model for a wide range of tasks
|
||||||
|
- **DeepSeek-R1** - A specialized model focused on reasoning and coding
|
||||||
|
|
||||||
|
#### Google Gemini Models
|
||||||
|
- **Gemini 3.1 Pro** - The newest and most advanced model available
|
||||||
|
- **Gemini 3.1 Flash Lite** - Fastest and most cost-efficient model for high-volume workloads
|
||||||
|
|
||||||
<details>
|
<details>
|
||||||
<summary>🌐 Potentially Compatible Providers</summary>
|
<summary>🌐 Potentially Compatible Providers</summary>
|
||||||
|
|
||||||
@@ -166,18 +186,23 @@ To be compatible, a provider should support:
|
|||||||
<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>
|
<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
|
1. Open HACS in Home Assistant
|
||||||
2. Click on "Integrations"
|
2. Click on "Integrations"
|
||||||
3. Click "..." in top right corner
|
3. Search for "HA Text AI"
|
||||||
4. Select "Custom repositories"
|
4. Click "Download"
|
||||||
5. Add repository URL: `https://github.com/smkrv/ha-text-ai`
|
5. Restart Home Assistant
|
||||||
6. Choose "Integration" as category
|
|
||||||
7. Click "Download"
|
**Alternative Method (Custom Repository):**
|
||||||
8. Restart Home Assistant
|
If the integration is not found in the default repository:
|
||||||
|
1. Click "..." in top right corner of HACS
|
||||||
|
2. Select "Custom repositories"
|
||||||
|
3. Add repository URL: `https://github.com/smkrv/ha-text-ai`
|
||||||
|
4. Choose "Integration" as category
|
||||||
|
5. Click "Download"
|
||||||
|
|
||||||
### Manual Installation
|
### Manual Installation
|
||||||
1. Download the latest release
|
1. Download the latest release
|
||||||
2. Extract and copy `custom_components/ha_text_ai` to your `custom_components` directory
|
2. Extract and copy `custom_components/ha_text_ai` to your `custom_components` directory
|
||||||
3. Restart Home Assistant
|
3. Restart Home Assistant
|
||||||
4. Add configuration via UI or YAML
|
4. Add configuration via UI (Settings → Devices & Services → Add Integration)
|
||||||
|
|
||||||
## ⚙️ Configuration
|
## ⚙️ Configuration
|
||||||
|
|
||||||
@@ -187,80 +212,47 @@ To be compatible, a provider should support:
|
|||||||
3. Search for "HA Text AI"
|
3. Search for "HA Text AI"
|
||||||
4. Follow the configuration steps
|
4. Follow the configuration steps
|
||||||
|
|
||||||
<details>
|
> **Note:** This integration is configured exclusively through the UI (config entries). YAML configuration is not supported.
|
||||||
<summary>📦 Via YAML (Advanced)</summary>
|
|
||||||
|
|
||||||
### Platform Configuration (Global Settings)
|
|
||||||
|
|
||||||
```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.
|
|
||||||
```
|
|
||||||
|
|
||||||
### Sensor Configuration
|
|
||||||
|
|
||||||
```yaml
|
|
||||||
sensor:
|
|
||||||
- platform: ha_text_ai
|
|
||||||
name: "My AI Assistant" # Required, unique identifier
|
|
||||||
api_provider: openai # Optional (inherits from platform)
|
|
||||||
model: "gpt-4o-mini" # Optional
|
|
||||||
temperature: 0.7 # Optional
|
|
||||||
max_tokens: 1000 # Optional
|
|
||||||
```
|
|
||||||
|
|
||||||
### 📋 Configuration Parameters
|
|
||||||
|
|
||||||
#### Platform Configuration
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Default | Description |
|
|
||||||
|-----------|------|----------|---------|-------------|
|
|
||||||
| `api_provider` | String | ✅ | - | AI service provider (openai, anthropic) |
|
|
||||||
| `api_key` | String | ✅ | - | Authentication key for AI service |
|
|
||||||
| `model` | String | ⚠️ | Provider default | Strongly recommended: Specific AI model to use. If not specified, the provider's default model will be used |
|
|
||||||
| `temperature` | Float | ❌ | 0.7 | Response creativity level (0.0-2.0) |
|
|
||||||
| `max_tokens` | Integer | ❌ | 1000 | Maximum response length |
|
|
||||||
| `request_interval` | Float | ❌ | 1.0 | Delay between API requests |
|
|
||||||
| `api_endpoint` | URL | ⚠️ | Provider default | Custom API endpoint |
|
|
||||||
| `system_prompt` | String | ❌ | - | Default context for AI interactions |
|
|
||||||
| `max_history_size` | Integer | ❌ | 100 | Maximum number of conversation entries to store |
|
|
||||||
| `history_file_size` | Integer | ⚠️ | 1 | Maximum history file size in MB |
|
|
||||||
|
|
||||||
#### Sensor Configuration
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Default | Description |
|
|
||||||
|-----------|------|----------|---------|-------------|
|
|
||||||
| `platform` | String | ✅ | - | Must be `ha_text_ai` |
|
|
||||||
| `name` | String | ✅ | - | Unique sensor identifier |
|
|
||||||
| `api_provider` | String | ❌ | Platform setting | Override global provider |
|
|
||||||
| `model` | String | ⚠️ | Platform setting | Recommended: Override global model. If not specified, uses platform or provider default |
|
|
||||||
| `temperature` | Float | ❌ | Platform setting | Override global temperature |
|
|
||||||
| `max_tokens` | Integer | ❌ | Platform setting | Override global max tokens |
|
|
||||||
|
|
||||||
</details>
|
|
||||||
|
|
||||||
## 🛠️ Available Services
|
## 🛠️ Available Services
|
||||||
|
|
||||||
|
### 🔄 Response Variables (New!)
|
||||||
|
|
||||||
|
**HA Text AI now supports response variables** - a powerful feature that returns AI responses directly from service calls, eliminating the need for separate text sensors and the 255-character limitation!
|
||||||
|
|
||||||
|
#### ✨ Key Benefits:
|
||||||
|
- **Unlimited response length** - No more 255-character truncation
|
||||||
|
- **Direct data access** - Get responses immediately in automations
|
||||||
|
- **Race condition prevention** - Eliminates conflicts in parallel automations
|
||||||
|
- **Simplified workflows** - No need to read from sensors
|
||||||
|
|
||||||
### ask_question
|
### ask_question
|
||||||
```yaml
|
```yaml
|
||||||
service: ha_text_ai.ask_question
|
service: ha_text_ai.ask_question
|
||||||
data:
|
data:
|
||||||
question: "What's the optimal temperature for sleeping?"
|
question: "What's the optimal temperature for sleeping?"
|
||||||
model: "claude-3-sonnet" # optional
|
model: "claude-sonnet-4-6-20260217" # optional
|
||||||
temperature: 0.5 # optional
|
temperature: 0.5 # optional
|
||||||
max_tokens: 500 # optional
|
max_tokens: 500 # optional
|
||||||
context_messages: 10 #optional, number of previous messages to include in context, default: 5
|
context_messages: 10 #optional, number of previous messages to include in context, default: 5
|
||||||
system_prompt: "You are a sleep optimization expert" # optional
|
system_prompt: "You are a sleep optimization expert" # optional
|
||||||
instance: sensor.ha_text_ai_gpt
|
instance: sensor.ha_text_ai_gpt
|
||||||
|
response_variable: ai_response # NEW! Store response data directly
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 📊 Response Data Structure:
|
||||||
|
```yaml
|
||||||
|
# The service returns structured data:
|
||||||
|
response_text: "The optimal sleeping temperature is 65-68°F (18-20°C)..."
|
||||||
|
tokens_used: 150
|
||||||
|
prompt_tokens: 50
|
||||||
|
completion_tokens: 100
|
||||||
|
model_used: "claude-sonnet-4-6-20260217"
|
||||||
|
instance: "sensor.ha_text_ai_gpt"
|
||||||
|
question: "What's the optimal temperature for sleeping?"
|
||||||
|
timestamp: "2025-02-09T16:57:00.000Z"
|
||||||
|
success: true
|
||||||
|
# error: "Error message" (only present if success: false)
|
||||||
```
|
```
|
||||||
|
|
||||||
### set_system_prompt
|
### set_system_prompt
|
||||||
@@ -287,11 +279,157 @@ data:
|
|||||||
```yaml
|
```yaml
|
||||||
service: ha_text_ai.get_history
|
service: ha_text_ai.get_history
|
||||||
data:
|
data:
|
||||||
limit: 5 # optional
|
limit: 5 # optional, number of conversations to return (1-100)
|
||||||
filter_model: "gpt-4o" # optional
|
filter_model: "gpt-4o" # optional, filter by specific AI model
|
||||||
|
start_date: "2025-02-01" # optional, filter conversations from this date
|
||||||
|
include_metadata: false # optional, include tokens, response time, etc.
|
||||||
|
sort_order: "newest" # optional, sort order: "newest" or "oldest"
|
||||||
instance: sensor.ha_text_ai_gpt
|
instance: sensor.ha_text_ai_gpt
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## 🚀 Advanced Automation Examples with Response Variables
|
||||||
|
|
||||||
|
### 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 comprehensive report
|
||||||
|
- service: notify.telegram
|
||||||
|
data:
|
||||||
|
title: "🏠 Home Analysis Report"
|
||||||
|
message: |
|
||||||
|
**Analysis:**
|
||||||
|
{{ status_analysis.response_text }}
|
||||||
|
|
||||||
|
**Recommendations:**
|
||||||
|
{{ recommendations.response_text }}
|
||||||
|
|
||||||
|
**Report Details:**
|
||||||
|
- Total tokens used: {{ status_analysis.tokens_used + recommendations.tokens_used }}
|
||||||
|
- Analysis model: {{ status_analysis.model_used }}
|
||||||
|
- Generated: {{ recommendations.timestamp }}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 💡 Migration from Sensors to Response Variables
|
||||||
|
|
||||||
|
#### Old Method (Limited):
|
||||||
|
```yaml
|
||||||
|
# ❌ Old way - limited to 255 characters, race conditions
|
||||||
|
automation:
|
||||||
|
- alias: "Old AI Response Method"
|
||||||
|
action:
|
||||||
|
- service: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
question: "Long question here..."
|
||||||
|
instance: sensor.ha_text_ai_gpt
|
||||||
|
- delay: "00:00:05" # Wait for sensor update
|
||||||
|
- service: notify.mobile
|
||||||
|
data:
|
||||||
|
message: "{{ state_attr('sensor.ha_text_ai_gpt', 'response')[:255] }}..." # Truncated!
|
||||||
|
```
|
||||||
|
|
||||||
|
#### New Method (Unlimited):
|
||||||
|
```yaml
|
||||||
|
# ✅ New way - unlimited length, immediate access, no race conditions
|
||||||
|
automation:
|
||||||
|
- alias: "New AI Response Method"
|
||||||
|
action:
|
||||||
|
- service: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
question: "Long question here..."
|
||||||
|
instance: sensor.ha_text_ai_gpt
|
||||||
|
response_variable: ai_response # Direct access!
|
||||||
|
- service: notify.mobile
|
||||||
|
data:
|
||||||
|
message: "{{ ai_response.response_text }}" # Full response, no truncation!
|
||||||
|
```
|
||||||
|
|
||||||
### 🏷️ HA Text AI Sensor Naming Convention
|
### 🏷️ HA Text AI Sensor Naming Convention
|
||||||
|
|
||||||
#### Character Restrictions
|
#### Character Restrictions
|
||||||
@@ -367,10 +505,7 @@ automation:
|
|||||||
|
|
||||||
#### System Status
|
#### System Status
|
||||||
```yaml
|
```yaml
|
||||||
# Current operational readiness of the AI service API
|
# Indicates if a request is currently being processed
|
||||||
{{ 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
|
{{ state_attr('sensor.ha_text_ai_gpt', 'Is processing') }} # false
|
||||||
|
|
||||||
# Shows if the API has hit its request rate limit
|
# Shows if the API has hit its request rate limit
|
||||||
@@ -412,7 +547,7 @@ automation:
|
|||||||
# Number of entries in current history file
|
# Number of entries in current history file
|
||||||
{{ state_attr('sensor.ha_text_ai_gpt', 'History size') }} # 0
|
{{ state_attr('sensor.ha_text_ai_gpt', 'History size') }} # 0
|
||||||
|
|
||||||
# Last few conversation entries (limited to 1 for performance)
|
# Last few conversation entries (last 5 for performance)
|
||||||
{{ state_attr('sensor.ha_text_ai_gpt', 'conversation_history') }} # [...]
|
{{ state_attr('sensor.ha_text_ai_gpt', 'conversation_history') }} # [...]
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -457,10 +592,10 @@ Conversation history stored in `.storage/ha_text_ai_history/` directory:
|
|||||||
## 📘 FAQ
|
## 📘 FAQ
|
||||||
|
|
||||||
**Q: Which AI providers are supported?**
|
**Q: Which AI providers are supported?**
|
||||||
A: Currently OpenAI (GPT models) and Anthropic (Claude models) are supported, with more providers planned.
|
A: OpenAI (GPT models), Anthropic (Claude models), DeepSeek, Google Gemini, and OpenRouter are officially supported, with many other OpenAI-compatible providers working as well.
|
||||||
|
|
||||||
**Q: How can I reduce API costs?**
|
**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 gpt-5-mini or claude-haiku-4-5 for most queries, implement caching, and optimize token usage.
|
||||||
|
|
||||||
**Q: Are there limitations on the number of requests?**
|
**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. We recommend monitoring usage and implementing request throttling via `request_interval` configuration.
|
||||||
@@ -471,8 +606,11 @@ A: Yes, you can configure custom endpoints and use any compatible model by speci
|
|||||||
**Q: How do I switch between different AI providers?**
|
**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: Simply change the model parameter in your configuration or service calls to use the desired provider's model.
|
||||||
|
|
||||||
**Q: How can I reduce API costs?**
|
**Q: What are the token limits for different models?**
|
||||||
A: Use GPT-3.5-Turbo for most queries, implement caching, and optimize token usage.
|
A: Token limits vary by provider and model. OpenAI's GPT-5 supports up to 1M context tokens, Claude Opus 4.6 supports up to 1M tokens, Gemini 3.1 Pro supports up to 1M tokens, while smaller models typically have 128K-200K limits. Check your provider's documentation for specific limits.
|
||||||
|
|
||||||
|
**Q: How do I monitor token usage?**
|
||||||
|
A: Use the sensor attributes like `Total tokens`, `Prompt tokens`, and `Completion tokens` to track usage. You can also create automations to alert you when usage exceeds certain thresholds.
|
||||||
|
|
||||||
**Q: Is my data secure?**
|
**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: 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.
|
||||||
@@ -487,7 +625,7 @@ A: History is stored in files under the `.storage/ha_text_ai_history/` directory
|
|||||||
A: Yes, archived history files are stored with timestamps and can be accessed manually if needed.
|
A: Yes, archived history files are stored with timestamps and can be accessed manually if needed.
|
||||||
|
|
||||||
**Q: How much history is kept?**
|
**Q: How much history is kept?**
|
||||||
A: By default, up to 100 conversations are stored, but this can be configured. Files are automatically rotated when they reach 1MB.
|
A: By default, up to 50 conversations are stored (max 200), configurable via UI. Files are automatically rotated when they reach 1MB.
|
||||||
|
|
||||||
## 🤝 Contributing
|
## 🤝 Contributing
|
||||||
|
|
||||||
@@ -515,7 +653,7 @@ DEALINGS IN THE SOFTWARE.
|
|||||||
## 📝 License
|
## 📝 License
|
||||||
|
|
||||||
Author: SMKRV
|
Author: SMKRV
|
||||||
[CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) - see [LICENSE](LICENSE) for details.
|
[PolyForm Noncommercial 1.0.0](https://polyformproject.org/licenses/noncommercial/1.0.0) - see [LICENSE](LICENSE) for details.
|
||||||
|
|
||||||
## 💡 Support the Project
|
## 💡 Support the Project
|
||||||
|
|
||||||
@@ -538,9 +676,9 @@ If you want to say thanks financially, you can send a small token of appreciatio
|
|||||||
<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"><img src="https://github.com/smkrv/ha-text-ai/blob/2aaf3405759eb2d97624834594e24ace896131df/assets/images/icons/footer_icon.png" alt="HA Text AI" style="width: 128px; height: auto;"/></div>
|
||||||
<div align="center">
|
<div align="center">
|
||||||
|
|
||||||
Made with ❤️ for the Home Assistant Community,
|
Made with ❤️ for the Home Assistant Community
|
||||||
utilizing Claude 3.5 Sonnet, Gemini Pro 1.5, and Qwen 2.5 Coder 32B Instruct.
|
|
||||||
|
|
||||||
[Report Bug](https://github.com/smkrv/ha-text-ai/issues) · [Request Feature](https://github.com/smkrv/ha-text-ai/issues)
|
[Report Bug](https://github.com/smkrv/ha-text-ai/issues) · [Request Feature](https://github.com/smkrv/ha-text-ai/issues)
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,148 @@
|
|||||||
|
# Using response_variable with HA Text AI
|
||||||
|
|
||||||
|
After updating the HA Text AI integration, it now supports using the `response_variable` parameter in Home Assistant scripts and automations.
|
||||||
|
|
||||||
|
## What Changed
|
||||||
|
|
||||||
|
- Added response schema support in the `ha_text_ai.ask_question` service
|
||||||
|
- Service is now correctly registered with `supports_response=True` flag
|
||||||
|
- You can now use `response_variable` to capture AI response in a variable
|
||||||
|
|
||||||
|
## Example Usage in Script
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
action: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
context_messages: 0
|
||||||
|
temperature: 0.7
|
||||||
|
max_tokens: 1000
|
||||||
|
instance: sensor.ha_text_ai_gemini
|
||||||
|
question: "What time is it?"
|
||||||
|
response_variable: ai_response
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example Usage in Automation
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
alias: "Get AI Response"
|
||||||
|
trigger:
|
||||||
|
- platform: state
|
||||||
|
entity_id: input_boolean.ask_ai
|
||||||
|
to: "on"
|
||||||
|
action:
|
||||||
|
- action: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
instance: sensor.ha_text_ai_gemini
|
||||||
|
question: "What's the current weather?"
|
||||||
|
temperature: 0.7
|
||||||
|
max_tokens: 500
|
||||||
|
response_variable: weather_response
|
||||||
|
|
||||||
|
- action: notify.persistent_notification
|
||||||
|
data:
|
||||||
|
title: "AI Response"
|
||||||
|
message: "{{ weather_response.response_text }}"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Available Fields in response_variable
|
||||||
|
|
||||||
|
When you use `response_variable`, you will receive an object with the following fields:
|
||||||
|
|
||||||
|
- `response_text` (string) - The AI response text
|
||||||
|
- `tokens_used` (integer) - Total number of tokens used
|
||||||
|
- `prompt_tokens` (integer) - Number of tokens in the prompt
|
||||||
|
- `completion_tokens` (integer) - Number of tokens in the completion
|
||||||
|
- `model_used` (string) - The AI model that was used for the response
|
||||||
|
- `instance` (string) - The instance name that was used
|
||||||
|
- `question` (string) - The original question that was asked
|
||||||
|
- `timestamp` (string) - ISO timestamp when the response was generated
|
||||||
|
- `success` (boolean) - Whether the request was successful
|
||||||
|
- `error` (string) - Error message if the request failed
|
||||||
|
|
||||||
|
## Example Using Response Fields
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
action:
|
||||||
|
- action: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
instance: sensor.ha_text_ai_gemini
|
||||||
|
question: "Tell me a joke"
|
||||||
|
response_variable: joke_response
|
||||||
|
|
||||||
|
- condition: template
|
||||||
|
value_template: "{{ joke_response.success }}"
|
||||||
|
|
||||||
|
- action: input_text.set_value
|
||||||
|
target:
|
||||||
|
entity_id: input_text.last_ai_response
|
||||||
|
data:
|
||||||
|
value: "{{ joke_response.response_text }}"
|
||||||
|
|
||||||
|
- action: input_number.set_value
|
||||||
|
target:
|
||||||
|
entity_id: input_number.tokens_used
|
||||||
|
data:
|
||||||
|
value: "{{ joke_response.tokens_used }}"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
action:
|
||||||
|
- action: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
instance: sensor.ha_text_ai_gemini
|
||||||
|
question: "Test question"
|
||||||
|
response_variable: ai_result
|
||||||
|
|
||||||
|
- choose:
|
||||||
|
- conditions:
|
||||||
|
- condition: template
|
||||||
|
value_template: "{{ ai_result.success }}"
|
||||||
|
sequence:
|
||||||
|
- action: notify.mobile_app_phone
|
||||||
|
data:
|
||||||
|
title: "AI Response"
|
||||||
|
message: "{{ ai_result.response_text }}"
|
||||||
|
- conditions:
|
||||||
|
- condition: template
|
||||||
|
value_template: "{{ not ai_result.success }}"
|
||||||
|
sequence:
|
||||||
|
- action: notify.mobile_app_phone
|
||||||
|
data:
|
||||||
|
title: "AI Error"
|
||||||
|
message: "Error: {{ ai_result.error }}"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Migration from Old Approach
|
||||||
|
|
||||||
|
**Old method (without response_variable):**
|
||||||
|
```yaml
|
||||||
|
# Ask question
|
||||||
|
- action: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
instance: sensor.ha_text_ai_gemini
|
||||||
|
question: "Hello!"
|
||||||
|
|
||||||
|
# Wait and read response from sensor
|
||||||
|
- delay: 00:00:05
|
||||||
|
- action: notify.mobile_app_phone
|
||||||
|
data:
|
||||||
|
message: "{{ states('sensor.ha_text_ai_gemini') }}"
|
||||||
|
```
|
||||||
|
|
||||||
|
**New method (with response_variable):**
|
||||||
|
```yaml
|
||||||
|
# Ask question and get response immediately
|
||||||
|
- action: ha_text_ai.ask_question
|
||||||
|
data:
|
||||||
|
instance: sensor.ha_text_ai_gemini
|
||||||
|
question: "Hello!"
|
||||||
|
response_variable: greeting_response
|
||||||
|
|
||||||
|
- action: notify.mobile_app_phone
|
||||||
|
data:
|
||||||
|
message: "{{ greeting_response.response_text }}"
|
||||||
|
```
|
||||||
|
|
||||||
|
The new approach is more reliable as it doesn't require waiting and reading from the sensor.
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
The HA Text AI integration.
|
The HA Text AI integration.
|
||||||
|
|
||||||
@license: CC BY-NC-SA 4.0 International
|
@license: PolyForm Noncommercial 1.0.0 (https://polyformproject.org/licenses/noncommercial/1.0.0)
|
||||||
@author: SMKRV
|
@author: SMKRV
|
||||||
@github: https://github.com/smkrv/ha-text-ai
|
@github: https://github.com/smkrv/ha-text-ai
|
||||||
@source: https://github.com/smkrv/ha-text-ai
|
@source: https://github.com/smkrv/ha-text-ai
|
||||||
@@ -9,24 +9,24 @@ The HA Text AI integration.
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import os
|
from typing import Any, Dict
|
||||||
import shutil
|
|
||||||
import hashlib
|
import asyncio
|
||||||
from datetime import datetime, timedelta
|
|
||||||
from typing import Any, Dict, TypeVar
|
|
||||||
|
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
from async_timeout import timeout
|
|
||||||
|
|
||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import ConfigEntry
|
||||||
from homeassistant.const import CONF_API_KEY, CONF_NAME, Platform
|
from homeassistant.const import CONF_API_KEY, CONF_NAME
|
||||||
from homeassistant.core import HomeAssistant, ServiceCall
|
from homeassistant.core import HomeAssistant, ServiceCall, SupportsResponse
|
||||||
from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError
|
from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError
|
||||||
from homeassistant.helpers import config_validation as cv
|
from homeassistant.helpers import config_validation as cv
|
||||||
from homeassistant.helpers import aiohttp_client
|
from homeassistant.helpers import aiohttp_client
|
||||||
|
from homeassistant.util import dt as dt_util
|
||||||
|
|
||||||
from .coordinator import HATextAICoordinator
|
from .coordinator import HATextAICoordinator
|
||||||
from .api_client import APIClient
|
from .api_client import APIClient
|
||||||
|
from .utils import normalize_name, safe_log_data, validate_endpoint
|
||||||
|
from .providers import get_default_endpoint, get_default_model, build_auth_headers
|
||||||
from .const import (
|
from .const import (
|
||||||
DOMAIN,
|
DOMAIN,
|
||||||
PLATFORMS,
|
PLATFORMS,
|
||||||
@@ -35,46 +35,38 @@ from .const import (
|
|||||||
CONF_MAX_TOKENS,
|
CONF_MAX_TOKENS,
|
||||||
CONF_API_ENDPOINT,
|
CONF_API_ENDPOINT,
|
||||||
CONF_REQUEST_INTERVAL,
|
CONF_REQUEST_INTERVAL,
|
||||||
|
CONF_API_TIMEOUT,
|
||||||
CONF_API_PROVIDER,
|
CONF_API_PROVIDER,
|
||||||
CONF_CONTEXT_MESSAGES,
|
CONF_CONTEXT_MESSAGES,
|
||||||
API_PROVIDER_OPENAI,
|
|
||||||
API_PROVIDER_ANTHROPIC,
|
|
||||||
API_PROVIDER_DEEPSEEK,
|
|
||||||
API_PROVIDER_GEMINI,
|
|
||||||
DEFAULT_MODEL,
|
|
||||||
DEFAULT_DEEPSEEK_MODEL,
|
|
||||||
DEFAULT_GEMINI_MODEL,
|
|
||||||
DEFAULT_TEMPERATURE,
|
DEFAULT_TEMPERATURE,
|
||||||
DEFAULT_MAX_TOKENS,
|
DEFAULT_MAX_TOKENS,
|
||||||
DEFAULT_OPENAI_ENDPOINT,
|
|
||||||
DEFAULT_ANTHROPIC_ENDPOINT,
|
|
||||||
DEFAULT_DEEPSEEK_ENDPOINT,
|
|
||||||
DEFAULT_GEMINI_ENDPOINT,
|
|
||||||
DEFAULT_REQUEST_INTERVAL,
|
DEFAULT_REQUEST_INTERVAL,
|
||||||
|
DEFAULT_API_TIMEOUT,
|
||||||
DEFAULT_CONTEXT_MESSAGES,
|
DEFAULT_CONTEXT_MESSAGES,
|
||||||
API_TIMEOUT,
|
|
||||||
SERVICE_ASK_QUESTION,
|
SERVICE_ASK_QUESTION,
|
||||||
SERVICE_CLEAR_HISTORY,
|
SERVICE_CLEAR_HISTORY,
|
||||||
SERVICE_GET_HISTORY,
|
SERVICE_GET_HISTORY,
|
||||||
SERVICE_SET_SYSTEM_PROMPT,
|
SERVICE_SET_SYSTEM_PROMPT,
|
||||||
DEFAULT_MAX_HISTORY,
|
DEFAULT_MAX_HISTORY,
|
||||||
CONF_MAX_HISTORY_SIZE,
|
CONF_MAX_HISTORY_SIZE,
|
||||||
ICONS_SUBDOMAIN,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
|
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
|
||||||
ConfigType = TypeVar("ConfigType", bound=Dict[str, Any])
|
|
||||||
|
|
||||||
SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
|
SERVICE_SCHEMA_ASK_QUESTION = vol.Schema({
|
||||||
vol.Required("instance"): cv.string,
|
vol.Required("instance"): cv.string,
|
||||||
vol.Required("question"): cv.string,
|
vol.Required("question"): vol.All(cv.string, vol.Length(min=1, max=100000)),
|
||||||
vol.Optional("system_prompt"): cv.string,
|
vol.Optional("system_prompt"): vol.All(cv.string, vol.Length(max=50000)),
|
||||||
vol.Optional("model"): cv.string,
|
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("max_tokens"): cv.positive_int,
|
||||||
vol.Optional("context_messages"): 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)),
|
||||||
})
|
})
|
||||||
|
|
||||||
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
|
SERVICE_SCHEMA_SET_SYSTEM_PROMPT = vol.Schema({
|
||||||
@@ -86,47 +78,80 @@ SERVICE_SCHEMA_GET_HISTORY = vol.Schema({
|
|||||||
vol.Required("instance"): cv.string,
|
vol.Required("instance"): cv.string,
|
||||||
vol.Optional("limit"): cv.positive_int,
|
vol.Optional("limit"): cv.positive_int,
|
||||||
vol.Optional("filter_model"): cv.string,
|
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:
|
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."):
|
if instance.startswith("sensor."):
|
||||||
instance = instance.replace("sensor.ha_text_ai_", "", 1)
|
instance = instance.replace("sensor.ha_text_ai_", "", 1)
|
||||||
|
|
||||||
|
normalized_input = normalize_name(instance)
|
||||||
|
|
||||||
for entry_id, coord in hass.data[DOMAIN].items():
|
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
|
return coord
|
||||||
|
|
||||||
raise HomeAssistantError(f"Instance {instance} not found")
|
raise HomeAssistantError(f"Instance {instance} not found")
|
||||||
|
|
||||||
def get_file_hash(file_path: str) -> str:
|
async def async_setup(hass: HomeAssistant, config: Dict[str, Any]) -> bool:
|
||||||
"""Calculate SHA256 hash of file."""
|
|
||||||
sha256_hash = hashlib.sha256()
|
|
||||||
with open(file_path, "rb") as f:
|
|
||||||
for byte_block in iter(lambda: f.read(4096), b""):
|
|
||||||
sha256_hash.update(byte_block)
|
|
||||||
return sha256_hash.hexdigest()
|
|
||||||
|
|
||||||
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
||||||
"""Set up the Home Assistant Text AI component."""
|
"""Set up the Home Assistant Text AI component."""
|
||||||
# Initialize domain data storage
|
# Initialize domain data storage
|
||||||
hass.data.setdefault(DOMAIN, {})
|
hass.data.setdefault(DOMAIN, {})
|
||||||
|
|
||||||
async def async_ask_question(call: ServiceCall) -> None:
|
async def async_ask_question(call: ServiceCall) -> dict:
|
||||||
"""Handle ask_question service."""
|
"""Handle ask_question service with response data."""
|
||||||
try:
|
try:
|
||||||
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||||
await coordinator.async_ask_question(
|
response = await coordinator.async_ask_question(
|
||||||
question=call.data["question"],
|
question=call.data["question"],
|
||||||
model=call.data.get("model"),
|
model=call.data.get("model"),
|
||||||
temperature=call.data.get("temperature"),
|
temperature=call.data.get("temperature"),
|
||||||
max_tokens=call.data.get("max_tokens"),
|
max_tokens=call.data.get("max_tokens"),
|
||||||
system_prompt=call.data.get("system_prompt"),
|
system_prompt=call.data.get("system_prompt"),
|
||||||
context_messages=call.data.get("context_messages"),
|
context_messages=call.data.get("context_messages"),
|
||||||
|
structured_output=call.data.get("structured_output", False),
|
||||||
|
json_schema=call.data.get("json_schema"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# 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:
|
except Exception as err:
|
||||||
_LOGGER.error("Error asking question: %s", str(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:
|
async def async_clear_history(call: ServiceCall) -> None:
|
||||||
"""Handle clear_history service."""
|
"""Handle clear_history service."""
|
||||||
@@ -143,7 +168,10 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|||||||
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
coordinator = get_coordinator_by_instance(hass, call.data["instance"])
|
||||||
return await coordinator.async_get_history(
|
return await coordinator.async_get_history(
|
||||||
limit=call.data.get("limit"),
|
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")
|
||||||
)
|
)
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
_LOGGER.error("Error getting history: %s", str(err))
|
_LOGGER.error("Error getting history: %s", str(err))
|
||||||
@@ -163,7 +191,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|||||||
DOMAIN,
|
DOMAIN,
|
||||||
SERVICE_ASK_QUESTION,
|
SERVICE_ASK_QUESTION,
|
||||||
async_ask_question,
|
async_ask_question,
|
||||||
schema=SERVICE_SCHEMA_ASK_QUESTION
|
schema=SERVICE_SCHEMA_ASK_QUESTION,
|
||||||
|
supports_response=SupportsResponse.OPTIONAL
|
||||||
)
|
)
|
||||||
|
|
||||||
hass.services.async_register(
|
hass.services.async_register(
|
||||||
@@ -177,7 +206,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|||||||
DOMAIN,
|
DOMAIN,
|
||||||
SERVICE_GET_HISTORY,
|
SERVICE_GET_HISTORY,
|
||||||
async_get_history,
|
async_get_history,
|
||||||
schema=SERVICE_SCHEMA_GET_HISTORY
|
schema=SERVICE_SCHEMA_GET_HISTORY,
|
||||||
|
supports_response=SupportsResponse.OPTIONAL
|
||||||
)
|
)
|
||||||
|
|
||||||
hass.services.async_register(
|
hass.services.async_register(
|
||||||
@@ -187,71 +217,33 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|||||||
schema=SERVICE_SCHEMA_SET_SYSTEM_PROMPT
|
schema=SERVICE_SCHEMA_SET_SYSTEM_PROMPT
|
||||||
)
|
)
|
||||||
|
|
||||||
# Handle icons
|
|
||||||
try:
|
|
||||||
source_icon_path = os.path.join(
|
|
||||||
os.path.dirname(__file__),
|
|
||||||
ICONS_SUBDOMAIN,
|
|
||||||
'icon@2x.png'
|
|
||||||
)
|
|
||||||
|
|
||||||
destination_directory = os.path.join(
|
|
||||||
hass.config.path('www'),
|
|
||||||
DOMAIN,
|
|
||||||
ICONS_SUBDOMAIN
|
|
||||||
)
|
|
||||||
|
|
||||||
destination_icon_path = os.path.join(
|
|
||||||
destination_directory,
|
|
||||||
'icon.png'
|
|
||||||
)
|
|
||||||
|
|
||||||
if not os.path.exists(source_icon_path):
|
|
||||||
_LOGGER.error("Source icon not found: %s", source_icon_path)
|
|
||||||
return True
|
|
||||||
|
|
||||||
def create_directory():
|
|
||||||
os.makedirs(destination_directory, exist_ok=True)
|
|
||||||
|
|
||||||
await hass.async_add_executor_job(create_directory)
|
|
||||||
|
|
||||||
should_copy = True
|
|
||||||
|
|
||||||
if os.path.exists(destination_icon_path):
|
|
||||||
source_hash = await hass.async_add_executor_job(get_file_hash, source_icon_path)
|
|
||||||
dest_hash = await hass.async_add_executor_job(get_file_hash, destination_icon_path)
|
|
||||||
should_copy = source_hash != dest_hash
|
|
||||||
|
|
||||||
if should_copy:
|
|
||||||
def copy_file():
|
|
||||||
shutil.copyfile(source_icon_path, destination_icon_path)
|
|
||||||
|
|
||||||
await hass.async_add_executor_job(copy_file)
|
|
||||||
_LOGGER.debug("Icon updated: %s", destination_icon_path)
|
|
||||||
|
|
||||||
except PermissionError as e:
|
|
||||||
_LOGGER.error("Permission denied when managing icons: %s", str(e))
|
|
||||||
except Exception as e:
|
|
||||||
_LOGGER.error("Failed to manage icons: %s", str(e))
|
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
async def async_check_api(session, endpoint: str, headers: dict, provider: str) -> bool:
|
async def async_check_api(session, endpoint: str, headers: dict, provider: str, api_timeout: int = DEFAULT_API_TIMEOUT) -> bool:
|
||||||
"""Check API availability for different providers."""
|
"""Check API availability using provider registry configuration."""
|
||||||
try:
|
try:
|
||||||
if provider == API_PROVIDER_ANTHROPIC:
|
from .providers import get_provider_config
|
||||||
check_url = f"{endpoint}/v1/models"
|
provider_config = get_provider_config(provider)
|
||||||
elif provider == API_PROVIDER_DEEPSEEK:
|
check_path = provider_config.get("check_path")
|
||||||
check_url = f"{endpoint}/models" # DeepSeek
|
|
||||||
else: # OpenAI
|
|
||||||
check_url = f"{endpoint}/models"
|
|
||||||
|
|
||||||
async with timeout(API_TIMEOUT):
|
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) as response:
|
async with session.get(check_url, headers=headers) as response:
|
||||||
if response.status in [200, 404]:
|
if response.status == 200:
|
||||||
return True
|
return True
|
||||||
elif response.status == 401:
|
elif response.status == 401:
|
||||||
raise ConfigEntryNotReady("Invalid API key")
|
_LOGGER.error("Invalid API key")
|
||||||
|
return False
|
||||||
elif response.status == 429:
|
elif response.status == 429:
|
||||||
_LOGGER.warning("Rate limit exceeded during API check")
|
_LOGGER.warning("Rate limit exceeded during API check")
|
||||||
return False
|
return False
|
||||||
@@ -264,43 +256,39 @@ async def async_check_api(session, endpoint: str, headers: dict, provider: str)
|
|||||||
|
|
||||||
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||||
"""Set up HA Text AI from a config entry."""
|
"""Set up HA Text AI from a config entry."""
|
||||||
_LOGGER.debug(f"Setting up HA Text AI entry: {entry.data}")
|
_LOGGER.debug("Setting up HA Text AI entry: %s", safe_log_data(dict(entry.data)))
|
||||||
|
|
||||||
try:
|
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")
|
_LOGGER.error("API provider not specified")
|
||||||
raise ConfigEntryNotReady("API provider is required")
|
raise ConfigEntryNotReady("API provider is required")
|
||||||
|
|
||||||
# Get configuration
|
|
||||||
session = aiohttp_client.async_get_clientsession(hass)
|
session = aiohttp_client.async_get_clientsession(hass)
|
||||||
api_provider = entry.data.get(CONF_API_PROVIDER)
|
|
||||||
model = entry.data.get(CONF_MODEL, DEFAULT_MODEL)
|
model = config.get(CONF_MODEL, get_default_model(api_provider))
|
||||||
endpoint = entry.data.get(
|
raw_endpoint = config.get(CONF_API_ENDPOINT, get_default_endpoint(api_provider))
|
||||||
CONF_API_ENDPOINT,
|
try:
|
||||||
DEFAULT_OPENAI_ENDPOINT if api_provider == API_PROVIDER_OPENAI
|
endpoint = await validate_endpoint(hass, raw_endpoint)
|
||||||
else DEFAULT_ANTHROPIC_ENDPOINT
|
except ValueError as err:
|
||||||
).rstrip('/')
|
_LOGGER.error("Invalid API endpoint: %s", err)
|
||||||
api_key = entry.data[CONF_API_KEY]
|
raise ConfigEntryNotReady(f"Invalid API endpoint: {err}") from err
|
||||||
|
# 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)
|
instance_name = entry.data.get(CONF_NAME, entry.entry_id)
|
||||||
request_interval = entry.data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
request_interval = config.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
||||||
max_tokens = entry.data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
api_timeout = config.get(CONF_API_TIMEOUT, DEFAULT_API_TIMEOUT)
|
||||||
temperature = entry.data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
max_tokens = config.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
||||||
max_history_size = entry.data.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
|
temperature = config.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
||||||
context_messages = entry.data.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
|
max_history_size = config.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY)
|
||||||
is_anthropic = api_provider == API_PROVIDER_ANTHROPIC
|
context_messages = config.get(CONF_CONTEXT_MESSAGES, DEFAULT_CONTEXT_MESSAGES)
|
||||||
|
|
||||||
headers = {
|
headers = build_auth_headers(api_provider, api_key)
|
||||||
"Content-Type": "application/json",
|
|
||||||
"Accept": "application/json"
|
|
||||||
}
|
|
||||||
|
|
||||||
if is_anthropic:
|
if not await async_check_api(session, endpoint, headers, api_provider, api_timeout):
|
||||||
headers["x-api-key"] = api_key
|
|
||||||
headers["anthropic-version"] = "2023-06-01"
|
|
||||||
else:
|
|
||||||
headers["Authorization"] = f"Bearer {api_key}"
|
|
||||||
|
|
||||||
if not await async_check_api(session, endpoint, headers, api_provider):
|
|
||||||
raise ConfigEntryNotReady("API connection failed")
|
raise ConfigEntryNotReady("API connection failed")
|
||||||
|
|
||||||
_LOGGER.debug("Creating API client for %s with endpoint %s", api_provider, endpoint)
|
_LOGGER.debug("Creating API client for %s with endpoint %s", api_provider, endpoint)
|
||||||
@@ -311,6 +299,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
headers=headers,
|
headers=headers,
|
||||||
api_provider=api_provider,
|
api_provider=api_provider,
|
||||||
model=model,
|
model=model,
|
||||||
|
api_timeout=api_timeout,
|
||||||
|
api_key=api_key,
|
||||||
)
|
)
|
||||||
|
|
||||||
coordinator = HATextAICoordinator(
|
coordinator = HATextAICoordinator(
|
||||||
@@ -319,45 +309,61 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||||||
model=model,
|
model=model,
|
||||||
update_interval=request_interval,
|
update_interval=request_interval,
|
||||||
instance_name=instance_name,
|
instance_name=instance_name,
|
||||||
|
config_entry=entry,
|
||||||
max_tokens=max_tokens,
|
max_tokens=max_tokens,
|
||||||
temperature=temperature,
|
temperature=temperature,
|
||||||
max_history_size=max_history_size,
|
max_history_size=max_history_size,
|
||||||
context_messages=context_messages,
|
context_messages=context_messages,
|
||||||
is_anthropic=is_anthropic,
|
api_timeout=api_timeout,
|
||||||
)
|
)
|
||||||
|
|
||||||
_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
|
# Store coordinator
|
||||||
hass.data.setdefault(DOMAIN, {})
|
hass.data.setdefault(DOMAIN, {})
|
||||||
hass.data[DOMAIN][entry.entry_id] = coordinator
|
hass.data[DOMAIN][entry.entry_id] = coordinator
|
||||||
|
|
||||||
_LOGGER.debug(f"Stored coordinator in hass.data[{DOMAIN}][{entry.entry_id}]")
|
_LOGGER.debug("Stored coordinator in hass.data[%s][%s]", DOMAIN, entry.entry_id)
|
||||||
|
|
||||||
# Set up platforms
|
# Set up platforms
|
||||||
await hass.config_entries.async_forward_entry_setups(entry, 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))
|
||||||
|
|
||||||
|
_LOGGER.debug("Setup completed for %s", instance_name)
|
||||||
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
_LOGGER.exception(f"Error setting up HA Text AI: {err}")
|
_LOGGER.exception("Error setting up HA Text AI: %s", err)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
|
async def async_update_options(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
||||||
|
"""Handle options update - reload the config entry."""
|
||||||
|
_LOGGER.info("Options updated for %s, reloading integration", entry.title)
|
||||||
|
await hass.config_entries.async_reload(entry.entry_id)
|
||||||
|
|
||||||
|
|
||||||
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
||||||
"""Unload a config entry."""
|
"""Unload a config entry."""
|
||||||
try:
|
try:
|
||||||
if entry.entry_id in hass.data[DOMAIN]:
|
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||||
coordinator = hass.data[DOMAIN][entry.entry_id]
|
if unload_ok and entry.entry_id in hass.data[DOMAIN]:
|
||||||
|
coordinator = hass.data[DOMAIN].pop(entry.entry_id)
|
||||||
|
|
||||||
if hasattr(coordinator.client, 'shutdown'):
|
if hasattr(coordinator.client, 'shutdown'):
|
||||||
await coordinator.client.shutdown()
|
await coordinator.client.shutdown()
|
||||||
|
|
||||||
await coordinator.async_shutdown()
|
await coordinator.async_shutdown()
|
||||||
hass.data[DOMAIN].pop(entry.entry_id)
|
|
||||||
|
|
||||||
return await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
if not hass.data.get(DOMAIN):
|
||||||
|
hass.data.pop(DOMAIN, None)
|
||||||
|
|
||||||
|
return unload_ok
|
||||||
|
|
||||||
except Exception as ex:
|
except Exception as ex:
|
||||||
_LOGGER.exception("Error unloading entry: %s", str(ex))
|
_LOGGER.exception("Error unloading entry: %s", str(ex))
|
||||||
|
|||||||
@@ -1,21 +1,21 @@
|
|||||||
"""
|
"""
|
||||||
API Client for HA Text AI.
|
API Client for HA Text AI.
|
||||||
|
|
||||||
@license: CC BY-NC-SA 4.0 International
|
@license: PolyForm Noncommercial 1.0.0 (https://polyformproject.org/licenses/noncommercial/1.0.0)
|
||||||
@author: SMKRV
|
@author: SMKRV
|
||||||
@github: https://github.com/smkrv/ha-text-ai
|
@github: https://github.com/smkrv/ha-text-ai
|
||||||
@source: https://github.com/smkrv/ha-text-ai
|
@source: https://github.com/smkrv/ha-text-ai
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import asyncio
|
import asyncio
|
||||||
from typing import Any, Dict, List, Optional
|
from typing import Any, Dict, List, Optional
|
||||||
from aiohttp import ClientSession, ClientTimeout
|
from aiohttp import ClientSession, ClientTimeout
|
||||||
from async_timeout import timeout
|
|
||||||
|
|
||||||
from homeassistant.core import HomeAssistant
|
|
||||||
from homeassistant.exceptions import HomeAssistantError
|
from homeassistant.exceptions import HomeAssistantError
|
||||||
from .const import (
|
from .const import (
|
||||||
API_TIMEOUT,
|
DEFAULT_API_TIMEOUT,
|
||||||
API_RETRY_COUNT,
|
API_RETRY_COUNT,
|
||||||
API_PROVIDER_ANTHROPIC,
|
API_PROVIDER_ANTHROPIC,
|
||||||
API_PROVIDER_DEEPSEEK,
|
API_PROVIDER_DEEPSEEK,
|
||||||
@@ -40,6 +40,8 @@ class APIClient:
|
|||||||
headers: Dict[str, str],
|
headers: Dict[str, str],
|
||||||
api_provider: str,
|
api_provider: str,
|
||||||
model: str,
|
model: str,
|
||||||
|
api_timeout: int = DEFAULT_API_TIMEOUT,
|
||||||
|
api_key: Optional[str] = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Initialize API client."""
|
"""Initialize API client."""
|
||||||
self.session = session
|
self.session = session
|
||||||
@@ -47,21 +49,41 @@ class APIClient:
|
|||||||
self.headers = headers
|
self.headers = headers
|
||||||
self.api_provider = api_provider
|
self.api_provider = api_provider
|
||||||
self.model = model
|
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(
|
def _validate_parameters(
|
||||||
self,
|
self,
|
||||||
temperature: float,
|
temperature: float,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
) -> None:
|
) -> 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:
|
if not MIN_TEMPERATURE <= temperature <= MAX_TEMPERATURE:
|
||||||
raise ValueError(
|
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:
|
if not MIN_MAX_TOKENS <= max_tokens <= MAX_MAX_TOKENS:
|
||||||
raise ValueError(
|
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(
|
async def _make_request(
|
||||||
@@ -69,33 +91,61 @@ class APIClient:
|
|||||||
url: str,
|
url: str,
|
||||||
payload: Dict[str, Any],
|
payload: Dict[str, Any],
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""Make API request with retry logic."""
|
"""Make API request with retry logic for transient errors only."""
|
||||||
_LOGGER.debug(f"API Request: URL={url}, Payload={payload}")
|
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)
|
||||||
|
|
||||||
for attempt in range(API_RETRY_COUNT):
|
for attempt in range(API_RETRY_COUNT):
|
||||||
try:
|
try:
|
||||||
async with timeout(API_TIMEOUT):
|
async with self.session.post(
|
||||||
async with self.session.post(
|
url,
|
||||||
url,
|
json=payload,
|
||||||
json=payload,
|
headers=self.headers,
|
||||||
headers=self.headers,
|
timeout=self.timeout,
|
||||||
timeout=self.timeout,
|
) as response:
|
||||||
) as response:
|
_LOGGER.debug("Response status: %s", response.status)
|
||||||
_LOGGER.debug(f"Response status: {response.status}")
|
if response.status == 200:
|
||||||
if response.status != 200:
|
|
||||||
error_data = await response.json()
|
|
||||||
_LOGGER.error(f"API error: {error_data}")
|
|
||||||
raise HomeAssistantError(f"API error: {error_data}")
|
|
||||||
return await response.json()
|
return await response.json()
|
||||||
|
|
||||||
|
# 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
|
||||||
|
if response.status == 429:
|
||||||
|
_LOGGER.warning(
|
||||||
|
"Rate limit on attempt %d/%d", attempt + 1, API_RETRY_COUNT
|
||||||
|
)
|
||||||
|
if attempt < API_RETRY_COUNT - 1:
|
||||||
|
await asyncio.sleep(2 ** attempt)
|
||||||
|
continue
|
||||||
|
raise HomeAssistantError("API rate limit exceeded")
|
||||||
|
|
||||||
|
# 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:
|
except asyncio.TimeoutError:
|
||||||
_LOGGER.warning(f"Timeout on attempt {attempt + 1}")
|
_LOGGER.warning("Timeout on attempt %d/%d", attempt + 1, API_RETRY_COUNT)
|
||||||
if attempt == API_RETRY_COUNT - 1:
|
if attempt == API_RETRY_COUNT - 1:
|
||||||
raise HomeAssistantError("API request timed out")
|
raise HomeAssistantError("API request timed out")
|
||||||
await asyncio.sleep(1 * (attempt + 1))
|
await asyncio.sleep(2 ** attempt)
|
||||||
|
except HomeAssistantError:
|
||||||
|
raise
|
||||||
except Exception as e:
|
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:
|
if attempt == API_RETRY_COUNT - 1:
|
||||||
raise
|
raise
|
||||||
await asyncio.sleep(1 * (attempt + 1))
|
await asyncio.sleep(2 ** attempt)
|
||||||
|
|
||||||
|
raise HomeAssistantError("API request failed after all retries")
|
||||||
|
|
||||||
async def create(
|
async def create(
|
||||||
self,
|
self,
|
||||||
@@ -103,6 +153,8 @@ class APIClient:
|
|||||||
messages: List[Dict[str, str]],
|
messages: List[Dict[str, str]],
|
||||||
temperature: float,
|
temperature: float,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""Create completion using appropriate API."""
|
"""Create completion using appropriate API."""
|
||||||
try:
|
try:
|
||||||
@@ -110,30 +162,60 @@ class APIClient:
|
|||||||
|
|
||||||
if self.api_provider == API_PROVIDER_ANTHROPIC:
|
if self.api_provider == API_PROVIDER_ANTHROPIC:
|
||||||
return await self._create_anthropic_completion(
|
return await self._create_anthropic_completion(
|
||||||
model, messages, temperature, max_tokens
|
model, messages, temperature, max_tokens,
|
||||||
|
structured_output, json_schema
|
||||||
)
|
)
|
||||||
elif self.api_provider == API_PROVIDER_DEEPSEEK:
|
elif self.api_provider == API_PROVIDER_DEEPSEEK:
|
||||||
return await self._create_deepseek_completion(
|
return await self._create_deepseek_completion(
|
||||||
model, messages, temperature, max_tokens
|
model, messages, temperature, max_tokens,
|
||||||
|
structured_output, json_schema
|
||||||
)
|
)
|
||||||
elif self.api_provider == API_PROVIDER_GEMINI:
|
elif self.api_provider == API_PROVIDER_GEMINI:
|
||||||
return await self._create_gemini_completion(
|
return await self._create_gemini_completion(
|
||||||
model, messages, temperature, max_tokens
|
model, messages, temperature, max_tokens,
|
||||||
|
structured_output, json_schema
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
return await self._create_openai_completion(
|
return await self._create_openai_completion(
|
||||||
model, messages, temperature, max_tokens
|
model, messages, temperature, max_tokens,
|
||||||
|
structured_output, json_schema
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
_LOGGER.error("API request failed: %s", str(e))
|
_LOGGER.error("API request failed: %s", str(e))
|
||||||
raise HomeAssistantError(f"API request failed: {str(e)}")
|
raise HomeAssistantError(f"API request failed: {str(e)}")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _apply_structured_output(
|
||||||
|
payload: Dict[str, Any],
|
||||||
|
structured_output: bool,
|
||||||
|
json_schema: Optional[str],
|
||||||
|
) -> None:
|
||||||
|
"""Apply OpenAI-compatible structured output to payload in-place."""
|
||||||
|
if not (structured_output and json_schema):
|
||||||
|
return
|
||||||
|
import json
|
||||||
|
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(
|
async def _create_deepseek_completion(
|
||||||
self,
|
self,
|
||||||
model: str,
|
model: str,
|
||||||
messages: List[Dict[str, str]],
|
messages: List[Dict[str, str]],
|
||||||
temperature: float,
|
temperature: float,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""Create completion using DeepSeek API."""
|
"""Create completion using DeepSeek API."""
|
||||||
url = f"{self.endpoint}/chat/completions"
|
url = f"{self.endpoint}/chat/completions"
|
||||||
@@ -142,8 +224,9 @@ class APIClient:
|
|||||||
"messages": messages,
|
"messages": messages,
|
||||||
"temperature": temperature,
|
"temperature": temperature,
|
||||||
"max_tokens": max_tokens,
|
"max_tokens": max_tokens,
|
||||||
"stream": False
|
"stream": False,
|
||||||
}
|
}
|
||||||
|
self._apply_structured_output(payload, structured_output, json_schema)
|
||||||
|
|
||||||
data = await self._make_request(url, payload)
|
data = await self._make_request(url, payload)
|
||||||
return {
|
return {
|
||||||
@@ -165,6 +248,8 @@ class APIClient:
|
|||||||
messages: List[Dict[str, str]],
|
messages: List[Dict[str, str]],
|
||||||
temperature: float,
|
temperature: float,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""Create completion using OpenAI API."""
|
"""Create completion using OpenAI API."""
|
||||||
url = f"{self.endpoint}/chat/completions"
|
url = f"{self.endpoint}/chat/completions"
|
||||||
@@ -174,6 +259,7 @@ class APIClient:
|
|||||||
"temperature": temperature,
|
"temperature": temperature,
|
||||||
"max_tokens": max_tokens,
|
"max_tokens": max_tokens,
|
||||||
}
|
}
|
||||||
|
self._apply_structured_output(payload, structured_output, json_schema)
|
||||||
|
|
||||||
data = await self._make_request(url, payload)
|
data = await self._make_request(url, payload)
|
||||||
return {
|
return {
|
||||||
@@ -195,6 +281,8 @@ class APIClient:
|
|||||||
messages: List[Dict[str, str]],
|
messages: List[Dict[str, str]],
|
||||||
temperature: float,
|
temperature: float,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""Create completion using Anthropic API."""
|
"""Create completion using Anthropic API."""
|
||||||
url = f"{self.endpoint}/v1/messages"
|
url = f"{self.endpoint}/v1/messages"
|
||||||
@@ -210,6 +298,20 @@ class APIClient:
|
|||||||
else:
|
else:
|
||||||
filtered_messages.append(msg)
|
filtered_messages.append(msg)
|
||||||
|
|
||||||
|
# For Anthropic, add structured output instruction to system prompt
|
||||||
|
if structured_output and json_schema:
|
||||||
|
schema_instruction = (
|
||||||
|
f"\n\nIMPORTANT: You MUST respond ONLY with valid JSON that matches "
|
||||||
|
f"this JSON Schema:\n{json_schema}\n"
|
||||||
|
f"Do not include any text before or after the JSON. "
|
||||||
|
f"Do not wrap the JSON in markdown code blocks."
|
||||||
|
)
|
||||||
|
if system_prompt:
|
||||||
|
system_prompt += schema_instruction
|
||||||
|
else:
|
||||||
|
system_prompt = schema_instruction.strip()
|
||||||
|
_LOGGER.debug("Anthropic structured output enabled via system prompt")
|
||||||
|
|
||||||
payload = {
|
payload = {
|
||||||
"model": model,
|
"model": model,
|
||||||
"messages": filtered_messages,
|
"messages": filtered_messages,
|
||||||
@@ -234,110 +336,179 @@ class APIClient:
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
async def check_connection(self) -> bool:
|
|
||||||
"""Check API connection."""
|
|
||||||
try:
|
|
||||||
await self._make_request(self.endpoint, {"test": "connection"})
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
_LOGGER.error(f"Connection check failed: {str(e)}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
async def _create_gemini_completion(
|
async def _create_gemini_completion(
|
||||||
self,
|
self,
|
||||||
model: str,
|
model: str,
|
||||||
messages: List[Dict[str, str]],
|
messages: List[Dict[str, str]],
|
||||||
temperature: float,
|
temperature: float,
|
||||||
max_tokens: int,
|
max_tokens: int,
|
||||||
|
structured_output: bool = False,
|
||||||
|
json_schema: Optional[str] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
"""Create completion using Gemini API."""
|
"""Create completion using Gemini API with google-genai library.
|
||||||
# Extract API key from headers (Bearer token)
|
|
||||||
api_key = self.headers.get("Authorization", "").replace("Bearer ", "")
|
|
||||||
url = f"{self.endpoint}/models/{model}:generateContent?key={api_key}"
|
|
||||||
|
|
||||||
# Convert messages to Gemini format
|
Args:
|
||||||
contents = []
|
model: The model name to use
|
||||||
system_instruction = ""
|
messages: List of message dictionaries with role and content
|
||||||
|
temperature: Sampling temperature between 0.0 and 2.0
|
||||||
# Process messages
|
max_tokens: Maximum number of tokens to generate
|
||||||
for msg in messages:
|
structured_output: Enable JSON structured output mode
|
||||||
if msg['role'] == 'system':
|
json_schema: JSON Schema for structured output validation
|
||||||
system_instruction += msg['content'] + "\n"
|
|
||||||
else:
|
|
||||||
# Convert role: 'user' stays 'user', anything else becomes 'model'
|
|
||||||
role = "user" if msg['role'] == 'user' else "model"
|
|
||||||
contents.append({
|
|
||||||
"role": role,
|
|
||||||
"parts": [{"text": msg['content']}]
|
|
||||||
})
|
|
||||||
|
|
||||||
# Ensure contents starts with a user message if not empty
|
|
||||||
if contents and contents[0]["role"] != "user":
|
|
||||||
# Add a placeholder user message
|
|
||||||
contents.insert(0, {
|
|
||||||
"role": "user",
|
|
||||||
"parts": [{"text": "I need your assistance."}]
|
|
||||||
})
|
|
||||||
|
|
||||||
# Ensure contents is not empty
|
|
||||||
if not contents:
|
|
||||||
contents.append({
|
|
||||||
"role": "user",
|
|
||||||
"parts": [{"text": "I need your assistance."}]
|
|
||||||
})
|
|
||||||
|
|
||||||
# Create payload with snake_case keys as required by Gemini API
|
|
||||||
payload = {
|
|
||||||
"contents": contents,
|
|
||||||
"generation_config": { # Changed from camelCase to snake_case
|
|
||||||
"temperature": temperature,
|
|
||||||
"max_output_tokens": max_tokens # Changed from camelCase to snake_case
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if system_instruction:
|
|
||||||
payload["system_instruction"] = { # Changed from camelCase to snake_case
|
|
||||||
"parts": [{"text": system_instruction.strip()}]
|
|
||||||
}
|
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dictionary with response content and token usage
|
||||||
|
"""
|
||||||
try:
|
try:
|
||||||
data = await self._make_request(url, payload)
|
def import_genai():
|
||||||
|
from google import genai
|
||||||
|
return genai
|
||||||
|
|
||||||
# Safely extract response data
|
genai = await asyncio.to_thread(import_genai)
|
||||||
candidates = data.get("candidates", [])
|
|
||||||
if not candidates:
|
|
||||||
raise HomeAssistantError("Gemini API returned no candidates")
|
|
||||||
|
|
||||||
content = candidates[0].get("content", {})
|
api_key = self._api_key
|
||||||
parts = content.get("parts", [])
|
|
||||||
if not parts:
|
|
||||||
raise HomeAssistantError("Gemini API response contains no content parts")
|
|
||||||
|
|
||||||
answer_text = parts[0].get("text", "")
|
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)
|
||||||
|
|
||||||
# Safely extract usage data
|
client = await asyncio.to_thread(create_client)
|
||||||
usage = data.get("usageMetadata", {})
|
|
||||||
prompt_tokens = usage.get("promptTokenCount", 0)
|
# Process messages to extract system instruction and chat history
|
||||||
completion_tokens = usage.get("candidatesTokenCount", 0)
|
system_instruction = ""
|
||||||
total_tokens = usage.get("totalTokenCount", prompt_tokens + completion_tokens)
|
contents = []
|
||||||
|
|
||||||
|
for msg in messages:
|
||||||
|
if msg['role'] == 'system':
|
||||||
|
system_instruction += msg['content'] + "\n"
|
||||||
|
else:
|
||||||
|
# For chat history, we need to convert to the format Gemini expects
|
||||||
|
role = "user" if msg['role'] == 'user' else "model"
|
||||||
|
contents.append({
|
||||||
|
"role": role,
|
||||||
|
"parts": [{"text": msg['content']}]
|
||||||
|
})
|
||||||
|
|
||||||
|
# Parse JSON schema if structured output is enabled
|
||||||
|
parsed_schema = None
|
||||||
|
if structured_output and json_schema:
|
||||||
|
try:
|
||||||
|
import json
|
||||||
|
parsed_schema = json.loads(json_schema)
|
||||||
|
_LOGGER.debug("Gemini structured output enabled with schema")
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
_LOGGER.warning("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
|
||||||
|
|
||||||
|
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)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"choices": [{
|
"choices": [{
|
||||||
"message": {
|
"message": {
|
||||||
"content": answer_text
|
"content": response_text
|
||||||
}
|
}
|
||||||
}],
|
}],
|
||||||
"usage": {
|
"usage": usage
|
||||||
"prompt_tokens": prompt_tokens,
|
|
||||||
"completion_tokens": completion_tokens,
|
|
||||||
"total_tokens": total_tokens
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
except ImportError as e:
|
||||||
|
_LOGGER.error("Google Gemini library not installed: %s", e)
|
||||||
|
raise HomeAssistantError("Missing dependency: google-genai. Please install it.")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
_LOGGER.error(f"Gemini API error: {str(e)}")
|
_LOGGER.error("Gemini API error: %s", e)
|
||||||
raise HomeAssistantError(f"Gemini API error: {str(e)}")
|
raise HomeAssistantError("Gemini API request failed")
|
||||||
|
|
||||||
async def shutdown(self) -> None:
|
async def shutdown(self) -> None:
|
||||||
"""Shutdown API client."""
|
"""Shutdown API client."""
|
||||||
_LOGGER.debug("Shutting down API client")
|
_LOGGER.debug("Shutting down API client")
|
||||||
await self.session.close()
|
self._closed = True
|
||||||
|
# Do NOT close the shared Home Assistant session
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
"""
|
"""
|
||||||
Config flow for HA text AI integration.
|
Config flow for HA text AI integration.
|
||||||
|
|
||||||
@license: CC BY-NC-SA 4.0 International
|
@license: PolyForm Noncommercial 1.0.0 (https://polyformproject.org/licenses/noncommercial/1.0.0)
|
||||||
@author: SMKRV
|
@author: SMKRV
|
||||||
@github: https://github.com/smkrv/ha-text-ai
|
@github: https://github.com/smkrv/ha-text-ai
|
||||||
@source: https://github.com/smkrv/ha-text-ai
|
@source: https://github.com/smkrv/ha-text-ai
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
from typing import Any, Dict, Optional
|
from typing import Any, Dict, Optional
|
||||||
|
|
||||||
@@ -13,7 +15,7 @@ import voluptuous as vol
|
|||||||
from homeassistant import config_entries
|
from homeassistant import config_entries
|
||||||
from homeassistant.const import CONF_API_KEY, CONF_NAME
|
from homeassistant.const import CONF_API_KEY, CONF_NAME
|
||||||
from homeassistant.core import callback
|
from homeassistant.core import callback
|
||||||
from homeassistant.data_entry_flow import FlowResult
|
from homeassistant.config_entries import ConfigFlowResult
|
||||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||||
from homeassistant.helpers import selector
|
from homeassistant.helpers import selector
|
||||||
|
|
||||||
@@ -24,6 +26,7 @@ from .const import (
|
|||||||
CONF_MAX_TOKENS,
|
CONF_MAX_TOKENS,
|
||||||
CONF_API_ENDPOINT,
|
CONF_API_ENDPOINT,
|
||||||
CONF_REQUEST_INTERVAL,
|
CONF_REQUEST_INTERVAL,
|
||||||
|
CONF_API_TIMEOUT,
|
||||||
CONF_API_PROVIDER,
|
CONF_API_PROVIDER,
|
||||||
CONF_CONTEXT_MESSAGES,
|
CONF_CONTEXT_MESSAGES,
|
||||||
API_PROVIDER_OPENAI,
|
API_PROVIDER_OPENAI,
|
||||||
@@ -31,35 +34,63 @@ from .const import (
|
|||||||
API_PROVIDER_DEEPSEEK,
|
API_PROVIDER_DEEPSEEK,
|
||||||
API_PROVIDER_GEMINI,
|
API_PROVIDER_GEMINI,
|
||||||
API_PROVIDERS,
|
API_PROVIDERS,
|
||||||
DEFAULT_MODEL,
|
|
||||||
DEFAULT_DEEPSEEK_MODEL,
|
|
||||||
DEFAULT_GEMINI_MODEL,
|
|
||||||
DEFAULT_TEMPERATURE,
|
DEFAULT_TEMPERATURE,
|
||||||
DEFAULT_MAX_TOKENS,
|
DEFAULT_MAX_TOKENS,
|
||||||
DEFAULT_REQUEST_INTERVAL,
|
DEFAULT_REQUEST_INTERVAL,
|
||||||
DEFAULT_OPENAI_ENDPOINT,
|
DEFAULT_API_TIMEOUT,
|
||||||
DEFAULT_ANTHROPIC_ENDPOINT,
|
|
||||||
DEFAULT_DEEPSEEK_ENDPOINT,
|
|
||||||
DEFAULT_GEMINI_ENDPOINT,
|
|
||||||
DEFAULT_CONTEXT_MESSAGES,
|
DEFAULT_CONTEXT_MESSAGES,
|
||||||
MIN_TEMPERATURE,
|
MIN_TEMPERATURE,
|
||||||
MAX_TEMPERATURE,
|
MAX_TEMPERATURE,
|
||||||
MIN_MAX_TOKENS,
|
MIN_MAX_TOKENS,
|
||||||
MAX_MAX_TOKENS,
|
MAX_MAX_TOKENS,
|
||||||
MIN_REQUEST_INTERVAL,
|
MIN_REQUEST_INTERVAL,
|
||||||
|
MIN_API_TIMEOUT,
|
||||||
|
MAX_API_TIMEOUT,
|
||||||
DEFAULT_NAME_PREFIX,
|
DEFAULT_NAME_PREFIX,
|
||||||
|
DEFAULT_INSTANCE_NAME,
|
||||||
DEFAULT_MAX_HISTORY,
|
DEFAULT_MAX_HISTORY,
|
||||||
CONF_MAX_HISTORY_SIZE,
|
CONF_MAX_HISTORY_SIZE,
|
||||||
|
MIN_CONTEXT_MESSAGES,
|
||||||
|
MAX_CONTEXT_MESSAGES,
|
||||||
|
MIN_HISTORY_SIZE,
|
||||||
|
MAX_HISTORY_SIZE,
|
||||||
)
|
)
|
||||||
|
from homeassistant.util import dt as dt_util
|
||||||
|
|
||||||
|
from .utils import normalize_name, safe_log_data, validate_endpoint
|
||||||
|
from .providers import get_default_endpoint, get_default_model, build_auth_headers
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
def normalize_name(name: str) -> str:
|
def _build_parameter_schema(data: Dict[str, Any]) -> dict:
|
||||||
"""Normalize name to conform to HA naming convention using underscores."""
|
"""Build shared parameter schema fields used by both ConfigFlow and OptionsFlow."""
|
||||||
normalized = ''.join(c if c.isalnum() or c == '_' else '_' for c in name)
|
return {
|
||||||
normalized = '_'.join(filter(None, normalized.split('_')))
|
vol.Optional(
|
||||||
return normalized.lower()
|
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)),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||||
@@ -73,7 +104,7 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
self._data = {}
|
self._data = {}
|
||||||
self._provider = None
|
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: Optional[Dict[str, Any]] = None) -> ConfigFlowResult:
|
||||||
"""Handle the initial step."""
|
"""Handle the initial step."""
|
||||||
if user_input is None:
|
if user_input is None:
|
||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
@@ -91,80 +122,57 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
self._provider = user_input[CONF_API_PROVIDER]
|
self._provider = user_input[CONF_API_PROVIDER]
|
||||||
return await self.async_step_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: Optional[Dict[str, Any]] = 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): str,
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
schema_dict.update(_build_parameter_schema(defaults))
|
||||||
|
return vol.Schema(schema_dict)
|
||||||
|
|
||||||
|
async def async_step_provider(self, user_input: Optional[Dict[str, Any]] = None) -> ConfigFlowResult:
|
||||||
"""Handle provider configuration step."""
|
"""Handle provider configuration step."""
|
||||||
self._errors = {}
|
self._errors = {}
|
||||||
|
|
||||||
if user_input is None:
|
if user_input is None:
|
||||||
# Selecting an endpoint by provider
|
|
||||||
default_endpoint = {
|
|
||||||
API_PROVIDER_OPENAI: DEFAULT_OPENAI_ENDPOINT,
|
|
||||||
API_PROVIDER_ANTHROPIC: DEFAULT_ANTHROPIC_ENDPOINT,
|
|
||||||
API_PROVIDER_DEEPSEEK: DEFAULT_DEEPSEEK_ENDPOINT,
|
|
||||||
API_PROVIDER_GEMINI: DEFAULT_GEMINI_ENDPOINT,
|
|
||||||
}.get(self._provider, DEFAULT_OPENAI_ENDPOINT)
|
|
||||||
|
|
||||||
# Selecting the default model by provider
|
|
||||||
default_model = (
|
|
||||||
DEFAULT_DEEPSEEK_MODEL if self._provider == API_PROVIDER_DEEPSEEK else
|
|
||||||
DEFAULT_GEMINI_MODEL if self._provider == API_PROVIDER_GEMINI else
|
|
||||||
DEFAULT_MODEL
|
|
||||||
)
|
|
||||||
|
|
||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
step_id="provider",
|
step_id="provider",
|
||||||
data_schema=vol.Schema({
|
data_schema=self._build_provider_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)
|
|
||||||
),
|
|
||||||
})
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
_LOGGER.debug("Provider step input data: %s", safe_log_data(user_input))
|
||||||
|
|
||||||
input_copy = user_input.copy()
|
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:
|
try:
|
||||||
normalized_name = self._validate_and_normalize_name(input_copy[CONF_NAME])
|
normalized_name = self._validate_and_normalize_name(input_copy[CONF_NAME])
|
||||||
input_copy[CONF_NAME] = normalized_name
|
input_copy[CONF_NAME] = normalized_name
|
||||||
except ValueError as e:
|
except ValueError as e:
|
||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
step_id="provider",
|
step_id="provider",
|
||||||
data_schema=vol.Schema({
|
data_schema=self._build_provider_schema(input_copy),
|
||||||
vol.Required(CONF_NAME, default=input_copy[CONF_NAME]): str,
|
|
||||||
vol.Required(CONF_API_KEY, default=input_copy[CONF_API_KEY]): str,
|
|
||||||
vol.Required(CONF_MODEL, default=input_copy[CONF_MODEL]): str,
|
|
||||||
vol.Required(CONF_API_ENDPOINT, default=input_copy[CONF_API_ENDPOINT]): str,
|
|
||||||
vol.Optional(CONF_TEMPERATURE, default=input_copy.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)): vol.All(
|
|
||||||
vol.Coerce(float),
|
|
||||||
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
|
||||||
),
|
|
||||||
}),
|
|
||||||
errors={"name": str(e)}
|
errors={"name": str(e)}
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -172,67 +180,74 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
if not await self._async_validate_api(input_copy):
|
if not await self._async_validate_api(input_copy):
|
||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
step_id="provider",
|
step_id="provider",
|
||||||
data_schema=vol.Schema({}),
|
data_schema=self._build_provider_schema(input_copy),
|
||||||
errors=self._errors
|
errors=self._errors
|
||||||
)
|
)
|
||||||
except Exception as e:
|
except Exception:
|
||||||
|
_LOGGER.exception("Unexpected error during API validation")
|
||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
step_id="provider",
|
step_id="provider",
|
||||||
data_schema=vol.Schema({}),
|
data_schema=self._build_provider_schema(input_copy),
|
||||||
errors={"base": str(e)}
|
errors={"base": "unknown"}
|
||||||
)
|
)
|
||||||
|
|
||||||
return await self._create_entry(input_copy)
|
return await self._create_entry(input_copy)
|
||||||
|
|
||||||
def _validate_and_normalize_name(self, name: str) -> str:
|
def _validate_and_normalize_name(self, name: str) -> str:
|
||||||
"""
|
"""Validate and normalize name.
|
||||||
Validate and normalize name with detailed error handling.
|
|
||||||
|
Truncates before uniqueness check to prevent collisions.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: If name is invalid
|
ValueError: If name is invalid or already exists.
|
||||||
|
|
||||||
Returns:
|
|
||||||
Normalized name
|
|
||||||
"""
|
"""
|
||||||
if not name:
|
if not name or not name.strip():
|
||||||
raise ValueError("empty")
|
raise ValueError("empty")
|
||||||
|
|
||||||
name = name.strip()
|
normalized = normalize_name(name.strip())[:50]
|
||||||
normalized = ''.join(
|
|
||||||
c if c.isalnum() or c in ' _' else '_' # Only allow underscores
|
|
||||||
for c in name
|
|
||||||
)
|
|
||||||
|
|
||||||
normalized = normalized.replace(' ', '_').lower()
|
if not normalized:
|
||||||
|
raise ValueError("empty")
|
||||||
|
|
||||||
for entry in self._async_current_entries():
|
for entry in self._async_current_entries():
|
||||||
if entry.data.get(CONF_NAME, "") == normalized:
|
if entry.data.get(CONF_NAME, "") == normalized:
|
||||||
raise ValueError("name_exists")
|
raise ValueError("name_exists")
|
||||||
|
|
||||||
normalized = normalized[:50]
|
|
||||||
|
|
||||||
if not normalized:
|
|
||||||
raise ValueError("empty")
|
|
||||||
|
|
||||||
return normalized
|
return normalized
|
||||||
|
|
||||||
async def _async_validate_api(self, user_input: Dict[str, Any]) -> bool:
|
async def _async_validate_api(self, user_input: Dict[str, Any]) -> bool:
|
||||||
"""Validate API connection."""
|
"""Validate API connection using provider registry."""
|
||||||
try:
|
try:
|
||||||
session = async_get_clientsession(self.hass)
|
if CONF_API_KEY not in user_input:
|
||||||
headers = self._get_api_headers(user_input)
|
_LOGGER.error("API validation error: 'api_key'")
|
||||||
endpoint = user_input[CONF_API_ENDPOINT].rstrip('/')
|
self._errors["base"] = "invalid_auth"
|
||||||
|
return False
|
||||||
|
|
||||||
check_url = (
|
try:
|
||||||
f"{endpoint}/v1/models" if self._provider == API_PROVIDER_ANTHROPIC
|
endpoint = await validate_endpoint(self.hass, user_input[CONF_API_ENDPOINT])
|
||||||
else f"{endpoint}/models"
|
except ValueError as err:
|
||||||
)
|
_LOGGER.error("Endpoint validation failed: %s", err)
|
||||||
|
self._errors["base"] = "cannot_connect"
|
||||||
|
return False
|
||||||
|
|
||||||
|
if self._provider == API_PROVIDER_GEMINI:
|
||||||
|
if not user_input[CONF_API_KEY]:
|
||||||
|
self._errors["base"] = "invalid_auth"
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
session = async_get_clientsession(self.hass)
|
||||||
|
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}"
|
||||||
|
|
||||||
async with session.get(check_url, headers=headers) as response:
|
async with session.get(check_url, headers=headers) as response:
|
||||||
if response.status == 401:
|
if response.status == 401:
|
||||||
self._errors["base"] = "invalid_auth"
|
self._errors["base"] = "invalid_auth"
|
||||||
return False
|
return False
|
||||||
elif response.status not in [200, 404]:
|
elif response.status != 200:
|
||||||
self._errors["base"] = "cannot_connect"
|
self._errors["base"] = "cannot_connect"
|
||||||
return False
|
return False
|
||||||
return True
|
return True
|
||||||
@@ -242,54 +257,32 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
self._errors["base"] = "cannot_connect"
|
self._errors["base"] = "cannot_connect"
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _get_api_headers(self, user_input: Dict[str, Any]) -> Dict[str, str]:
|
async def _create_entry(self, user_input: Dict[str, Any]) -> ConfigFlowResult:
|
||||||
"""Get API headers based on provider."""
|
"""Create the config entry with unique_id deduplication."""
|
||||||
api_key = user_input[CONF_API_KEY]
|
|
||||||
|
|
||||||
if self._provider == API_PROVIDER_ANTHROPIC:
|
|
||||||
return {
|
|
||||||
"x-api-key": api_key,
|
|
||||||
"anthropic-version": "2023-06-01",
|
|
||||||
"Content-Type": "application/json"
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
"Authorization": f"Bearer {api_key}",
|
|
||||||
"Content-Type": "application/json"
|
|
||||||
}
|
|
||||||
|
|
||||||
async def _create_entry(self, user_input: Dict[str, Any]) -> FlowResult:
|
|
||||||
"""Create the config entry with comprehensive data preservation."""
|
|
||||||
instance_name = user_input[CONF_NAME]
|
instance_name = user_input[CONF_NAME]
|
||||||
normalized_name = normalize_name(instance_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 = (
|
default_model = get_default_model(self._provider)
|
||||||
DEFAULT_DEEPSEEK_MODEL if self._provider == API_PROVIDER_DEEPSEEK else
|
|
||||||
DEFAULT_GEMINI_MODEL if self._provider == API_PROVIDER_GEMINI else
|
|
||||||
DEFAULT_MODEL
|
|
||||||
)
|
|
||||||
|
|
||||||
entry_data = {
|
entry_data = {
|
||||||
CONF_API_PROVIDER: self._provider,
|
CONF_API_PROVIDER: self._provider,
|
||||||
CONF_NAME: instance_name,
|
CONF_NAME: instance_name,
|
||||||
"normalized_name": normalized_name,
|
|
||||||
CONF_API_KEY: user_input.get(CONF_API_KEY),
|
CONF_API_KEY: user_input.get(CONF_API_KEY),
|
||||||
CONF_API_ENDPOINT: user_input.get(CONF_API_ENDPOINT),
|
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_TEMPERATURE: user_input.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE),
|
||||||
CONF_MAX_TOKENS: user_input.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS),
|
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_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_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_MAX_HISTORY_SIZE: user_input.get(CONF_MAX_HISTORY_SIZE, DEFAULT_MAX_HISTORY),
|
||||||
}
|
}
|
||||||
|
|
||||||
for key, value in user_input.items():
|
_LOGGER.debug("Creating config entry with data: %s", safe_log_data(entry_data))
|
||||||
if key not in entry_data:
|
|
||||||
entry_data[key] = value
|
|
||||||
|
|
||||||
_LOGGER.debug(f"Creating config entry with data: {entry_data}")
|
|
||||||
|
|
||||||
return self.async_create_entry(
|
return self.async_create_entry(
|
||||||
title=instance_name,
|
title=instance_name,
|
||||||
@@ -300,77 +293,184 @@ class HATextAIConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
@callback
|
@callback
|
||||||
def async_get_options_flow(config_entry: config_entries.ConfigEntry) -> config_entries.OptionsFlow:
|
def async_get_options_flow(config_entry: config_entries.ConfigEntry) -> config_entries.OptionsFlow:
|
||||||
"""Get the options flow for this handler."""
|
"""Get the options flow for this handler."""
|
||||||
return OptionsFlowHandler(config_entry)
|
return OptionsFlowHandler()
|
||||||
|
|
||||||
|
|
||||||
class OptionsFlowHandler(config_entries.OptionsFlow):
|
class OptionsFlowHandler(config_entries.OptionsFlow):
|
||||||
"""Handle options flow."""
|
"""Handle options flow."""
|
||||||
|
|
||||||
def __init__(self, config_entry: config_entries.ConfigEntry) -> None:
|
async def _async_validate_api(self, provider: str, api_key: str, endpoint: str) -> bool:
|
||||||
"""Initialize options flow."""
|
"""Validate API connection using provider registry."""
|
||||||
self.config_entry = config_entry
|
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:
|
try:
|
||||||
"""Manage the options."""
|
endpoint = await validate_endpoint(self.hass, endpoint)
|
||||||
if user_input is not None:
|
except ValueError as err:
|
||||||
return self.async_create_entry(title="", data=user_input)
|
_LOGGER.error("Endpoint validation failed: %s", err)
|
||||||
|
self._errors["base"] = "cannot_connect"
|
||||||
|
return False
|
||||||
|
|
||||||
|
if provider == API_PROVIDER_GEMINI:
|
||||||
|
return True
|
||||||
|
|
||||||
|
session = async_get_clientsession(self.hass)
|
||||||
|
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}"
|
||||||
|
|
||||||
|
async with session.get(check_url, headers=headers) 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
|
||||||
|
|
||||||
|
except Exception as err:
|
||||||
|
_LOGGER.error("API validation error: %s", str(err))
|
||||||
|
self._errors["base"] = "cannot_connect"
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def async_step_init(self, user_input: Optional[Dict[str, Any]] = None) -> ConfigFlowResult:
|
||||||
|
"""Handle provider selection step."""
|
||||||
|
if not hasattr(self, "_errors"):
|
||||||
|
self._errors: dict[str, str] = {}
|
||||||
|
self._selected_provider: Optional[str] = None
|
||||||
current_data = {**self.config_entry.data, **self.config_entry.options}
|
current_data = {**self.config_entry.data, **self.config_entry.options}
|
||||||
provider = current_data.get(CONF_API_PROVIDER)
|
current_provider = current_data.get(CONF_API_PROVIDER, API_PROVIDER_OPENAI)
|
||||||
|
|
||||||
default_model = (
|
if user_input is not None:
|
||||||
DEFAULT_DEEPSEEK_MODEL if provider == API_PROVIDER_DEEPSEEK else
|
self._selected_provider = user_input.get(CONF_API_PROVIDER, current_provider)
|
||||||
DEFAULT_GEMINI_MODEL if provider == API_PROVIDER_GEMINI else
|
return await self.async_step_settings()
|
||||||
DEFAULT_MODEL
|
|
||||||
)
|
|
||||||
|
|
||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
step_id="init",
|
step_id="init",
|
||||||
data_schema=vol.Schema({
|
data_schema=vol.Schema({
|
||||||
vol.Optional(
|
vol.Required(
|
||||||
CONF_MODEL,
|
CONF_API_PROVIDER,
|
||||||
default=current_data.get(CONF_MODEL, default_model)
|
default=current_provider
|
||||||
): str,
|
): selector.SelectSelector(
|
||||||
vol.Optional(
|
selector.SelectSelectorConfig(
|
||||||
CONF_TEMPERATURE,
|
options=API_PROVIDERS,
|
||||||
default=current_data.get(CONF_TEMPERATURE, DEFAULT_TEMPERATURE)
|
translation_key="api_provider"
|
||||||
): vol.All(
|
|
||||||
vol.Coerce(float),
|
|
||||||
vol.Range(min=MIN_TEMPERATURE, max=MAX_TEMPERATURE)
|
|
||||||
),
|
|
||||||
vol.Optional(
|
|
||||||
CONF_MAX_TOKENS,
|
|
||||||
default=current_data.get(CONF_MAX_TOKENS, DEFAULT_MAX_TOKENS)
|
|
||||||
): vol.All(
|
|
||||||
vol.Coerce(int),
|
|
||||||
vol.Range(min=MIN_MAX_TOKENS, max=MAX_MAX_TOKENS)
|
|
||||||
),
|
|
||||||
vol.Optional(
|
|
||||||
CONF_REQUEST_INTERVAL,
|
|
||||||
default=current_data.get(CONF_REQUEST_INTERVAL, DEFAULT_REQUEST_INTERVAL)
|
|
||||||
): vol.All(
|
|
||||||
vol.Coerce(float),
|
|
||||||
vol.Range(min=MIN_REQUEST_INTERVAL)
|
|
||||||
),
|
|
||||||
vol.Optional(
|
|
||||||
CONF_CONTEXT_MESSAGES,
|
|
||||||
default=current_data.get(
|
|
||||||
CONF_CONTEXT_MESSAGES,
|
|
||||||
DEFAULT_CONTEXT_MESSAGES
|
|
||||||
)
|
)
|
||||||
): vol.All(
|
|
||||||
vol.Coerce(int),
|
|
||||||
vol.Range(min=1, max=20)
|
|
||||||
),
|
),
|
||||||
vol.Optional(
|
}),
|
||||||
CONF_MAX_HISTORY_SIZE,
|
description_placeholders={
|
||||||
default=current_data.get(
|
"current_provider": current_provider
|
||||||
CONF_MAX_HISTORY_SIZE,
|
}
|
||||||
DEFAULT_MAX_HISTORY
|
|
||||||
)
|
|
||||||
): vol.All(
|
|
||||||
vol.Coerce(int),
|
|
||||||
vol.Range(min=1, max=100)
|
|
||||||
),
|
|
||||||
})
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
async def async_step_settings(self, user_input: Optional[Dict[str, Any]] = 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
|
||||||
|
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 if not re-entered and endpoint unchanged
|
||||||
|
if not api_key:
|
||||||
|
api_key = current_data.get(CONF_API_KEY, "")
|
||||||
|
|
||||||
|
if await self._async_validate_api(provider, api_key, endpoint):
|
||||||
|
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: Optional[Dict[str, Any]],
|
||||||
|
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=""): str,
|
||||||
|
vol.Required(
|
||||||
|
CONF_API_ENDPOINT,
|
||||||
|
default=data.get(CONF_API_ENDPOINT, default_endpoint),
|
||||||
|
): str,
|
||||||
|
vol.Required(
|
||||||
|
CONF_MODEL,
|
||||||
|
default=data.get(CONF_MODEL, default_model),
|
||||||
|
): str,
|
||||||
|
}
|
||||||
|
schema_dict.update(_build_parameter_schema(data))
|
||||||
|
return vol.Schema(schema_dict)
|
||||||
|
|||||||
@@ -1,23 +1,19 @@
|
|||||||
"""
|
"""
|
||||||
Constants for the HA text AI integration.
|
Constants for the HA text AI integration.
|
||||||
|
|
||||||
@license: CC BY-NC-SA 4.0 International
|
@license: PolyForm Noncommercial 1.0.0 (https://polyformproject.org/licenses/noncommercial/1.0.0)
|
||||||
@author: SMKRV
|
@author: SMKRV
|
||||||
@github: https://github.com/smkrv/ha-text-ai
|
@github: https://github.com/smkrv/ha-text-ai
|
||||||
@source: https://github.com/smkrv/ha-text-ai
|
@source: https://github.com/smkrv/ha-text-ai
|
||||||
"""
|
"""
|
||||||
import os
|
from __future__ import annotations
|
||||||
import json
|
|
||||||
from typing import Final
|
from typing import Final
|
||||||
import voluptuous as vol
|
from homeassistant.const import Platform
|
||||||
from homeassistant.const import Platform, CONF_API_KEY, CONF_NAME
|
|
||||||
from homeassistant.helpers import config_validation as cv
|
|
||||||
import logging
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
# Domain and platforms
|
# Domain and platforms
|
||||||
DOMAIN: Final = "ha_text_ai"
|
DOMAIN: Final = "ha_text_ai"
|
||||||
PLATFORMS: list[str] = ["sensor"]
|
PLATFORMS: list[Platform] = [Platform.SENSOR]
|
||||||
|
|
||||||
# Provider configuration
|
# Provider configuration
|
||||||
CONF_API_PROVIDER: Final = "api_provider"
|
CONF_API_PROVIDER: Final = "api_provider"
|
||||||
@@ -33,21 +29,7 @@ API_PROVIDERS: Final = [
|
|||||||
API_PROVIDER_GEMINI
|
API_PROVIDER_GEMINI
|
||||||
]
|
]
|
||||||
|
|
||||||
# Read version from manifest.json
|
VERSION: Final = "2.4.0"
|
||||||
MANIFEST_PATH = os.path.join(os.path.dirname(__file__), "manifest.json")
|
|
||||||
try:
|
|
||||||
with open(MANIFEST_PATH) as manifest_file:
|
|
||||||
manifest = json.load(manifest_file)
|
|
||||||
VERSION = manifest.get("version", "unknown")
|
|
||||||
except FileNotFoundError:
|
|
||||||
VERSION = "unknown"
|
|
||||||
_LOGGER.warning("manifest.json not found at %s", MANIFEST_PATH)
|
|
||||||
except json.JSONDecodeError as err:
|
|
||||||
VERSION = "unknown"
|
|
||||||
_LOGGER.error("Error decoding JSON from manifest.json: %s", err)
|
|
||||||
except Exception as err:
|
|
||||||
VERSION = "unknown"
|
|
||||||
_LOGGER.error("Error reading manifest.json: %s", err)
|
|
||||||
|
|
||||||
# Default endpoints
|
# Default endpoints
|
||||||
DEFAULT_OPENAI_ENDPOINT: Final = "https://api.openai.com/v1"
|
DEFAULT_OPENAI_ENDPOINT: Final = "https://api.openai.com/v1"
|
||||||
@@ -61,28 +43,34 @@ CONF_TEMPERATURE: Final = "temperature"
|
|||||||
CONF_MAX_TOKENS: Final = "max_tokens"
|
CONF_MAX_TOKENS: Final = "max_tokens"
|
||||||
CONF_API_ENDPOINT: Final = "api_endpoint"
|
CONF_API_ENDPOINT: Final = "api_endpoint"
|
||||||
CONF_REQUEST_INTERVAL: Final = "request_interval"
|
CONF_REQUEST_INTERVAL: Final = "request_interval"
|
||||||
|
CONF_API_TIMEOUT: Final = "api_timeout"
|
||||||
CONF_INSTANCE: Final = "instance"
|
CONF_INSTANCE: Final = "instance"
|
||||||
CONF_MAX_HISTORY_SIZE: Final = "max_history_size" # Correct constant name
|
CONF_MAX_HISTORY_SIZE: Final = "max_history_size" # Correct constant name
|
||||||
CONF_IS_ANTHROPIC: Final = "is_anthropic"
|
|
||||||
CONF_CONTEXT_MESSAGES: Final = "context_messages"
|
CONF_CONTEXT_MESSAGES: Final = "context_messages"
|
||||||
|
CONF_STRUCTURED_OUTPUT: Final = "structured_output"
|
||||||
|
CONF_JSON_SCHEMA: Final = "json_schema"
|
||||||
|
|
||||||
ABSOLUTE_MAX_HISTORY_SIZE = 500
|
ABSOLUTE_MAX_HISTORY_SIZE: Final = 200 # Hard cap; UI allows max MAX_HISTORY_SIZE (100)
|
||||||
MAX_ATTRIBUTE_SIZE = 4 * 1024
|
MAX_ATTRIBUTE_SIZE = 4 * 1024
|
||||||
MAX_HISTORY_FILE_SIZE = 1 * 1024 * 1024
|
MAX_HISTORY_FILE_SIZE = 1 * 1024 * 1024
|
||||||
ICONS_SUBDOMAIN = "icons"
|
|
||||||
|
|
||||||
# Default values
|
# Default values
|
||||||
DEFAULT_MODEL: Final = "gpt-4o-mini"
|
DEFAULT_MODEL: Final = "gpt-4o-mini"
|
||||||
|
DEFAULT_ANTHROPIC_MODEL: Final = "claude-sonnet-4-6"
|
||||||
DEFAULT_DEEPSEEK_MODEL: Final = "deepseek-chat"
|
DEFAULT_DEEPSEEK_MODEL: Final = "deepseek-chat"
|
||||||
DEFAULT_GEMINI_MODEL: Final = "gemini-pro"
|
DEFAULT_GEMINI_MODEL: Final = "gemini-2.0-flash"
|
||||||
DEFAULT_TEMPERATURE: Final = 0.1
|
DEFAULT_TEMPERATURE: Final = 0.1
|
||||||
DEFAULT_MAX_TOKENS: Final = 1000
|
DEFAULT_MAX_TOKENS: Final = 1000
|
||||||
DEFAULT_REQUEST_INTERVAL: Final = 1.0
|
DEFAULT_REQUEST_INTERVAL: Final = 1.0
|
||||||
DEFAULT_TIMEOUT: Final = 30
|
DEFAULT_API_TIMEOUT: Final = 30
|
||||||
DEFAULT_MAX_HISTORY: Final = 50
|
DEFAULT_MAX_HISTORY: Final = 50
|
||||||
DEFAULT_NAME: Final = "HA Text AI"
|
DEFAULT_NAME: Final = "HA Text AI"
|
||||||
DEFAULT_NAME_PREFIX = "ha_text_ai"
|
DEFAULT_NAME_PREFIX = "ha_text_ai"
|
||||||
|
DEFAULT_INSTANCE_NAME: Final = "my_assistant"
|
||||||
DEFAULT_CONTEXT_MESSAGES: Final = 5
|
DEFAULT_CONTEXT_MESSAGES: Final = 5
|
||||||
|
MIN_CONTEXT_MESSAGES: Final = 1
|
||||||
|
MAX_CONTEXT_MESSAGES: Final = 20
|
||||||
|
MIN_HISTORY_SIZE: Final = 1
|
||||||
|
MAX_HISTORY_SIZE: Final = 100
|
||||||
|
|
||||||
TRUNCATION_INDICATOR = " ... "
|
TRUNCATION_INDICATOR = " ... "
|
||||||
|
|
||||||
@@ -93,9 +81,10 @@ MIN_MAX_TOKENS: Final = 1
|
|||||||
MAX_MAX_TOKENS: Final = 100000
|
MAX_MAX_TOKENS: Final = 100000
|
||||||
MIN_REQUEST_INTERVAL: Final = 0.1
|
MIN_REQUEST_INTERVAL: Final = 0.1
|
||||||
MAX_REQUEST_INTERVAL: Final = 60.0
|
MAX_REQUEST_INTERVAL: Final = 60.0
|
||||||
|
MIN_API_TIMEOUT: Final = 5
|
||||||
|
MAX_API_TIMEOUT: Final = 600
|
||||||
|
|
||||||
# API constants
|
# API constants
|
||||||
API_TIMEOUT: Final = 30
|
|
||||||
API_RETRY_COUNT: Final = 3
|
API_RETRY_COUNT: Final = 3
|
||||||
|
|
||||||
# Service names
|
# Service names
|
||||||
@@ -177,68 +166,3 @@ STATE_DISCONNECTED: Final = "disconnected"
|
|||||||
EVENT_RESPONSE_RECEIVED: Final = f"{DOMAIN}_response_received"
|
EVENT_RESPONSE_RECEIVED: Final = f"{DOMAIN}_response_received"
|
||||||
EVENT_ERROR_OCCURRED: Final = f"{DOMAIN}_error_occurred"
|
EVENT_ERROR_OCCURRED: Final = f"{DOMAIN}_error_occurred"
|
||||||
EVENT_STATE_CHANGED: Final = f"{DOMAIN}_state_changed"
|
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)
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,459 @@
|
|||||||
|
"""
|
||||||
|
History management for HA Text AI integration.
|
||||||
|
|
||||||
|
@license: PolyForm Noncommercial 1.0.0 (https://polyformproject.org/licenses/noncommercial/1.0.0)
|
||||||
|
@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, Dict, List, Optional
|
||||||
|
|
||||||
|
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()
|
||||||
|
|
||||||
|
|
||||||
|
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(
|
||||||
|
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(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(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: Optional[int] = None,
|
||||||
|
filter_model: Optional[str] = None,
|
||||||
|
start_date: Optional[str] = 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)
|
||||||
|
|
||||||
|
if limit and limit > 0:
|
||||||
|
history = history[: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
|
||||||
@@ -2,7 +2,6 @@
|
|||||||
"domain": "ha_text_ai",
|
"domain": "ha_text_ai",
|
||||||
"name": "HA Text AI",
|
"name": "HA Text AI",
|
||||||
"after_dependencies": ["http"],
|
"after_dependencies": ["http"],
|
||||||
"bluetooth": [],
|
|
||||||
"codeowners": ["@smkrv"],
|
"codeowners": ["@smkrv"],
|
||||||
"config_flow": true,
|
"config_flow": true,
|
||||||
"dependencies": [],
|
"dependencies": [],
|
||||||
@@ -11,19 +10,10 @@
|
|||||||
"iot_class": "cloud_polling",
|
"iot_class": "cloud_polling",
|
||||||
"issue_tracker": "https://github.com/smkrv/ha-text-ai/issues",
|
"issue_tracker": "https://github.com/smkrv/ha-text-ai/issues",
|
||||||
"loggers": ["custom_components.ha_text_ai"],
|
"loggers": ["custom_components.ha_text_ai"],
|
||||||
"mqtt": [],
|
"requirements": [
|
||||||
"quality_scale": "silver",
|
"aiofiles>=23.0.0",
|
||||||
"requirements": [
|
"google-genai>=1.16.0"
|
||||||
"openai>=1.12.0",
|
],
|
||||||
"anthropic>=0.8.0",
|
|
||||||
"google-generativeai>=0.3.0",
|
|
||||||
"aiohttp>=3.8.0",
|
|
||||||
"async-timeout>=4.0.0",
|
|
||||||
"certifi>=2024.2.2"
|
|
||||||
],
|
|
||||||
"single_config_entry": false,
|
"single_config_entry": false,
|
||||||
"ssdp": [],
|
"version": "2.4.0"
|
||||||
"usb": [],
|
|
||||||
"version": "2.1.6",
|
|
||||||
"zeroconf": []
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
"""
|
||||||
|
Metrics management for HA Text AI integration.
|
||||||
|
|
||||||
|
@license: PolyForm Noncommercial 1.0.0 (https://polyformproject.org/licenses/noncommercial/1.0.0)
|
||||||
|
@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, Dict
|
||||||
|
|
||||||
|
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
|
||||||
|
error_msg = re.sub(r'https?://\S+', '[URL]', error_msg)
|
||||||
|
error_msg = re.sub(r'[?&]key=[^\s&]+', '?key=***', error_msg)
|
||||||
|
error_msg = re.sub(r'AIza[A-Za-z0-9_-]+', '***', error_msg)
|
||||||
|
error_msg = re.sub(r'Bearer\s+\S+', 'Bearer ***', error_msg)
|
||||||
|
error_msg = re.sub(r'sk-[A-Za-z0-9_-]{20,}', '***', error_msg)
|
||||||
|
error_msg = re.sub(r'x-api-key:\s*\S+', '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,97 @@
|
|||||||
|
"""
|
||||||
|
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: PolyForm Noncommercial 1.0.0 (https://polyformproject.org/licenses/noncommercial/1.0.0)
|
||||||
|
@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,15 +1,16 @@
|
|||||||
"""
|
"""
|
||||||
Sensor platform for HA Text AI.
|
Sensor platform for HA Text AI.
|
||||||
|
|
||||||
@license: CC BY-NC-SA 4.0 International
|
@license: PolyForm Noncommercial 1.0.0 (https://polyformproject.org/licenses/noncommercial/1.0.0)
|
||||||
@author: SMKRV
|
@author: SMKRV
|
||||||
@github: https://github.com/smkrv/ha-text-ai
|
@github: https://github.com/smkrv/ha-text-ai
|
||||||
@source: https://github.com/smkrv/ha-text-ai
|
@source: https://github.com/smkrv/ha-text-ai
|
||||||
"""
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import math
|
import math
|
||||||
from typing import Any, Dict
|
from typing import Any, Dict
|
||||||
|
|
||||||
from homeassistant.components.sensor import (
|
from homeassistant.components.sensor import (
|
||||||
SensorEntity,
|
SensorEntity,
|
||||||
SensorEntityDescription,
|
SensorEntityDescription,
|
||||||
@@ -43,10 +44,8 @@ from .const import (
|
|||||||
ATTR_API_PROVIDER,
|
ATTR_API_PROVIDER,
|
||||||
ATTR_MODEL,
|
ATTR_MODEL,
|
||||||
ATTR_SYSTEM_PROMPT,
|
ATTR_SYSTEM_PROMPT,
|
||||||
ATTR_API_STATUS,
|
|
||||||
ATTR_RESPONSE,
|
ATTR_RESPONSE,
|
||||||
ATTR_QUESTION,
|
ATTR_QUESTION,
|
||||||
ATTR_CONVERSATION_HISTORY,
|
|
||||||
METRIC_TOTAL_TOKENS,
|
METRIC_TOTAL_TOKENS,
|
||||||
METRIC_PROMPT_TOKENS,
|
METRIC_PROMPT_TOKENS,
|
||||||
METRIC_COMPLETION_TOKENS,
|
METRIC_COMPLETION_TOKENS,
|
||||||
@@ -67,14 +66,19 @@ from .const import (
|
|||||||
ENTITY_ICON_PROCESSING,
|
ENTITY_ICON_PROCESSING,
|
||||||
DEFAULT_NAME_PREFIX,
|
DEFAULT_NAME_PREFIX,
|
||||||
CONF_MAX_HISTORY_SIZE,
|
CONF_MAX_HISTORY_SIZE,
|
||||||
MAX_ATTRIBUTE_SIZE,
|
|
||||||
VERSION,
|
VERSION,
|
||||||
)
|
)
|
||||||
|
|
||||||
from .coordinator import HATextAICoordinator
|
from .coordinator import HATextAICoordinator
|
||||||
|
from .utils import safe_log_data
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_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(
|
async def async_setup_entry(
|
||||||
hass: HomeAssistant,
|
hass: HomeAssistant,
|
||||||
@@ -82,23 +86,23 @@ async def async_setup_entry(
|
|||||||
async_add_entities: AddEntitiesCallback,
|
async_add_entities: AddEntitiesCallback,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Set up the HA Text AI sensor."""
|
"""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:
|
try:
|
||||||
coordinator = hass.data[DOMAIN][entry.entry_id]
|
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
|
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)
|
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)
|
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:
|
except Exception as err:
|
||||||
_LOGGER.exception(f"Error setting up sensor: {err}")
|
_LOGGER.exception("Error setting up sensor: %s", err)
|
||||||
raise
|
raise
|
||||||
|
|
||||||
class HATextAISensor(CoordinatorEntity, SensorEntity):
|
class HATextAISensor(CoordinatorEntity, SensorEntity):
|
||||||
@@ -112,7 +116,7 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
|||||||
config_entry: ConfigEntry,
|
config_entry: ConfigEntry,
|
||||||
) -> None:
|
) -> None:
|
||||||
"""Initialize the sensor."""
|
"""Initialize the sensor."""
|
||||||
_LOGGER.debug(f"Initializing sensor with config entry: {config_entry.data}")
|
_LOGGER.debug("Initializing sensor with config entry: %s", safe_log_data(dict(config_entry.data)))
|
||||||
|
|
||||||
super().__init__(coordinator)
|
super().__init__(coordinator)
|
||||||
|
|
||||||
@@ -120,19 +124,20 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
|||||||
self._instance_name = coordinator.instance_name
|
self._instance_name = coordinator.instance_name
|
||||||
self._normalized_name = coordinator.normalized_name
|
self._normalized_name = coordinator.normalized_name
|
||||||
|
|
||||||
_LOGGER.debug(f"Instance name: {self._instance_name}")
|
_LOGGER.debug("Instance name: %s", self._instance_name)
|
||||||
_LOGGER.debug(f"Normalized name: {self._normalized_name}")
|
_LOGGER.debug("Normalized name: %s", self._normalized_name)
|
||||||
|
|
||||||
self._conversation_history = []
|
self._conversation_history = []
|
||||||
self._system_prompt = None
|
self._system_prompt = None
|
||||||
|
|
||||||
self._attr_name = f"HA Text AI {self._instance_name}"
|
self._attr_has_entity_name = True
|
||||||
|
self._attr_name = self._instance_name
|
||||||
self.entity_id = f"sensor.ha_text_ai_{self._normalized_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("Created sensor with entity_id: %s", self.entity_id)
|
||||||
_LOGGER.debug(f"Sensor name: {self._attr_name}")
|
_LOGGER.debug("Sensor name: %s", self._attr_name)
|
||||||
_LOGGER.debug(f"Unique ID: {self._attr_unique_id}")
|
_LOGGER.debug("Unique ID: %s", self._attr_unique_id)
|
||||||
|
|
||||||
self.entity_description = SensorEntityDescription(
|
self.entity_description = SensorEntityDescription(
|
||||||
key=f"ha_text_ai_{self._normalized_name.lower()}",
|
key=f"ha_text_ai_{self._normalized_name.lower()}",
|
||||||
@@ -159,7 +164,8 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
|||||||
)
|
)
|
||||||
|
|
||||||
_LOGGER.debug(
|
_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
|
@property
|
||||||
@@ -199,7 +205,7 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
|||||||
]
|
]
|
||||||
|
|
||||||
metrics_values = {k: sanitized.get(k) for k in metrics_keys if k in sanitized}
|
metrics_values = {k: sanitized.get(k) for k in metrics_keys if k in sanitized}
|
||||||
_LOGGER.debug(f"Metrics for {self.entity_id}: {metrics_values}")
|
_LOGGER.debug("Metrics for %s: %s", self.entity_id, metrics_values)
|
||||||
|
|
||||||
return sanitized
|
return sanitized
|
||||||
|
|
||||||
@@ -237,11 +243,10 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
|||||||
attributes = {
|
attributes = {
|
||||||
ATTR_MODEL: self._config_entry.data.get(CONF_MODEL, "Unknown"),
|
ATTR_MODEL: self._config_entry.data.get(CONF_MODEL, "Unknown"),
|
||||||
ATTR_API_PROVIDER: self._config_entry.data.get(CONF_API_PROVIDER, "Unknown"),
|
ATTR_API_PROVIDER: self._config_entry.data.get(CONF_API_PROVIDER, "Unknown"),
|
||||||
ATTR_API_STATUS: self._current_state,
|
|
||||||
ATTR_TOTAL_ERRORS: metrics.get("total_errors", 0),
|
ATTR_TOTAL_ERRORS: metrics.get("total_errors", 0),
|
||||||
"instance_name": self._instance_name,
|
"instance_name": self._instance_name,
|
||||||
"normalized_name": self._normalized_name,
|
"normalized_name": self._normalized_name,
|
||||||
ATTR_SYSTEM_PROMPT: (data.get("system_prompt", "")[:MAX_ATTRIBUTE_SIZE]
|
ATTR_SYSTEM_PROMPT: (data.get("system_prompt", "")[:_ATTR_PROMPT_LIMIT]
|
||||||
if data.get("system_prompt") else None),
|
if data.get("system_prompt") else None),
|
||||||
ATTR_IS_PROCESSING: data.get("is_processing", False),
|
ATTR_IS_PROCESSING: data.get("is_processing", False),
|
||||||
ATTR_IS_RATE_LIMITED: data.get("is_rate_limited", False),
|
ATTR_IS_RATE_LIMITED: data.get("is_rate_limited", False),
|
||||||
@@ -251,18 +256,19 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
|||||||
ATTR_HISTORY_SIZE: data.get("history_size", 0),
|
ATTR_HISTORY_SIZE: data.get("history_size", 0),
|
||||||
}
|
}
|
||||||
|
|
||||||
# History limit
|
# 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", [])
|
conversation_history = data.get("conversation_history", [])
|
||||||
if conversation_history:
|
if conversation_history:
|
||||||
limited_history = []
|
preview = conversation_history[-3:]
|
||||||
for entry in conversation_history:
|
attributes["conversation_history"] = [
|
||||||
limited_entry = {
|
{
|
||||||
"timestamp": entry["timestamp"],
|
"timestamp": entry["timestamp"],
|
||||||
"question": entry["question"][:MAX_ATTRIBUTE_SIZE],
|
"question": entry["question"][:256],
|
||||||
"response": entry["response"][:MAX_ATTRIBUTE_SIZE]
|
"response": entry["response"][:256],
|
||||||
}
|
}
|
||||||
limited_history.append(limited_entry)
|
for entry in preview
|
||||||
attributes[ATTR_CONVERSATION_HISTORY] = limited_history
|
]
|
||||||
|
|
||||||
# Metrics
|
# Metrics
|
||||||
if isinstance(metrics, dict):
|
if isinstance(metrics, dict):
|
||||||
@@ -274,20 +280,18 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
|||||||
METRIC_FAILED_REQUESTS: metrics.get("failed_requests", 0),
|
METRIC_FAILED_REQUESTS: metrics.get("failed_requests", 0),
|
||||||
METRIC_AVERAGE_LATENCY: round(metrics.get("average_latency", 0), 2),
|
METRIC_AVERAGE_LATENCY: round(metrics.get("average_latency", 0), 2),
|
||||||
METRIC_MAX_LATENCY: round(metrics.get("max_latency", 0), 2),
|
METRIC_MAX_LATENCY: round(metrics.get("max_latency", 0), 2),
|
||||||
METRIC_MIN_LATENCY: (metrics.get("min_latency")
|
METRIC_MIN_LATENCY: metrics.get("min_latency", 0) or None,
|
||||||
if metrics.get("min_latency") != float("inf")
|
|
||||||
else None),
|
|
||||||
})
|
})
|
||||||
|
|
||||||
# Last response handling
|
# Last response handling
|
||||||
last_response = data.get("last_response", {})
|
last_response = data.get("last_response", {})
|
||||||
if isinstance(last_response, dict):
|
if isinstance(last_response, dict):
|
||||||
attributes.update({
|
attributes.update({
|
||||||
ATTR_RESPONSE: last_response.get("response", "")[:MAX_ATTRIBUTE_SIZE],
|
ATTR_RESPONSE: last_response.get("response", "")[:_ATTR_TEXT_LIMIT],
|
||||||
ATTR_QUESTION: last_response.get("question", "")[:MAX_ATTRIBUTE_SIZE],
|
ATTR_QUESTION: last_response.get("question", "")[:_ATTR_TEXT_LIMIT],
|
||||||
"last_model": last_response.get("model", ""),
|
"last_model": last_response.get("model", ""),
|
||||||
"last_timestamp": last_response.get("timestamp", ""),
|
"last_timestamp": last_response.get("timestamp", ""),
|
||||||
"last_error": (last_response.get("error", "")[:MAX_ATTRIBUTE_SIZE]
|
"last_error": (last_response.get("error", "")[:_ATTR_TEXT_LIMIT]
|
||||||
if last_response.get("error") else None),
|
if last_response.get("error") else None),
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -301,7 +305,7 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
|||||||
"""When entity is added to hass."""
|
"""When entity is added to hass."""
|
||||||
await super().async_added_to_hass()
|
await super().async_added_to_hass()
|
||||||
self._handle_coordinator_update()
|
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:
|
def _handle_coordinator_update(self) -> None:
|
||||||
"""Handle updated data from the coordinator."""
|
"""Handle updated data from the coordinator."""
|
||||||
@@ -309,7 +313,7 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
|||||||
data = self.coordinator.data
|
data = self.coordinator.data
|
||||||
if not self.coordinator.last_update_success or not data:
|
if not self.coordinator.last_update_success or not data:
|
||||||
self._current_state = STATE_DISCONNECTED
|
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()
|
self.async_write_ha_state()
|
||||||
return
|
return
|
||||||
|
|
||||||
@@ -319,7 +323,7 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
|||||||
metrics = data.get("metrics", {})
|
metrics = data.get("metrics", {})
|
||||||
if isinstance(metrics, dict):
|
if isinstance(metrics, dict):
|
||||||
self._metrics.update(metrics)
|
self._metrics.update(metrics)
|
||||||
_LOGGER.debug(f"Updated metrics for {self.entity_id}: {self._metrics}")
|
_LOGGER.debug("Updated metrics for %s: %s", self.entity_id, self._metrics)
|
||||||
|
|
||||||
# Update conversation history and system prompt
|
# Update conversation history and system prompt
|
||||||
self._conversation_history = data.get("conversation_history", [])
|
self._conversation_history = data.get("conversation_history", [])
|
||||||
@@ -343,8 +347,8 @@ class HATextAISensor(CoordinatorEntity, SensorEntity):
|
|||||||
self._last_update = dt_util.utcnow()
|
self._last_update = dt_util.utcnow()
|
||||||
|
|
||||||
_LOGGER.debug(
|
_LOGGER.debug(
|
||||||
f"Updated {self.entity_id} state to: {self._current_state} "
|
"Updated %s state to: %s (available: %s)",
|
||||||
f"(available: {self.available})"
|
self.entity_id, self._current_state, self.available,
|
||||||
)
|
)
|
||||||
|
|
||||||
except Exception as err:
|
except Exception as err:
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ ask_question:
|
|||||||
description: >-
|
description: >-
|
||||||
Send a question to the AI model and receive a detailed response.
|
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.
|
The response will be stored in the conversation history and can be retrieved later.
|
||||||
|
This service now returns response data directly, eliminating the need to read from sensors.
|
||||||
fields:
|
fields:
|
||||||
instance:
|
instance:
|
||||||
name: Instance
|
name: Instance
|
||||||
@@ -73,6 +74,24 @@ ask_question:
|
|||||||
step: 1
|
step: 1
|
||||||
mode: box
|
mode: box
|
||||||
|
|
||||||
|
structured_output:
|
||||||
|
name: Structured Output
|
||||||
|
description: Enable JSON structured output mode. When enabled, the AI will respond with valid JSON matching the provided schema.
|
||||||
|
required: false
|
||||||
|
default: false
|
||||||
|
selector:
|
||||||
|
boolean: {}
|
||||||
|
|
||||||
|
json_schema:
|
||||||
|
name: JSON Schema
|
||||||
|
description: >-
|
||||||
|
JSON Schema defining the structure of the expected response.
|
||||||
|
Required when structured_output is enabled.
|
||||||
|
required: false
|
||||||
|
selector:
|
||||||
|
text:
|
||||||
|
multiline: true
|
||||||
|
|
||||||
clear_history:
|
clear_history:
|
||||||
name: Clear History
|
name: Clear History
|
||||||
description: >-
|
description: >-
|
||||||
@@ -134,7 +153,7 @@ get_history:
|
|||||||
required: false
|
required: false
|
||||||
default: false
|
default: false
|
||||||
selector:
|
selector:
|
||||||
boolean:
|
boolean: {}
|
||||||
|
|
||||||
sort_order:
|
sort_order:
|
||||||
name: Sort Order
|
name: Sort Order
|
||||||
|
|||||||
@@ -0,0 +1,326 @@
|
|||||||
|
{
|
||||||
|
"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)"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"user": {
|
||||||
|
"title": "Configure HA Text AI Instance",
|
||||||
|
"description": "Set up a new AI assistant instance with your selected provider.",
|
||||||
|
"data": {
|
||||||
|
"name": "Instance name (e.g., 'GPT Assistant', 'Claude Helper')",
|
||||||
|
"api_key": "API key for authentication",
|
||||||
|
"model": "AI model to use",
|
||||||
|
"temperature": "Response creativity (0-2, lower = more focused)",
|
||||||
|
"max_tokens": "Maximum response length (1-100000 tokens)",
|
||||||
|
"api_endpoint": "Custom API endpoint URL (optional)",
|
||||||
|
"api_provider": "API Provider",
|
||||||
|
"request_interval": "Minimum time between requests (0.1-60 seconds)",
|
||||||
|
"api_timeout": "API request timeout in seconds (5-600)",
|
||||||
|
"context_messages": "Number of context messages to retain (1-20)",
|
||||||
|
"max_history_size": "Maximum conversation history size (1-100)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"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)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"selector": {
|
||||||
|
"api_provider": {
|
||||||
|
"options": {
|
||||||
|
"openai": "OpenAI (compatible)",
|
||||||
|
"anthropic": "Anthropic (compatible)",
|
||||||
|
"deepseek": "DeepSeek",
|
||||||
|
"gemini": "Google Gemini"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"services": {
|
||||||
|
"ask_question": {
|
||||||
|
"name": "Ask Question (HA Text AI)",
|
||||||
|
"description": "Send a question to the AI model and receive a detailed response. This service now returns response data directly, eliminating the need for separate text sensors and the 255-character limitation. The response will also be stored in the conversation history.",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Instance",
|
||||||
|
"description": "Name of the HA Text AI instance to use"
|
||||||
|
},
|
||||||
|
"question": {
|
||||||
|
"name": "Question",
|
||||||
|
"description": "Your question or prompt for the AI assistant"
|
||||||
|
},
|
||||||
|
"context_messages": {
|
||||||
|
"name": "Context Messages",
|
||||||
|
"description": "Number of previous messages to include in context (1-20)"
|
||||||
|
},
|
||||||
|
"system_prompt": {
|
||||||
|
"name": "System Prompt",
|
||||||
|
"description": "Optional system prompt to set context for this specific question"
|
||||||
|
},
|
||||||
|
"model": {
|
||||||
|
"name": "Model",
|
||||||
|
"description": "Select AI model to use (optional, overrides default setting)"
|
||||||
|
},
|
||||||
|
"temperature": {
|
||||||
|
"name": "Temperature",
|
||||||
|
"description": "Controls response creativity (0.0-2.0)"
|
||||||
|
},
|
||||||
|
"max_tokens": {
|
||||||
|
"name": "Max Tokens",
|
||||||
|
"description": "Maximum length of the response (1-100000 tokens)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Structured Output",
|
||||||
|
"description": "Enable JSON structured output mode. When enabled, the AI will respond with valid JSON matching the provided schema."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON Schema",
|
||||||
|
"description": "JSON Schema defining the structure of the expected response. Required when structured_output is enabled."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"clear_history": {
|
||||||
|
"name": "Clear History",
|
||||||
|
"description": "Delete all stored questions and responses from the conversation history",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Instance",
|
||||||
|
"description": "Name of the HA Text AI instance to clear history for"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"get_history": {
|
||||||
|
"name": "Get History",
|
||||||
|
"description": "Retrieve conversation history with optional filtering and sorting",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Instance",
|
||||||
|
"description": "Name of the HA Text AI instance to get history from"
|
||||||
|
},
|
||||||
|
"limit": {
|
||||||
|
"name": "Limit",
|
||||||
|
"description": "Number of conversations to return (1-100)"
|
||||||
|
},
|
||||||
|
"filter_model": {
|
||||||
|
"name": "Filter Model",
|
||||||
|
"description": "Filter conversations by specific AI model"
|
||||||
|
},
|
||||||
|
"start_date": {
|
||||||
|
"name": "Start Date",
|
||||||
|
"description": "Filter conversations starting from this date/time"
|
||||||
|
},
|
||||||
|
"include_metadata": {
|
||||||
|
"name": "Include Metadata",
|
||||||
|
"description": "Include additional information like tokens used, response time, etc."
|
||||||
|
},
|
||||||
|
"sort_order": {
|
||||||
|
"name": "Sort Order",
|
||||||
|
"description": "Sort order for results (newest or oldest first)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"set_system_prompt": {
|
||||||
|
"name": "Set System Prompt",
|
||||||
|
"description": "Set default system behavior instructions for all future conversations",
|
||||||
|
"fields": {
|
||||||
|
"instance": {
|
||||||
|
"name": "Instance",
|
||||||
|
"description": "Name of the HA Text AI instance to set system prompt for"
|
||||||
|
},
|
||||||
|
"prompt": {
|
||||||
|
"name": "System Prompt",
|
||||||
|
"description": "Instructions that define how the AI should behave and respond"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"entity": {
|
||||||
|
"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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,15 +1,6 @@
|
|||||||
{
|
{
|
||||||
"config": {
|
"config": {
|
||||||
"step": {
|
"step": {
|
||||||
"provider": {
|
|
||||||
"title": "Wählen Sie AI-Anbieter",
|
|
||||||
"description": "Wählen Sie, welchen AI-Dienstanbieter Sie für diese Instanz verwenden möchten.",
|
|
||||||
"data": {
|
|
||||||
"api_provider": "API-Anbieter",
|
|
||||||
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
|
|
||||||
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"provider": {
|
"provider": {
|
||||||
"title": "Anbieter-Einstellungen",
|
"title": "Anbieter-Einstellungen",
|
||||||
"description": "Geben Sie die Verbindungsdetails für Ihren gewählten AI-Anbieter an.",
|
"description": "Geben Sie die Verbindungsdetails für Ihren gewählten AI-Anbieter an.",
|
||||||
@@ -21,6 +12,7 @@
|
|||||||
"temperature": "Kreativität der Antwort (0-2, niedriger = fokussierter)",
|
"temperature": "Kreativität der Antwort (0-2, niedriger = fokussierter)",
|
||||||
"max_tokens": "Maximale Länge der Antwort (1-100000 Token)",
|
"max_tokens": "Maximale Länge der Antwort (1-100000 Token)",
|
||||||
"request_interval": "Minimale Zeit 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)",
|
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
|
||||||
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
||||||
}
|
}
|
||||||
@@ -37,6 +29,7 @@
|
|||||||
"api_endpoint": "Benutzerdefinierte API-Endpunkt-URL (optional)",
|
"api_endpoint": "Benutzerdefinierte API-Endpunkt-URL (optional)",
|
||||||
"api_provider": "API-Anbieter",
|
"api_provider": "API-Anbieter",
|
||||||
"request_interval": "Minimale Zeit 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)",
|
"context_messages": "Anzahl der zu behaltenden Kontextnachrichten (1-20)",
|
||||||
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
||||||
}
|
}
|
||||||
@@ -72,13 +65,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "Instanzeinstellungen aktualisieren",
|
"title": "Anbieter auswählen",
|
||||||
"description": "Ändern Sie die Einstellungen für diese AI-Assistenteninstanz.",
|
"description": "Wählen Sie den AI-Anbieter für diese Instanz. Die Integration wird nach dem Speichern der Änderungen neu geladen.",
|
||||||
"data": {
|
"data": {
|
||||||
|
"api_provider": "API-Anbieter"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Verbindungs- und Modelleinstellungen",
|
||||||
|
"description": "Konfigurieren Sie API-Anmeldeinformationen und Modellparameter. Änderungen werden nach dem Neuladen der Integration wirksam.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API-Schlüssel",
|
||||||
|
"api_endpoint": "API-Endpunkt-URL",
|
||||||
"model": "AI-Modell",
|
"model": "AI-Modell",
|
||||||
"temperature": "Kreativität der Antwort (0-2)",
|
"temperature": "Kreativität der Antwort (0-2)",
|
||||||
"max_tokens": "Maximale Länge der Antwort (1-100000)",
|
"max_tokens": "Maximale Länge der Antwort (1-100000)",
|
||||||
"request_interval": "Minimale Anfrageintervall (0,1-60 Sekunden)",
|
"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)",
|
"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)"
|
"max_history_size": "Maximale Größe des Gesprächsverlaufs (1-100)"
|
||||||
}
|
}
|
||||||
@@ -92,13 +95,13 @@
|
|||||||
"anthropic": "Anthropic (compatible)",
|
"anthropic": "Anthropic (compatible)",
|
||||||
"deepseek": "DeepSeek",
|
"deepseek": "DeepSeek",
|
||||||
"gemini": "Google Gemini"
|
"gemini": "Google Gemini"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
},
|
|
||||||
"services": {
|
"services": {
|
||||||
"ask_question": {
|
"ask_question": {
|
||||||
"name": "Frage stellen (HA Text AI)",
|
"name": "Frage stellen (HA Text AI)",
|
||||||
"description": "Stellen Sie eine Frage an das AI-Modell und erhalten Sie eine detaillierte Antwort. Die Antwort wird im Gesprächsverlauf gespeichert und kann später abgerufen werden.",
|
"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": {
|
"fields": {
|
||||||
"instance": {
|
"instance": {
|
||||||
"name": "Instanz",
|
"name": "Instanz",
|
||||||
@@ -127,6 +130,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "Max Tokens",
|
"name": "Max Tokens",
|
||||||
"description": "Maximale Länge der Antwort (1-100000 Token)"
|
"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."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,15 +1,6 @@
|
|||||||
{
|
{
|
||||||
"config": {
|
"config": {
|
||||||
"step": {
|
"step": {
|
||||||
"provider": {
|
|
||||||
"title": "Select AI Provider",
|
|
||||||
"description": "Choose which AI service provider to use for this instance.",
|
|
||||||
"data": {
|
|
||||||
"api_provider": "API Provider",
|
|
||||||
"context_messages": "Number of context messages to retain (1-20)",
|
|
||||||
"max_history_size": "Maximum conversation history size (1-100)"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"provider": {
|
"provider": {
|
||||||
"title": "Provider Settings",
|
"title": "Provider Settings",
|
||||||
"description": "Provide connection details for your chosen AI provider.",
|
"description": "Provide connection details for your chosen AI provider.",
|
||||||
@@ -21,6 +12,7 @@
|
|||||||
"temperature": "Response creativity (0-2, lower = more focused)",
|
"temperature": "Response creativity (0-2, lower = more focused)",
|
||||||
"max_tokens": "Maximum response length (1-100000 tokens)",
|
"max_tokens": "Maximum response length (1-100000 tokens)",
|
||||||
"request_interval": "Minimum time between requests (0.1-60 seconds)",
|
"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)",
|
"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)"
|
||||||
}
|
}
|
||||||
@@ -37,6 +29,7 @@
|
|||||||
"api_endpoint": "Custom API endpoint URL (optional)",
|
"api_endpoint": "Custom API endpoint URL (optional)",
|
||||||
"api_provider": "API Provider",
|
"api_provider": "API Provider",
|
||||||
"request_interval": "Minimum time between requests (0.1-60 seconds)",
|
"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)",
|
"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)"
|
||||||
}
|
}
|
||||||
@@ -49,6 +42,7 @@
|
|||||||
"name_exists": "An instance with this name already exists",
|
"name_exists": "An instance with this name already exists",
|
||||||
"invalid_name": "Invalid instance name",
|
"invalid_name": "Invalid instance name",
|
||||||
"invalid_auth": "Authentication failed - check your API key",
|
"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",
|
"invalid_api_key": "Invalid API key - please verify your credentials",
|
||||||
"cannot_connect": "Failed to connect to API service",
|
"cannot_connect": "Failed to connect to API service",
|
||||||
"invalid_model": "Selected model is not available",
|
"invalid_model": "Selected model is not available",
|
||||||
@@ -62,7 +56,6 @@
|
|||||||
"invalid_instance": "Invalid instance specified",
|
"invalid_instance": "Invalid instance specified",
|
||||||
"unknown": "Unexpected error occurred",
|
"unknown": "Unexpected error occurred",
|
||||||
"empty": "Name cannot be empty",
|
"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"
|
"name_too_long": "Name must be 50 characters or less"
|
||||||
},
|
},
|
||||||
"abort": {
|
"abort": {
|
||||||
@@ -72,13 +65,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "Update Instance Settings",
|
"title": "Select Provider",
|
||||||
"description": "Modify settings for this AI assistant instance.",
|
"description": "Choose the AI provider for this instance. The integration will reload after saving changes.",
|
||||||
"data": {
|
"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",
|
"model": "AI model",
|
||||||
"temperature": "Response creativity (0-2)",
|
"temperature": "Response creativity (0-2)",
|
||||||
"max_tokens": "Maximum response length (1-100000)",
|
"max_tokens": "Maximum response length (1-100000)",
|
||||||
"request_interval": "Minimum request interval (0.1-60 seconds)",
|
"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)",
|
"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)"
|
||||||
}
|
}
|
||||||
@@ -92,13 +95,13 @@
|
|||||||
"anthropic": "Anthropic (compatible)",
|
"anthropic": "Anthropic (compatible)",
|
||||||
"deepseek": "DeepSeek",
|
"deepseek": "DeepSeek",
|
||||||
"gemini": "Google Gemini"
|
"gemini": "Google Gemini"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
},
|
|
||||||
"services": {
|
"services": {
|
||||||
"ask_question": {
|
"ask_question": {
|
||||||
"name": "Ask Question (HA Text AI)",
|
"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": {
|
"fields": {
|
||||||
"instance": {
|
"instance": {
|
||||||
"name": "Instance",
|
"name": "Instance",
|
||||||
@@ -127,6 +130,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "Max Tokens",
|
"name": "Max Tokens",
|
||||||
"description": "Maximum length of the response (1-100000 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."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -197,8 +208,7 @@
|
|||||||
"rate_limited": "Rate Limited",
|
"rate_limited": "Rate Limited",
|
||||||
"maintenance": "Maintenance",
|
"maintenance": "Maintenance",
|
||||||
"initializing": "Initializing",
|
"initializing": "Initializing",
|
||||||
"retrying": "Retrying",
|
"retrying": "Retrying"
|
||||||
"queued": "Queued"
|
|
||||||
},
|
},
|
||||||
"state_attributes": {
|
"state_attributes": {
|
||||||
"question": {
|
"question": {
|
||||||
@@ -290,6 +300,24 @@
|
|||||||
},
|
},
|
||||||
"min_latency": {
|
"min_latency": {
|
||||||
"name": "Minimum 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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,6 @@
|
|||||||
{
|
{
|
||||||
"config": {
|
"config": {
|
||||||
"step": {
|
"step": {
|
||||||
"provider": {
|
|
||||||
"title": "Seleccionar proveedor de IA",
|
|
||||||
"description": "Elige qué proveedor de servicio de IA utilizar para esta instancia.",
|
|
||||||
"data": {
|
|
||||||
"api_provider": "Proveedor de API",
|
|
||||||
"context_messages": "Número de mensajes de contexto a retener (1-20)",
|
|
||||||
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"provider": {
|
"provider": {
|
||||||
"title": "Configuración del proveedor",
|
"title": "Configuración del proveedor",
|
||||||
"description": "Proporciona los detalles de conexión para tu proveedor de IA elegido.",
|
"description": "Proporciona los detalles de conexión para tu proveedor de IA elegido.",
|
||||||
@@ -21,6 +12,7 @@
|
|||||||
"temperature": "Creatividad de la respuesta (0-2, menor = más enfocado)",
|
"temperature": "Creatividad de la respuesta (0-2, menor = más enfocado)",
|
||||||
"max_tokens": "Longitud máxima de la respuesta (1-100000 tokens)",
|
"max_tokens": "Longitud máxima de la respuesta (1-100000 tokens)",
|
||||||
"request_interval": "Tiempo mínimo entre solicitudes (0.1-60 segundos)",
|
"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)",
|
"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)"
|
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||||
}
|
}
|
||||||
@@ -37,6 +29,7 @@
|
|||||||
"api_endpoint": "URL del endpoint de API personalizado (opcional)",
|
"api_endpoint": "URL del endpoint de API personalizado (opcional)",
|
||||||
"api_provider": "Proveedor de API",
|
"api_provider": "Proveedor de API",
|
||||||
"request_interval": "Tiempo mínimo entre solicitudes (0.1-60 segundos)",
|
"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)",
|
"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)"
|
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||||
}
|
}
|
||||||
@@ -72,13 +65,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "Actualizar configuración de la instancia",
|
"title": "Seleccionar proveedor",
|
||||||
"description": "Modifica la configuración para esta instancia de asistente de IA.",
|
"description": "Elige el proveedor de IA para esta instancia. La integración se recargará después de guardar los cambios.",
|
||||||
"data": {
|
"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",
|
"model": "Modelo de IA",
|
||||||
"temperature": "Creatividad de la respuesta (0-2)",
|
"temperature": "Creatividad de la respuesta (0-2)",
|
||||||
"max_tokens": "Longitud máxima de la respuesta (1-100000)",
|
"max_tokens": "Longitud máxima de la respuesta (1-100000)",
|
||||||
"request_interval": "Intervalo mínimo de solicitud (0.1-60 segundos)",
|
"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)",
|
"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)"
|
"max_history_size": "Tamaño máximo del historial de conversación (1-100)"
|
||||||
}
|
}
|
||||||
@@ -92,13 +95,13 @@
|
|||||||
"anthropic": "Anthropic (compatible)",
|
"anthropic": "Anthropic (compatible)",
|
||||||
"deepseek": "DeepSeek",
|
"deepseek": "DeepSeek",
|
||||||
"gemini": "Google Gemini"
|
"gemini": "Google Gemini"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
},
|
|
||||||
"services": {
|
"services": {
|
||||||
"ask_question": {
|
"ask_question": {
|
||||||
"name": "Hacer Pregunta (HA Text AI)",
|
"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.",
|
"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": {
|
"fields": {
|
||||||
"instance": {
|
"instance": {
|
||||||
"name": "Instancia",
|
"name": "Instancia",
|
||||||
@@ -127,6 +130,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "Máx. Tokens",
|
"name": "Máx. Tokens",
|
||||||
"description": "Longitud máxima de la respuesta (1-100000 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."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,15 +1,6 @@
|
|||||||
{
|
{
|
||||||
"config": {
|
"config": {
|
||||||
"step": {
|
"step": {
|
||||||
"provider": {
|
|
||||||
"title": "एआई प्रदाता चुनें",
|
|
||||||
"description": "इस उदाहरण के लिए किस एआई सेवा प्रदाता का उपयोग करना है, चुनें।",
|
|
||||||
"data": {
|
|
||||||
"api_provider": "एपीआई प्रदाता",
|
|
||||||
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
|
||||||
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"provider": {
|
"provider": {
|
||||||
"title": "प्रदाता सेटिंग्स",
|
"title": "प्रदाता सेटिंग्स",
|
||||||
"description": "आपके द्वारा चुने गए एआई प्रदाता के लिए कनेक्शन विवरण प्रदान करें।",
|
"description": "आपके द्वारा चुने गए एआई प्रदाता के लिए कनेक्शन विवरण प्रदान करें।",
|
||||||
@@ -21,6 +12,7 @@
|
|||||||
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)",
|
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2, कम = अधिक केंद्रित)",
|
||||||
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)",
|
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)",
|
||||||
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
|
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
|
||||||
|
"api_timeout": "एपीआई अनुरोध टाइमआउट सेकंड में (5-600)",
|
||||||
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
||||||
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
||||||
}
|
}
|
||||||
@@ -37,6 +29,7 @@
|
|||||||
"api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)",
|
"api_endpoint": "कस्टम एपीआई एंडपॉइंट यूआरएल (वैकल्पिक)",
|
||||||
"api_provider": "एपीआई प्रदाता",
|
"api_provider": "एपीआई प्रदाता",
|
||||||
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
|
"request_interval": "अनुरोधों के बीच न्यूनतम समय (0.1-60 सेकंड)",
|
||||||
|
"api_timeout": "एपीआई अनुरोध टाइमआउट सेकंड में (5-600)",
|
||||||
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
"context_messages": "रखने के लिए संदर्भ संदेशों की संख्या (1-20)",
|
||||||
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
||||||
}
|
}
|
||||||
@@ -72,13 +65,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "उदाहरण सेटिंग्स अपडेट करें",
|
"title": "प्रदाता चुनें",
|
||||||
"description": "इस एआई सहायक उदाहरण के लिए सेटिंग्स संशोधित करें।",
|
"description": "इस उदाहरण के लिए एआई प्रदाता चुनें। परिवर्तन सहेजने के बाद एकीकरण पुनः लोड होगा।",
|
||||||
"data": {
|
"data": {
|
||||||
|
"api_provider": "एपीआई प्रदाता"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "कनेक्शन और मॉडल सेटिंग्स",
|
||||||
|
"description": "एपीआई क्रेडेंशियल और मॉडल पैरामीटर कॉन्फ़िगर करें। एकीकरण पुनः लोड होने के बाद परिवर्तन प्रभावी होंगे।",
|
||||||
|
"data": {
|
||||||
|
"api_key": "एपीआई कुंजी",
|
||||||
|
"api_endpoint": "एपीआई एंडपॉइंट यूआरएल",
|
||||||
"model": "एआई मॉडल",
|
"model": "एआई मॉडल",
|
||||||
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2)",
|
"temperature": "प्रतिक्रिया की रचनात्मकता (0-2)",
|
||||||
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000)",
|
"max_tokens": "प्रतिक्रिया की अधिकतम लंबाई (1-100000)",
|
||||||
"request_interval": "न्यूनतम अनुरोध अंतराल (0.1-60 सेकंड)",
|
"request_interval": "न्यूनतम अनुरोध अंतराल (0.1-60 सेकंड)",
|
||||||
|
"api_timeout": "एपीआई अनुरोध टाइमआउट सेकंड में (5-600)",
|
||||||
"context_messages": "संदर्भ में शामिल करने के लिए पिछले संदेशों की संख्या (1-20)",
|
"context_messages": "संदर्भ में शामिल करने के लिए पिछले संदेशों की संख्या (1-20)",
|
||||||
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
"max_history_size": "अधिकतम बातचीत इतिहास आकार (1-100)"
|
||||||
}
|
}
|
||||||
@@ -98,7 +101,7 @@
|
|||||||
"services": {
|
"services": {
|
||||||
"ask_question": {
|
"ask_question": {
|
||||||
"name": "प्रश्न पूछें (HA Text AI)",
|
"name": "प्रश्न पूछें (HA Text AI)",
|
||||||
"description": "एआई मॉडल को एक प्रश्न भेजें और विस्तृत प्रतिक्रिया प्राप्त करें। प्रतिक्रिया बातचीत के इतिहास में संग्रहीत की जाएगी और बाद में पुनर्प्राप्त की जा सकती है।",
|
"description": "AI मॉडल को प्रश्न भेजें और विस्तृत उत्तर प्राप्त करें। यह सेवा अब प्रत्यक्ष रूप से प्रतिक्रिया डेटा वापस करती है, अलग टेक्स्ट सेंसर की आवश्यकता और 255 वर्ण की सीमा को समाप्त करती है। प्रतिक्रिया को बातचीत के इतिहास में भी संग्रहीत किया जाएगा।",
|
||||||
"fields": {
|
"fields": {
|
||||||
"instance": {
|
"instance": {
|
||||||
"name": "उदाहरण",
|
"name": "उदाहरण",
|
||||||
@@ -127,6 +130,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "अधिकतम टोकन",
|
"name": "अधिकतम टोकन",
|
||||||
"description": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)"
|
"description": "प्रतिक्रिया की अधिकतम लंबाई (1-100000 टोकन)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "संरचित आउटपुट",
|
||||||
|
"description": "JSON संरचित आउटपुट मोड सक्षम करें। सक्षम होने पर, AI प्रदान किए गए स्कीमा से मेल खाने वाले वैध JSON के साथ प्रतिक्रिया देगा।"
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON स्कीमा",
|
||||||
|
"description": "अपेक्षित प्रतिक्रिया की संरचना को परिभाषित करने वाला JSON स्कीमा। structured_output सक्षम होने पर आवश्यक।"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -295,4 +306,4 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,6 @@
|
|||||||
{
|
{
|
||||||
"config": {
|
"config": {
|
||||||
"step": {
|
"step": {
|
||||||
"provider": {
|
|
||||||
"title": "Seleziona fornitore AI",
|
|
||||||
"description": "Scegli quale fornitore di servizi AI utilizzare per questa istanza.",
|
|
||||||
"data": {
|
|
||||||
"api_provider": "Fornitore API",
|
|
||||||
"context_messages": "Numero di messaggi di contesto da mantenere (1-20)",
|
|
||||||
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"provider": {
|
"provider": {
|
||||||
"title": "Impostazioni fornitore",
|
"title": "Impostazioni fornitore",
|
||||||
"description": "Fornisci i dettagli di connessione per il tuo fornitore di AI scelto.",
|
"description": "Fornisci i dettagli di connessione per il tuo fornitore di AI scelto.",
|
||||||
@@ -21,6 +12,7 @@
|
|||||||
"temperature": "Creatività della risposta (0-2, più basso = più focalizzato)",
|
"temperature": "Creatività della risposta (0-2, più basso = più focalizzato)",
|
||||||
"max_tokens": "Lunghezza massima della risposta (1-100000 token)",
|
"max_tokens": "Lunghezza massima della risposta (1-100000 token)",
|
||||||
"request_interval": "Tempo minimo tra le richieste (0.1-60 secondi)",
|
"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)",
|
"context_messages": "Numero di messaggi di contesto da mantenere (1-20)",
|
||||||
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||||
}
|
}
|
||||||
@@ -37,6 +29,7 @@
|
|||||||
"api_endpoint": "URL dell'endpoint API personalizzato (opzionale)",
|
"api_endpoint": "URL dell'endpoint API personalizzato (opzionale)",
|
||||||
"api_provider": "Fornitore API",
|
"api_provider": "Fornitore API",
|
||||||
"request_interval": "Tempo minimo tra le richieste (0.1-60 secondi)",
|
"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)",
|
"context_messages": "Numero di messaggi di contesto da mantenere (1-20)",
|
||||||
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
"max_history_size": "Dimensione massima della cronologia delle conversazioni (1-100)"
|
||||||
}
|
}
|
||||||
@@ -72,13 +65,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "Aggiorna impostazioni dell'istanza",
|
"title": "Seleziona fornitore",
|
||||||
"description": "Modifica le impostazioni per questa istanza di assistente AI.",
|
"description": "Scegli il fornitore AI per questa istanza. L'integrazione verrà ricaricata dopo aver salvato le modifiche.",
|
||||||
"data": {
|
"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",
|
"model": "Modello AI",
|
||||||
"temperature": "Creatività della risposta (0-2)",
|
"temperature": "Creatività della risposta (0-2)",
|
||||||
"max_tokens": "Lunghezza massima della risposta (1-100000)",
|
"max_tokens": "Lunghezza massima della risposta (1-100000)",
|
||||||
"request_interval": "Intervallo minimo di richiesta (0.1-60 secondi)",
|
"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)",
|
"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)"
|
||||||
}
|
}
|
||||||
@@ -98,7 +101,7 @@
|
|||||||
"services": {
|
"services": {
|
||||||
"ask_question": {
|
"ask_question": {
|
||||||
"name": "Fai una domanda (HA Text AI)",
|
"name": "Fai una domanda (HA Text AI)",
|
||||||
"description": "Invia una domanda al modello AI e ricevi una risposta dettagliata. La risposta sarà memorizzata nella cronologia delle conversazioni e potrà essere recuperata in seguito.",
|
"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": {
|
"fields": {
|
||||||
"instance": {
|
"instance": {
|
||||||
"name": "Istanze",
|
"name": "Istanze",
|
||||||
@@ -127,6 +130,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "Token massimi",
|
"name": "Token massimi",
|
||||||
"description": "Lunghezza massima della risposta (1-100000 token)"
|
"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."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,15 +1,6 @@
|
|||||||
{
|
{
|
||||||
"config": {
|
"config": {
|
||||||
"step": {
|
"step": {
|
||||||
"provider": {
|
|
||||||
"title": "Выбор провайдера ИИ",
|
|
||||||
"description": "Выберите сервис искусственного интеллекта для этого экземпляра.",
|
|
||||||
"data": {
|
|
||||||
"api_provider": "Провайдер API",
|
|
||||||
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
|
||||||
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"provider": {
|
"provider": {
|
||||||
"title": "Настройки провайдера",
|
"title": "Настройки провайдера",
|
||||||
"description": "Укажите параметры подключения для выбранного провайдера ИИ.",
|
"description": "Укажите параметры подключения для выбранного провайдера ИИ.",
|
||||||
@@ -21,6 +12,7 @@
|
|||||||
"temperature": "Креативность ответа (0-2, меньше = более сфокусированно)",
|
"temperature": "Креативность ответа (0-2, меньше = более сфокусированно)",
|
||||||
"max_tokens": "Максимальная длина ответа (1-100000 токенов)",
|
"max_tokens": "Максимальная длина ответа (1-100000 токенов)",
|
||||||
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||||
|
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||||
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
||||||
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||||
}
|
}
|
||||||
@@ -37,6 +29,7 @@
|
|||||||
"api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)",
|
"api_endpoint": "Пользовательский URL-адрес конечной точки API (необязательно)",
|
||||||
"api_provider": "Провайдер API",
|
"api_provider": "Провайдер API",
|
||||||
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||||
|
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||||
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
"context_messages": "Количество сохраняемых контекстных сообщений (1-20)",
|
||||||
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||||
}
|
}
|
||||||
@@ -49,6 +42,7 @@
|
|||||||
"name_exists": "Экземпляр с таким именем уже существует",
|
"name_exists": "Экземпляр с таким именем уже существует",
|
||||||
"invalid_name": "Недопустимое имя экземпляра",
|
"invalid_name": "Недопустимое имя экземпляра",
|
||||||
"invalid_auth": "Ошибка аутентификации - проверьте API-ключ",
|
"invalid_auth": "Ошибка аутентификации - проверьте API-ключ",
|
||||||
|
"api_key_required": "Необходимо ввести API-ключ при смене провайдера или эндпоинта",
|
||||||
"invalid_api_key": "Недопустимый API-ключ - пожалуйста, проверьте учетные данные",
|
"invalid_api_key": "Недопустимый API-ключ - пожалуйста, проверьте учетные данные",
|
||||||
"cannot_connect": "Не удалось подключиться к сервису API",
|
"cannot_connect": "Не удалось подключиться к сервису API",
|
||||||
"invalid_model": "Выбранная модель недоступна",
|
"invalid_model": "Выбранная модель недоступна",
|
||||||
@@ -62,7 +56,6 @@
|
|||||||
"invalid_instance": "Указан некорректный экземпляр",
|
"invalid_instance": "Указан некорректный экземпляр",
|
||||||
"unknown": "Произошла непредвиденная ошибка",
|
"unknown": "Произошла непредвиденная ошибка",
|
||||||
"empty": "Имя не может быть пустым",
|
"empty": "Имя не может быть пустым",
|
||||||
"invalid_characters": "Имя может содержать только буквы, цифры, пробелы, подчеркивания и дефисы",
|
|
||||||
"name_too_long": "Имя должно быть не длиннее 50 символов"
|
"name_too_long": "Имя должно быть не длиннее 50 символов"
|
||||||
},
|
},
|
||||||
"abort": {
|
"abort": {
|
||||||
@@ -72,13 +65,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "Обновление настроек экземпляра",
|
"title": "Выбор провайдера",
|
||||||
"description": "Измените настройки для этого экземпляра ИИ-помощника.",
|
"description": "Выберите провайдера ИИ для этого экземпляра. Интеграция перезагрузится после сохранения изменений.",
|
||||||
"data": {
|
"data": {
|
||||||
|
"api_provider": "Провайдер API"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Настройки подключения и модели",
|
||||||
|
"description": "Настройте учётные данные API и параметры модели. Изменения вступят в силу после перезагрузки интеграции.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API-ключ",
|
||||||
|
"api_endpoint": "URL конечной точки API",
|
||||||
"model": "Модель ИИ",
|
"model": "Модель ИИ",
|
||||||
"temperature": "Креативность ответа (0-2)",
|
"temperature": "Креативность ответа (0-2)",
|
||||||
"max_tokens": "Максимальная длина ответа (1-100000)",
|
"max_tokens": "Максимальная длина ответа (1-100000)",
|
||||||
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
"request_interval": "Минимальный интервал между запросами (0.1-60 секунд)",
|
||||||
|
"api_timeout": "Таймаут API-запроса в секундах (5-600)",
|
||||||
"context_messages": "Количество предыдущих сообщений для включения в контекст (1-20)",
|
"context_messages": "Количество предыдущих сообщений для включения в контекст (1-20)",
|
||||||
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
"max_history_size": "Максимальный размер истории разговора (1-100)"
|
||||||
}
|
}
|
||||||
@@ -98,7 +101,7 @@
|
|||||||
"services": {
|
"services": {
|
||||||
"ask_question": {
|
"ask_question": {
|
||||||
"name": "Задать вопрос (HA Text AI)",
|
"name": "Задать вопрос (HA Text AI)",
|
||||||
"description": "Отправить вопрос модели ИИ и получить подробный ответ. Ответ будет сохранен в истории разговора и может быть получен позже.",
|
"description": "Отправить вопрос модели ИИ и получить подробный ответ. Сервис теперь возвращает данные ответа напрямую, устраняя необходимость в отдельных текстовых сенсорах и ограничение в 255 символов. Ответ также будет сохранен в истории разговора.",
|
||||||
"fields": {
|
"fields": {
|
||||||
"instance": {
|
"instance": {
|
||||||
"name": "Экземпляр",
|
"name": "Экземпляр",
|
||||||
@@ -127,6 +130,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "Максимум токенов",
|
"name": "Максимум токенов",
|
||||||
"description": "Максимальная длина ответа (1-100000 токенов)"
|
"description": "Максимальная длина ответа (1-100000 токенов)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Структурированный вывод",
|
||||||
|
"description": "Включить режим структурированного JSON-вывода. При включении ИИ будет отвечать валидным JSON, соответствующим указанной схеме."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON Schema",
|
||||||
|
"description": "JSON-схема, определяющая структуру ожидаемого ответа. Обязательна при включении structured_output."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -197,8 +208,7 @@
|
|||||||
"rate_limited": "Лимит запросов",
|
"rate_limited": "Лимит запросов",
|
||||||
"maintenance": "Техническое обслуживание",
|
"maintenance": "Техническое обслуживание",
|
||||||
"initializing": "Инициализация",
|
"initializing": "Инициализация",
|
||||||
"retrying": "Повторная попытка",
|
"retrying": "Повторная попытка"
|
||||||
"queued": "В очереди"
|
|
||||||
},
|
},
|
||||||
"state_attributes": {
|
"state_attributes": {
|
||||||
"question": {
|
"question": {
|
||||||
@@ -290,6 +300,24 @@
|
|||||||
},
|
},
|
||||||
"min_latency": {
|
"min_latency": {
|
||||||
"name": "Минимальная задержка"
|
"name": "Минимальная задержка"
|
||||||
|
},
|
||||||
|
"last_model": {
|
||||||
|
"name": "Последняя использованная модель"
|
||||||
|
},
|
||||||
|
"last_timestamp": {
|
||||||
|
"name": "Время последнего ответа"
|
||||||
|
},
|
||||||
|
"instance_name": {
|
||||||
|
"name": "Имя экземпляра"
|
||||||
|
},
|
||||||
|
"normalized_name": {
|
||||||
|
"name": "Нормализованное имя"
|
||||||
|
},
|
||||||
|
"last_error": {
|
||||||
|
"name": "Последняя ошибка"
|
||||||
|
},
|
||||||
|
"conversation_history": {
|
||||||
|
"name": "История разговоров"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,15 +1,6 @@
|
|||||||
{
|
{
|
||||||
"config": {
|
"config": {
|
||||||
"step": {
|
"step": {
|
||||||
"provider": {
|
|
||||||
"title": "Изаберите AI провајдера",
|
|
||||||
"description": "Изаберите који AI сервис провајдер да користите за ову инстанцу.",
|
|
||||||
"data": {
|
|
||||||
"api_provider": "API провајдер",
|
|
||||||
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
|
||||||
"max_history_size": "Максимална величина историје разговора (1-100)"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"provider": {
|
"provider": {
|
||||||
"title": "Подешавања провајдера",
|
"title": "Подешавања провајдера",
|
||||||
"description": "Обезбедите детаље о вези за изабраног AI провајдера.",
|
"description": "Обезбедите детаље о вези за изабраног AI провајдера.",
|
||||||
@@ -21,6 +12,7 @@
|
|||||||
"temperature": "Креативност одговора (0-2, нижа = фокусираније)",
|
"temperature": "Креативност одговора (0-2, нижа = фокусираније)",
|
||||||
"max_tokens": "Максимална дужина одговора (1-100000 токена)",
|
"max_tokens": "Максимална дужина одговора (1-100000 токена)",
|
||||||
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
||||||
|
"api_timeout": "Временско ограничење API захтева у секундама (5-600)",
|
||||||
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
||||||
"max_history_size": "Максимална величина историје разговора (1-100)"
|
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||||
}
|
}
|
||||||
@@ -37,6 +29,7 @@
|
|||||||
"api_endpoint": "Прилагођени URL API крајње тачке (опционо)",
|
"api_endpoint": "Прилагођени URL API крајње тачке (опционо)",
|
||||||
"api_provider": "API провајдер",
|
"api_provider": "API провајдер",
|
||||||
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
||||||
|
"api_timeout": "Временско ограничење API захтева у секундама (5-600)",
|
||||||
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
"context_messages": "Број контекстуалних порука које треба задржати (1-20)",
|
||||||
"max_history_size": "Максимална величина историје разговора (1-100)"
|
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||||
}
|
}
|
||||||
@@ -72,13 +65,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "Ажурирајте подешавања инстанце",
|
"title": "Изаберите провајдера",
|
||||||
"description": "Измените подешавања за ову AI асистент инстанцу.",
|
"description": "Изаберите AI провајдера за ову инстанцу. Интеграција ће се поново учитати након чувања измена.",
|
||||||
"data": {
|
"data": {
|
||||||
|
"api_provider": "API провајдер"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "Подешавања везе и модела",
|
||||||
|
"description": "Конфигуришите API акредитиве и параметре модела. Промене ће ступити на снагу након поновног учитавања интеграције.",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API кључ",
|
||||||
|
"api_endpoint": "URL API крајње тачке",
|
||||||
"model": "AI модел",
|
"model": "AI модел",
|
||||||
"temperature": "Креативност одговора (0-2)",
|
"temperature": "Креативност одговора (0-2)",
|
||||||
"max_tokens": "Максимална дужина одговора (1-100000)",
|
"max_tokens": "Максимална дужина одговора (1-100000)",
|
||||||
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
"request_interval": "Минимално време између захтева (0.1-60 секунди)",
|
||||||
|
"api_timeout": "Временско ограничење API захтева у секундама (5-600)",
|
||||||
"context_messages": "Број претходних порука које треба укључити у контекст (1-20)",
|
"context_messages": "Број претходних порука које треба укључити у контекст (1-20)",
|
||||||
"max_history_size": "Максимална величина историје разговора (1-100)"
|
"max_history_size": "Максимална величина историје разговора (1-100)"
|
||||||
}
|
}
|
||||||
@@ -98,7 +101,7 @@
|
|||||||
"services": {
|
"services": {
|
||||||
"ask_question": {
|
"ask_question": {
|
||||||
"name": "Поставите питање (HA Text AI)",
|
"name": "Поставите питање (HA Text AI)",
|
||||||
"description": "Пошаљите питање AI моделу и примите детаљан одговор. Одговор ће бити сачуван у историји разговора и може се касније повратити.",
|
"description": "Пошаљите питање AI моделу и добијте детаљан одговор. Овај сервис сада враћа податке одговора директно, елиминишући потребу за засебним текстуалним сензорима и ограничење од 255 карактера. Одговор ће такође бити сачуван у историји разговора.",
|
||||||
"fields": {
|
"fields": {
|
||||||
"instance": {
|
"instance": {
|
||||||
"name": "Инстанца",
|
"name": "Инстанца",
|
||||||
@@ -127,6 +130,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "Максимални токени",
|
"name": "Максимални токени",
|
||||||
"description": "Максимална дужина одговора (1-100000 токена)"
|
"description": "Максимална дужина одговора (1-100000 токена)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "Структурисани излаз",
|
||||||
|
"description": "Омогући JSON структурисани излаз. Када је омогућено, AI ће одговарати валидним JSON-ом који одговара датој шеми."
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON шема",
|
||||||
|
"description": "JSON шема која дефинише структуру очекиваног одговора. Обавезна када је structured_output омогућен."
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -193,7 +204,7 @@
|
|||||||
"ready": "Спремно",
|
"ready": "Спремно",
|
||||||
"processing": "Обрада",
|
"processing": "Обрада",
|
||||||
"error": "Грешка",
|
"error": "Грешка",
|
||||||
"disconnected": "Прекључено",
|
"disconnected": "Искључено",
|
||||||
"rate_limited": "Ограничење захтева",
|
"rate_limited": "Ограничење захтева",
|
||||||
"maintenance": "Одржавање",
|
"maintenance": "Одржавање",
|
||||||
"initializing": "Инициализује се",
|
"initializing": "Инициализује се",
|
||||||
@@ -295,4 +306,4 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,15 +1,6 @@
|
|||||||
{
|
{
|
||||||
"config": {
|
"config": {
|
||||||
"step": {
|
"step": {
|
||||||
"provider": {
|
|
||||||
"title": "选择AI提供者",
|
|
||||||
"description": "选择要用于此实例的AI服务提供者。",
|
|
||||||
"data": {
|
|
||||||
"api_provider": "API提供者",
|
|
||||||
"context_messages": "保留的上下文消息数量(1-20)",
|
|
||||||
"max_history_size": "最大对话历史大小(1-100)"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"provider": {
|
"provider": {
|
||||||
"title": "提供者设置",
|
"title": "提供者设置",
|
||||||
"description": "提供所选AI提供者的连接详细信息。",
|
"description": "提供所选AI提供者的连接详细信息。",
|
||||||
@@ -21,6 +12,7 @@
|
|||||||
"temperature": "响应创造力(0-2,越低越专注)",
|
"temperature": "响应创造力(0-2,越低越专注)",
|
||||||
"max_tokens": "最大响应长度(1-100000个标记)",
|
"max_tokens": "最大响应长度(1-100000个标记)",
|
||||||
"request_interval": "请求之间的最小时间(0.1-60秒)",
|
"request_interval": "请求之间的最小时间(0.1-60秒)",
|
||||||
|
"api_timeout": "API请求超时时间(5-600秒)",
|
||||||
"context_messages": "保留的上下文消息数量(1-20)",
|
"context_messages": "保留的上下文消息数量(1-20)",
|
||||||
"max_history_size": "最大对话历史大小(1-100)"
|
"max_history_size": "最大对话历史大小(1-100)"
|
||||||
}
|
}
|
||||||
@@ -37,6 +29,7 @@
|
|||||||
"api_endpoint": "自定义API端点URL(可选)",
|
"api_endpoint": "自定义API端点URL(可选)",
|
||||||
"api_provider": "API提供者",
|
"api_provider": "API提供者",
|
||||||
"request_interval": "请求之间的最小时间(0.1-60秒)",
|
"request_interval": "请求之间的最小时间(0.1-60秒)",
|
||||||
|
"api_timeout": "API请求超时时间(5-600秒)",
|
||||||
"context_messages": "保留的上下文消息数量(1-20)",
|
"context_messages": "保留的上下文消息数量(1-20)",
|
||||||
"max_history_size": "最大对话历史大小(1-100)"
|
"max_history_size": "最大对话历史大小(1-100)"
|
||||||
}
|
}
|
||||||
@@ -72,13 +65,23 @@
|
|||||||
"options": {
|
"options": {
|
||||||
"step": {
|
"step": {
|
||||||
"init": {
|
"init": {
|
||||||
"title": "更新实例设置",
|
"title": "选择提供者",
|
||||||
"description": "修改此AI助手实例的设置。",
|
"description": "选择此实例的AI提供者。保存更改后集成将重新加载。",
|
||||||
"data": {
|
"data": {
|
||||||
|
"api_provider": "API提供者"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"settings": {
|
||||||
|
"title": "连接和模型设置",
|
||||||
|
"description": "配置API凭据和模型参数。更改将在集成重新加载后生效。",
|
||||||
|
"data": {
|
||||||
|
"api_key": "API密钥",
|
||||||
|
"api_endpoint": "API端点URL",
|
||||||
"model": "AI模型",
|
"model": "AI模型",
|
||||||
"temperature": "响应创造力(0-2)",
|
"temperature": "响应创造力(0-2)",
|
||||||
"max_tokens": "最大响应长度(1-100000)",
|
"max_tokens": "最大响应长度(1-100000)",
|
||||||
"request_interval": "最小请求间隔(0.1-60秒)",
|
"request_interval": "最小请求间隔(0.1-60秒)",
|
||||||
|
"api_timeout": "API请求超时时间(5-600秒)",
|
||||||
"context_messages": "要包含在上下文中的先前消息数量(1-20)",
|
"context_messages": "要包含在上下文中的先前消息数量(1-20)",
|
||||||
"max_history_size": "最大对话历史大小(1-100)"
|
"max_history_size": "最大对话历史大小(1-100)"
|
||||||
}
|
}
|
||||||
@@ -98,7 +101,7 @@
|
|||||||
"services": {
|
"services": {
|
||||||
"ask_question": {
|
"ask_question": {
|
||||||
"name": "提问 (HA Text AI)",
|
"name": "提问 (HA Text AI)",
|
||||||
"description": "向AI模型发送问题并接收详细响应。响应将存储在对话历史中,可以稍后检索。",
|
"description": "向AI模型发送问题并获得详细回答。此服务现在直接返回响应数据,消除了对单独文本传感器的需要和255字符限制。响应也将存储在对话历史中。",
|
||||||
"fields": {
|
"fields": {
|
||||||
"instance": {
|
"instance": {
|
||||||
"name": "实例",
|
"name": "实例",
|
||||||
@@ -127,6 +130,14 @@
|
|||||||
"max_tokens": {
|
"max_tokens": {
|
||||||
"name": "最大标记数",
|
"name": "最大标记数",
|
||||||
"description": "响应的最大长度(1-100000个标记)"
|
"description": "响应的最大长度(1-100000个标记)"
|
||||||
|
},
|
||||||
|
"structured_output": {
|
||||||
|
"name": "结构化输出",
|
||||||
|
"description": "启用JSON结构化输出模式。启用后,AI将以符合提供的模式的有效JSON进行响应。"
|
||||||
|
},
|
||||||
|
"json_schema": {
|
||||||
|
"name": "JSON模式",
|
||||||
|
"description": "定义预期响应结构的JSON模式。启用structured_output时必需。"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -295,4 +306,4 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
"""
|
||||||
|
Utility functions for HA Text AI integration.
|
||||||
|
|
||||||
|
@license: PolyForm Noncommercial 1.0.0 (https://polyformproject.org/licenses/noncommercial/1.0.0)
|
||||||
|
@author: SMKRV
|
||||||
|
@github: https://github.com/smkrv/ha-text-ai
|
||||||
|
@source: https://github.com/smkrv/ha-text-ai
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ipaddress
|
||||||
|
import socket
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
from homeassistant.const import CONF_API_KEY
|
||||||
|
from homeassistant.core import HomeAssistant
|
||||||
|
|
||||||
|
|
||||||
|
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 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
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def validate_endpoint(hass: HomeAssistant, endpoint: str) -> str:
|
||||||
|
"""Validate API endpoint URL for security.
|
||||||
|
|
||||||
|
Ensures HTTPS-only and blocks private/reserved IP ranges (SSRF protection).
|
||||||
|
Uses async DNS resolution to avoid blocking the event loop.
|
||||||
|
Returns the validated endpoint stripped of trailing slashes.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: If the endpoint fails validation.
|
||||||
|
"""
|
||||||
|
parsed = urlparse(endpoint)
|
||||||
|
|
||||||
|
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")
|
||||||
|
|
||||||
|
# Block private/reserved IPs (direct IP or resolved hostname)
|
||||||
|
try:
|
||||||
|
addr = ipaddress.ip_address(hostname)
|
||||||
|
if _check_ip_restricted(addr):
|
||||||
|
raise _RestrictedIPError("Private/reserved IP addresses are not allowed")
|
||||||
|
except _RestrictedIPError:
|
||||||
|
raise
|
||||||
|
except ValueError:
|
||||||
|
# Not an IP literal — resolve hostname and check all resolved IPs
|
||||||
|
# to prevent DNS rebinding attacks
|
||||||
|
try:
|
||||||
|
addrinfos = await hass.async_add_executor_job(
|
||||||
|
socket.getaddrinfo, hostname, None
|
||||||
|
)
|
||||||
|
for family, _type, _proto, _canonname, sockaddr in addrinfos:
|
||||||
|
ip_str = sockaddr[0]
|
||||||
|
resolved_addr = ipaddress.ip_address(ip_str)
|
||||||
|
if _check_ip_restricted(resolved_addr):
|
||||||
|
raise ValueError(
|
||||||
|
"Hostname resolves to a restricted IP range"
|
||||||
|
)
|
||||||
|
except socket.gaierror as err:
|
||||||
|
raise ValueError(f"Cannot resolve hostname: {hostname}") from err
|
||||||
|
|
||||||
|
return endpoint.rstrip("/")
|
||||||
Reference in New Issue
Block a user