mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 19:57:03 -04:00
Add category filter and pagination to the search integrations LLM tool (#193206)
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude
parent
5c111084fd
commit
12ed26f2e7
@@ -14,6 +14,7 @@ from homeassistant.components.llm import LLMTools
|
||||
from homeassistant.config_entries import ConfigEntry, ConfigEntryState, ConfigFlowResult
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.exceptions import DependencyError, HomeAssistantError
|
||||
from homeassistant.generated.integration_categories import INTEGRATION_CATEGORIES
|
||||
from homeassistant.helpers import config_validation as cv, translation
|
||||
from homeassistant.helpers.llm import (
|
||||
LLM_API_HOME_ASSISTANT,
|
||||
@@ -31,7 +32,6 @@ from .const import DOMAIN
|
||||
from .core import UPDATE_CONFIG_SCHEMA, async_update_config
|
||||
|
||||
_SEARCH_LIMIT = 15
|
||||
_INTEGRATION_FILTER_TYPES = ["integration", "helper"]
|
||||
_STATUS_VALUES = ["loaded", "error", "not_loaded"]
|
||||
_STATUS_STATES: dict[str, set[ConfigEntryState]] = {
|
||||
"loaded": {ConfigEntryState.LOADED},
|
||||
@@ -139,9 +139,9 @@ def _iter_searchable_matches(
|
||||
query: str,
|
||||
descriptions: dict[str, Any],
|
||||
title_trans: dict[str, str],
|
||||
filter_type: str | None,
|
||||
) -> Iterator[tuple[int, str, str, str]]:
|
||||
"""Yield (rank, sort_name, domain, name) for config-flow integrations matching query.
|
||||
category: str | None,
|
||||
) -> Iterator[tuple[int, str, str, str, list[str]]]:
|
||||
"""Yield (rank, sort_name, domain, name, categories) for matching config-flow integrations.
|
||||
|
||||
Lower rank numbers sort first with heapq.nsmallest:
|
||||
- 0: exact match on domain or name
|
||||
@@ -149,22 +149,20 @@ def _iter_searchable_matches(
|
||||
- 2: all query words match domain, name, or brand
|
||||
"""
|
||||
sources: list[tuple[str, dict[str, Any], str]] = []
|
||||
if filter_type in (None, "integration"):
|
||||
for key, info in (
|
||||
descriptions["core"]["integration"] | descriptions["custom"]["integration"]
|
||||
).items():
|
||||
if "integration_type" in info:
|
||||
sources.append((key, info, ""))
|
||||
elif sub := info.get("integrations"):
|
||||
brand = info.get("name", key).casefold()
|
||||
sources.extend((dom, meta, brand) for dom, meta in sub.items())
|
||||
if filter_type in (None, "helper"):
|
||||
sources.extend(
|
||||
(dom, meta, "")
|
||||
for dom, meta in (
|
||||
descriptions["core"]["helper"] | descriptions["custom"]["helper"]
|
||||
).items()
|
||||
)
|
||||
for key, info in (
|
||||
descriptions["core"]["integration"] | descriptions["custom"]["integration"]
|
||||
).items():
|
||||
if "integration_type" in info:
|
||||
sources.append((key, info, ""))
|
||||
elif sub := info.get("integrations"):
|
||||
brand = info.get("name", key).casefold()
|
||||
sources.extend((dom, meta, brand) for dom, meta in sub.items())
|
||||
sources.extend(
|
||||
(dom, meta, "")
|
||||
for dom, meta in (
|
||||
descriptions["core"]["helper"] | descriptions["custom"]["helper"]
|
||||
).items()
|
||||
)
|
||||
|
||||
words = query.replace("_", " ").split()
|
||||
seen: set[str] = set()
|
||||
@@ -179,6 +177,12 @@ def _iter_searchable_matches(
|
||||
head = f"{domain} {name_f}".replace("_", " ")
|
||||
if not all(word in f"{head} {brand}" for word in words):
|
||||
continue
|
||||
categories: list[str] = meta.get("categories", [])
|
||||
# Categories can be subcategories, like 'energy.energy_prices'
|
||||
if category is not None and not any(
|
||||
cat.partition(".")[0] == category for cat in categories
|
||||
):
|
||||
continue
|
||||
seen.add(domain)
|
||||
if query in (domain, name_f):
|
||||
rank = 0
|
||||
@@ -186,7 +190,7 @@ def _iter_searchable_matches(
|
||||
rank = 1
|
||||
else:
|
||||
rank = 2
|
||||
yield (rank, name_f, domain, name)
|
||||
yield (rank, name_f, domain, name, categories)
|
||||
|
||||
|
||||
class GetConfigEntriesTool(Tool):
|
||||
@@ -331,8 +335,9 @@ class SearchIntegrationsTool(Tool):
|
||||
description = (
|
||||
"Search the catalog of available Home Assistant integrations and helpers "
|
||||
"that can be set up via a config flow (including uninstalled ones) by name, "
|
||||
"domain, or brand. Use config__get_config_entries instead to list "
|
||||
"integrations that are already installed."
|
||||
"domain, brand, or category. Returns at most "
|
||||
f"{_SEARCH_LIMIT} results per call. Use config__get_config_entries instead "
|
||||
"to list integrations that are already installed."
|
||||
)
|
||||
annotations = ToolAnnotations(
|
||||
read_only=True, destructive=False, idempotent=True, open_world=False
|
||||
@@ -340,19 +345,29 @@ class SearchIntegrationsTool(Tool):
|
||||
integration = DOMAIN
|
||||
parameters = probatio.Schema(
|
||||
{
|
||||
probatio.Required(
|
||||
probatio.Optional(
|
||||
"query",
|
||||
description=(
|
||||
"Search text to match against integration name, domain, or "
|
||||
"brand (case-insensitive)."
|
||||
"brand (case-insensitive). Required if 'category' is not given."
|
||||
),
|
||||
): _NON_EMPTY_STRING,
|
||||
probatio.Optional(
|
||||
"type",
|
||||
description="Filter results by type: 'integration' or 'helper'.",
|
||||
): probatio.All(
|
||||
str, probatio.Lower, probatio.In(_INTEGRATION_FILTER_TYPES)
|
||||
),
|
||||
"category",
|
||||
description=(
|
||||
"Filter results by category. Use 'helpers' to find helpers, "
|
||||
"and 'local_services' for waste collection, power outages "
|
||||
"and other city or utility information."
|
||||
),
|
||||
): probatio.In(INTEGRATION_CATEGORIES),
|
||||
probatio.Optional(
|
||||
"offset",
|
||||
description=(
|
||||
"Number of results to skip. Use the next_offset of the "
|
||||
"previous result."
|
||||
),
|
||||
default=0,
|
||||
): probatio.All(probatio.Coerce(int), probatio.Range(min=0)),
|
||||
}
|
||||
)
|
||||
|
||||
@@ -362,11 +377,14 @@ class SearchIntegrationsTool(Tool):
|
||||
) -> ToolResult:
|
||||
"""Search available integrations and helpers."""
|
||||
args = self.parameters(tool_input.tool_args)
|
||||
query = args["query"].casefold()
|
||||
filter_type: str | None = args.get("type")
|
||||
if "query" not in args and "category" not in args:
|
||||
raise probatio.Invalid("Either 'query' or 'category' is required.")
|
||||
query = args.get("query", "").casefold()
|
||||
category: str | None = args.get("category")
|
||||
offset: int = args["offset"]
|
||||
|
||||
descriptions = await async_get_integration_descriptions(hass)
|
||||
lang = _resolve_language(hass, llm_context.language)
|
||||
descriptions = await async_get_integration_descriptions(hass)
|
||||
title_trans = await translation.async_get_translations(
|
||||
hass,
|
||||
lang,
|
||||
@@ -374,17 +392,24 @@ class SearchIntegrationsTool(Tool):
|
||||
set(descriptions["core"].get("translated_name", ())),
|
||||
)
|
||||
|
||||
best = heapq.nsmallest(
|
||||
_SEARCH_LIMIT,
|
||||
_iter_searchable_matches(query, descriptions, title_trans, filter_type),
|
||||
)
|
||||
return ToolResult(
|
||||
data={
|
||||
"result": list[JsonValueType](
|
||||
{"domain": domain, "name": name} for _, _, domain, name in best
|
||||
)
|
||||
}
|
||||
matches = list(
|
||||
_iter_searchable_matches(query, descriptions, title_trans, category)
|
||||
)
|
||||
best = heapq.nsmallest(offset + _SEARCH_LIMIT, matches)[offset:]
|
||||
result: JsonObjectType = {
|
||||
"result": list[JsonValueType](
|
||||
{
|
||||
"domain": domain,
|
||||
"name": name,
|
||||
"categories": list[JsonValueType](categories),
|
||||
}
|
||||
for _, _, domain, name, categories in best
|
||||
),
|
||||
"total": len(matches),
|
||||
}
|
||||
if (next_offset := offset + _SEARCH_LIMIT) < len(matches):
|
||||
result["next_offset"] = next_offset
|
||||
return ToolResult(data=result)
|
||||
|
||||
|
||||
_PLACEHOLDER_RE = re.compile(r"\{([^}]+)\}")
|
||||
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
"""Automatically generated file.
|
||||
|
||||
To update, run python3 -m script.hassfest
|
||||
"""
|
||||
|
||||
INTEGRATION_CATEGORIES = [
|
||||
"ai_voice",
|
||||
"appliances_cleaning",
|
||||
"blinds_curtains",
|
||||
"buttons_remotes",
|
||||
"climate",
|
||||
"computers_network",
|
||||
"diy_makers",
|
||||
"energy",
|
||||
"finance",
|
||||
"garden_plants",
|
||||
"health_wellbeing",
|
||||
"helpers",
|
||||
"hubs_protocols",
|
||||
"lighting",
|
||||
"local_services",
|
||||
"media_entertainment",
|
||||
"messaging_notifications",
|
||||
"news_social_media",
|
||||
"other_ecosystems",
|
||||
"pets",
|
||||
"plugs_switches",
|
||||
"presence_location",
|
||||
"productivity_information",
|
||||
"security_safety",
|
||||
"sensors",
|
||||
"vehicles_transport",
|
||||
"water",
|
||||
"weather_alerts",
|
||||
]
|
||||
@@ -1,11 +1,13 @@
|
||||
"""Generate the integration_categories.json file."""
|
||||
"""Generate the integration_categories.json and integration_categories.py files."""
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from hassfest.model import Config, Integration
|
||||
from hassfest.serializer import format_python_namespace
|
||||
|
||||
PATH = "homeassistant/generated/integration_categories.json"
|
||||
PYTHON_PATH = "homeassistant/generated/integration_categories.py"
|
||||
|
||||
|
||||
def _generate(integration_path: Path) -> str:
|
||||
@@ -43,9 +45,21 @@ def _generate(integration_path: Path) -> str:
|
||||
return json.dumps(categories, indent=2)
|
||||
|
||||
|
||||
def _generate_python(categories_json: str) -> str:
|
||||
"""Generate the slugs of the top-level categories, for code that needs them."""
|
||||
return format_python_namespace(
|
||||
{
|
||||
"INTEGRATION_CATEGORIES": [
|
||||
category["slug"] for category in json.loads(categories_json)
|
||||
]
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
def validate(integrations: dict[str, Integration], config: Config) -> None:
|
||||
"""Validate integration_categories.json."""
|
||||
"""Validate integration_categories.json and integration_categories.py."""
|
||||
path = config.root / PATH
|
||||
python_path = config.root / PYTHON_PATH
|
||||
integration = integrations["homeassistant"]
|
||||
|
||||
# The json, translations and icons plugins report invalid strings and icons,
|
||||
@@ -63,8 +77,22 @@ def validate(integrations: dict[str, Integration], config: Config) -> None:
|
||||
fixable=True,
|
||||
)
|
||||
|
||||
config.cache["integration_categories_python"] = python_content = _generate_python(
|
||||
content
|
||||
)
|
||||
|
||||
if not python_path.is_file() or python_path.read_text() != python_content:
|
||||
config.add_error(
|
||||
"integration_categories",
|
||||
"File integration_categories.py is not up to date. "
|
||||
"Run python3 -m script.hassfest",
|
||||
fixable=True,
|
||||
)
|
||||
|
||||
|
||||
def generate(integrations: dict[str, Integration], config: Config) -> None:
|
||||
"""Generate integration_categories.json."""
|
||||
"""Generate integration_categories.json and integration_categories.py."""
|
||||
path = config.root / PATH
|
||||
path.write_text(f"{config.cache['integration_categories']}\n")
|
||||
python_path = config.root / PYTHON_PATH
|
||||
python_path.write_text(config.cache["integration_categories_python"])
|
||||
|
||||
@@ -81,24 +81,52 @@
|
||||
'config__search_integrations': dict({
|
||||
'additionalProperties': False,
|
||||
'properties': dict({
|
||||
'category': dict({
|
||||
'description': "Filter results by category. Use 'helpers' to find helpers, and 'local_services' for waste collection, power outages and other city or utility information.",
|
||||
'enum': list([
|
||||
'ai_voice',
|
||||
'appliances_cleaning',
|
||||
'blinds_curtains',
|
||||
'buttons_remotes',
|
||||
'climate',
|
||||
'computers_network',
|
||||
'diy_makers',
|
||||
'energy',
|
||||
'finance',
|
||||
'garden_plants',
|
||||
'health_wellbeing',
|
||||
'helpers',
|
||||
'hubs_protocols',
|
||||
'lighting',
|
||||
'local_services',
|
||||
'media_entertainment',
|
||||
'messaging_notifications',
|
||||
'news_social_media',
|
||||
'other_ecosystems',
|
||||
'pets',
|
||||
'plugs_switches',
|
||||
'presence_location',
|
||||
'productivity_information',
|
||||
'security_safety',
|
||||
'sensors',
|
||||
'vehicles_transport',
|
||||
'water',
|
||||
'weather_alerts',
|
||||
]),
|
||||
'type': 'string',
|
||||
}),
|
||||
'offset': dict({
|
||||
'default': 0,
|
||||
'description': 'Number of results to skip. Use the next_offset of the previous result.',
|
||||
'minimum': 0,
|
||||
'type': 'integer',
|
||||
}),
|
||||
'query': dict({
|
||||
'description': 'Search text to match against integration name, domain, or brand (case-insensitive).',
|
||||
'description': "Search text to match against integration name, domain, or brand (case-insensitive). Required if 'category' is not given.",
|
||||
'format': 'strip',
|
||||
'type': 'string',
|
||||
}),
|
||||
'type': dict({
|
||||
'description': "Filter results by type: 'integration' or 'helper'.",
|
||||
'enum': list([
|
||||
'integration',
|
||||
'helper',
|
||||
]),
|
||||
'format': 'lower',
|
||||
'type': 'string',
|
||||
}),
|
||||
}),
|
||||
'required': list([
|
||||
'query',
|
||||
]),
|
||||
'type': 'object',
|
||||
}),
|
||||
'config__start_flow': dict({
|
||||
|
||||
@@ -670,20 +670,32 @@ async def test_reload_config_entry_invalid_args(
|
||||
("tool_args", "expected_prefix", "expected_domains"),
|
||||
[
|
||||
pytest.param(
|
||||
{"query": "random", "type": "helper"},
|
||||
[{"domain": "random", "name": "Random"}],
|
||||
{"query": "random"},
|
||||
[{"domain": "random", "name": "Random", "categories": ["helpers"]}],
|
||||
{"random"},
|
||||
id="helper_exact",
|
||||
),
|
||||
pytest.param(
|
||||
{"query": "sun", "type": "integration"},
|
||||
[{"domain": "sun", "name": "Sun"}],
|
||||
{"query": "sun"},
|
||||
[
|
||||
{
|
||||
"domain": "sun",
|
||||
"name": "Sun",
|
||||
"categories": ["weather_alerts.forecasts"],
|
||||
}
|
||||
],
|
||||
{"sun"},
|
||||
id="integration_exact",
|
||||
),
|
||||
pytest.param(
|
||||
{"query": "Times of the Day"},
|
||||
[{"domain": "tod", "name": "Times of the Day Sensor"}],
|
||||
[
|
||||
{
|
||||
"domain": "tod",
|
||||
"name": "Times of the Day Sensor",
|
||||
"categories": ["helpers.calculate_value"],
|
||||
}
|
||||
],
|
||||
{"tod"},
|
||||
id="translated_title_match",
|
||||
),
|
||||
@@ -701,7 +713,13 @@ async def test_reload_config_entry_invalid_args(
|
||||
),
|
||||
pytest.param(
|
||||
{"query": "yale bluetooth"},
|
||||
[{"domain": "yalexs_ble", "name": "Yale Access Bluetooth"}],
|
||||
[
|
||||
{
|
||||
"domain": "yalexs_ble",
|
||||
"name": "Yale Access Bluetooth",
|
||||
"categories": ["security_safety.locks_access"],
|
||||
}
|
||||
],
|
||||
{"yalexs_ble"},
|
||||
id="multi_word_deduplicated",
|
||||
),
|
||||
@@ -723,6 +741,42 @@ async def test_reload_config_entry_invalid_args(
|
||||
set(),
|
||||
id="hardware_excluded",
|
||||
),
|
||||
pytest.param(
|
||||
{"category": "pets"},
|
||||
[],
|
||||
{"litterrobot", "surepetcare", "tractive"},
|
||||
id="category_only",
|
||||
),
|
||||
pytest.param(
|
||||
{"query": "tibber", "category": "energy"},
|
||||
[
|
||||
{
|
||||
"domain": "tibber",
|
||||
"name": "Tibber",
|
||||
"categories": ["energy.energy_prices", "energy.meters_monitoring"],
|
||||
}
|
||||
],
|
||||
{"tibber"},
|
||||
id="query_and_category_includes_subcategories",
|
||||
),
|
||||
pytest.param(
|
||||
{"query": "hue", "category": "energy"},
|
||||
[],
|
||||
set(),
|
||||
id="query_and_category_no_match",
|
||||
),
|
||||
pytest.param(
|
||||
{"category": "helpers", "query": "meter"},
|
||||
[],
|
||||
{"utility_meter"},
|
||||
id="helper_by_category",
|
||||
),
|
||||
pytest.param(
|
||||
{"category": "helpers", "query": "workday"},
|
||||
[],
|
||||
{"workday"},
|
||||
id="helpers_category_includes_integrations",
|
||||
),
|
||||
],
|
||||
)
|
||||
async def test_search_integrations(
|
||||
@@ -746,15 +800,54 @@ async def test_search_integrations(
|
||||
assert len(domains) == len(set(domains))
|
||||
assert expected_domains <= set(domains)
|
||||
assert bool(domains) is bool(expected_domains)
|
||||
if category := tool_args.get("category"):
|
||||
for item in items:
|
||||
assert isinstance(item, dict)
|
||||
assert isinstance(categories := item["categories"], list)
|
||||
assert any(str(cat).partition(".")[0] == category for cat in categories)
|
||||
|
||||
|
||||
async def test_search_integrations_pagination(
|
||||
hass: HomeAssistant,
|
||||
llm_context: llm.LLMContext,
|
||||
) -> None:
|
||||
"""Test paging through the results with offset and next_offset."""
|
||||
tool = SearchIntegrationsTool()
|
||||
domains: list[str] = []
|
||||
offset = 0
|
||||
pages = 0
|
||||
while True:
|
||||
res = await tool.async_call(
|
||||
hass,
|
||||
llm.ToolInput(tool.name, {"category": "energy", "offset": offset}),
|
||||
llm_context,
|
||||
)
|
||||
assert res.error is False
|
||||
assert isinstance(items := res.data["result"], list)
|
||||
assert isinstance(total := res.data["total"], int)
|
||||
domains.extend(item["domain"] for item in items if isinstance(item, dict))
|
||||
pages += 1
|
||||
if "next_offset" not in res.data:
|
||||
break
|
||||
assert len(items) == 15
|
||||
assert isinstance(next_offset := res.data["next_offset"], int)
|
||||
offset = next_offset
|
||||
|
||||
assert pages > 1
|
||||
assert len(domains) == total
|
||||
assert len(set(domains)) == total
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"invalid_args",
|
||||
[
|
||||
pytest.param({}, id="missing_query"),
|
||||
pytest.param({}, id="missing_query_and_category"),
|
||||
pytest.param({"category": ""}, id="empty_category"),
|
||||
pytest.param({"category": "unknown"}, id="unknown_category"),
|
||||
pytest.param({"category": "energy.energy_prices"}, id="subcategory"),
|
||||
pytest.param({"query": ""}, id="empty_query"),
|
||||
pytest.param({"query": " "}, id="whitespace_query"),
|
||||
pytest.param({"query": "hue", "type": "unknown"}, id="invalid_type"),
|
||||
pytest.param({"query": "hue", "offset": -1}, id="negative_offset"),
|
||||
],
|
||||
)
|
||||
async def test_search_integrations_invalid_args(
|
||||
|
||||
@@ -88,6 +88,10 @@ def test_generate(integrations: dict[str, Integration], root_config: Config) ->
|
||||
|
||||
path = root_config.root / integration_categories.PATH
|
||||
assert json.loads(path.read_text()) == EXPECTED
|
||||
python_path = root_config.root / integration_categories.PYTHON_PATH
|
||||
assert 'INTEGRATION_CATEGORIES = [\n "energy",\n "pets",\n]\n' in (
|
||||
python_path.read_text()
|
||||
)
|
||||
|
||||
root_config.errors.clear()
|
||||
integration_categories.validate(integrations, root_config)
|
||||
@@ -97,25 +101,40 @@ def test_generate(integrations: dict[str, Integration], root_config: Config) ->
|
||||
def test_validate_missing_file(
|
||||
integrations: dict[str, Integration], root_config: Config
|
||||
) -> None:
|
||||
"""Test a missing file is a fixable error."""
|
||||
"""Test missing files are fixable errors."""
|
||||
integration_categories.validate(integrations, root_config)
|
||||
|
||||
assert len(root_config.errors) == 1
|
||||
assert root_config.errors[0].plugin == "integration_categories"
|
||||
assert root_config.errors[0].fixable
|
||||
assert [error.error for error in root_config.errors] == [
|
||||
"File integration_categories.json is not up to date. "
|
||||
"Run python3 -m script.hassfest",
|
||||
"File integration_categories.py is not up to date. "
|
||||
"Run python3 -m script.hassfest",
|
||||
]
|
||||
assert all(
|
||||
error.plugin == "integration_categories" and error.fixable
|
||||
for error in root_config.errors
|
||||
)
|
||||
|
||||
|
||||
def test_validate_outdated_file(
|
||||
integrations: dict[str, Integration], root_config: Config
|
||||
) -> None:
|
||||
"""Test an outdated file is a fixable error."""
|
||||
"""Test outdated files are fixable errors."""
|
||||
(root_config.root / integration_categories.PATH).write_text("[]\n")
|
||||
(root_config.root / integration_categories.PYTHON_PATH).write_text("")
|
||||
|
||||
integration_categories.validate(integrations, root_config)
|
||||
|
||||
assert len(root_config.errors) == 1
|
||||
assert root_config.errors[0].plugin == "integration_categories"
|
||||
assert root_config.errors[0].fixable
|
||||
assert [error.error for error in root_config.errors] == [
|
||||
"File integration_categories.json is not up to date. "
|
||||
"Run python3 -m script.hassfest",
|
||||
"File integration_categories.py is not up to date. "
|
||||
"Run python3 -m script.hassfest",
|
||||
]
|
||||
assert all(
|
||||
error.plugin == "integration_categories" and error.fixable
|
||||
for error in root_config.errors
|
||||
)
|
||||
|
||||
|
||||
def test_validate_skips_invalid_integration(
|
||||
|
||||
Reference in New Issue
Block a user