Deduplicate equal LLM tools and prefix only conflicting names (#188511)

This commit is contained in:
Paulus Schoutsen
2026-10-26 11:07:38 -04:00
committed by GitHub
parent e0348f9707
commit a26cdd8105
5 changed files with 326 additions and 19 deletions
+7
View File
@@ -25,6 +25,13 @@ class GetDateTimeTool(Tool):
annotations = ToolAnnotations(read_only=True, open_world=False)
integration = DOMAIN
@override
def __eq__(self, other: object) -> bool:
"""All instances of this stateless tool are interchangeable."""
if type(self) is type(other) is GetDateTimeTool:
return True
return NotImplemented
@override
async def async_call(
self,
+36 -8
View File
@@ -203,7 +203,11 @@ class ToolAnnotations:
class Tool:
"""LLM Tool base class."""
"""LLM Tool base class.
Tools may implement equality to allow merged APIs to deduplicate
interchangeable instances with the same name.
"""
name: str
title: str | None = None
@@ -506,18 +510,42 @@ class MergedAPI(API):
await llm_api.async_get_api_instance(llm_context)
for llm_api in self.llm_apis
]
prompt_parts = []
tools: list[Tool] = []
tools_by_name: dict[str, list[tuple[str, Tool]]] = {}
for api_instance in llm_apis:
namespace = unicode_slug.slugify(api_instance.api.name)
namespace = unicode_slug.slugify(api_instance.api.id)
for tool in api_instance.tools:
entries = tools_by_name.setdefault(tool.name, [])
if all(candidate != tool for _, candidate in entries):
entries.append((namespace, tool))
tools = [
tool if len(entries) == 1 else NamespacedTool(namespace, tool)
for entries in tools_by_name.values()
for namespace, tool in entries
]
if len({tool.name for tool in tools}) != len(tools):
raise ValueError("Merged tool names must be unique")
prompt_parts = []
for api_instance in llm_apis:
namespace = unicode_slug.slugify(api_instance.api.id)
tool_names = []
for tool in api_instance.tools:
entries = tools_by_name[tool.name]
if len(entries) == 1:
tool_names.append(tool.name)
else:
tool_namespace = next(
ns for ns, candidate in entries if candidate == tool
)
tool_names.append(f"{tool_namespace}__{tool.name}")
prompt_parts.append(
f'Follow these instructions for tools from "{namespace}":\n'
f'Follow these instructions for tools from "{namespace}" '
f"({', '.join(tool_names)}):\n"
)
prompt_parts.append(api_instance.api_prompt)
prompt_parts.append("\n\n")
tools.extend(
[NamespacedTool(namespace, tool) for tool in api_instance.tools]
)
return APIInstance(
api=self,
+43
View File
@@ -2,13 +2,28 @@
from freezegun import freeze_time
import pytest
from pytest_homeassistant.common import MockUser
from homeassistant.components import llm as llm_component
from homeassistant.components.llm.llm import GetDateTimeTool
from homeassistant.core import Context, HomeAssistant
from homeassistant.helpers import llm
from homeassistant.setup import async_setup_component
def test_get_datetime_equality() -> None:
"""Only the stateless date/time tool opts into equality."""
class ConfiguredDateTimeTool(GetDateTimeTool):
"""A tool whose subclass may introduce configuration."""
assert GetDateTimeTool() == GetDateTimeTool()
assert GetDateTimeTool() != llm.Tool()
assert GetDateTimeTool() != ConfiguredDateTimeTool()
assert ConfiguredDateTimeTool() != GetDateTimeTool()
assert ConfiguredDateTimeTool() != ConfiguredDateTimeTool()
@pytest.fixture(autouse=True)
async def setup_integrations(hass: HomeAssistant) -> None:
"""Set up the integrations for the llm tools platform."""
@@ -51,3 +66,31 @@ async def test_get_datetime_tool(hass: HomeAssistant) -> None:
"weekday": "Wednesday",
}
)
@pytest.mark.parametrize(
"api_ids",
[
[llm.LLM_API_ASSIST, llm.LLM_API_HOME_ASSISTANT],
[llm.LLM_API_HOME_ASSISTANT, llm.LLM_API_ASSIST],
],
)
async def test_builtin_apis_merge_without_prefixes(
hass: HomeAssistant, hass_admin_user: MockUser, api_ids: list[str]
) -> None:
"""Shared built-in tools must compare equal so merging preserves their names."""
llm_context = _llm_context()
llm_context.context = Context(user_id=hass_admin_user.id)
instances = [
await llm.async_get_api(hass, api_id, llm_context) for api_id in api_ids
]
original_names = {tool.name for instance in instances for tool in instance.tools}
assert {
"homeassistant__GetLiveContext",
"homeassistant__render_template",
"llm__GetDateTime",
} <= original_names
merged = await llm.async_get_api(hass, api_ids, llm_context)
assert sorted(tool.name for tool in merged.tools) == sorted(original_names)
+52 -2
View File
@@ -714,8 +714,58 @@ async def test_mcp_tools_list_all_llm_apis(
result = await session.list_tools()
tool_names = {tool.name for tool in result.tools}
assert "device-control__homeassistant__GetLiveContext" in tool_names
assert "test-api__test_tool" in tool_names
assert "homeassistant__GetLiveContext" in tool_names
assert "assist__homeassistant__GetLiveContext" not in tool_names
assert "device-control__homeassistant__GetLiveContext" not in tool_names
assert "test_tool" in tool_names
assert [tool.name for tool in result.tools].count("llm__GetDateTime") == 1
@pytest.mark.parametrize("llm_hass_api", [[llm.LLM_API_ASSIST, TEST_LLM_API_ID]])
async def test_mcp_merged_live_context(
hass: HomeAssistant,
setup_integration: None,
mcp_url: str,
mcp_client: MCPClientFactory,
hass_supervisor_access_token: str,
) -> None:
"""Call live context with its unchanged name in a merged API."""
llm.async_register_api(
hass, MockLLMAPI(hass=hass, id=TEST_LLM_API_ID, name="Test API")
)
async with mcp_client(hass, mcp_url, hass_supervisor_access_token) as session:
result = await session.call_tool(
name="homeassistant__GetLiveContext", arguments={"domain": "light"}
)
assert not result.is_error
assert "Kitchen Light" in result.content[0].text
@pytest.mark.parametrize("llm_hass_api", [[llm.LLM_API_ASSIST, TEST_LLM_API_ID]])
@pytest.mark.parametrize("read_only", [True])
async def test_mcp_merged_read_only_blocks_write_tools(
hass: HomeAssistant,
setup_integration: None,
mcp_url: str,
mcp_client: MCPClientFactory,
hass_supervisor_access_token: str,
) -> None:
"""Merged write tools are excluded by the read-only tool filter."""
llm.async_register_api(
hass, MockLLMAPI(hass=hass, id=TEST_LLM_API_ID, name="Test API")
)
async with mcp_client(hass, mcp_url, hass_supervisor_access_token) as session:
result = await session.call_tool(
name="intent__HassTurnOn",
arguments={"name": "kitchen light"},
)
assert result.is_error
assert 'Tool "intent__HassTurnOn" not found' in result.content[0].text
assert hass.states.get(TEST_ENTITY).state == STATE_OFF
@pytest.mark.usefixtures("setup_integration")
+188 -9
View File
@@ -12,6 +12,7 @@ from pytest_homeassistant.common import (
mock_integration,
)
from homeassistant.components import llm as llm_component
from homeassistant.components.homeassistant.exposed_entities import async_expose_entity
from homeassistant.components.intent import async_register_timer_handler
from homeassistant.components.script import ScriptConfig
@@ -1628,7 +1629,16 @@ async def test_no_tools_exposed(hass: HomeAssistant) -> None:
]
async def test_merged_api(hass: HomeAssistant, llm_context: llm.LLMContext) -> None:
@pytest.mark.parametrize(
("first_name", "second_name"),
[("API 1", "API 2"), ("Renamed API", "Other API"), ("Same name", "Same name")],
)
async def test_merged_api(
hass: HomeAssistant,
llm_context: llm.LLMContext,
first_name: str,
second_name: str,
) -> None:
"""Test an API instance that merges multiple llm apis."""
class MyTool(llm.Tool):
@@ -1644,12 +1654,12 @@ async def test_merged_api(hass: HomeAssistant, llm_context: llm.LLMContext) -> N
data={"result": {tool_input.tool_name: tool_input.tool_args}}
)
api1 = MyAPI(hass=hass, id="api-1", name="API 1")
api1 = MyAPI(hass=hass, id="api-1", name=first_name)
api1.prompt = "This is prompt 1"
api1.tools = [MyTool(name="Tool_1", description="Description 1")]
llm.async_register_api(hass, api1)
api2 = MyAPI(hass=hass, id="api-2", name="API 2")
api2 = MyAPI(hass=hass, id="api-2", name=second_name)
api2.prompt = "This is prompt 2"
api2.tools = [MyTool(name="Tool_2", description="Description 2")]
llm.async_register_api(hass, api2)
@@ -1660,32 +1670,201 @@ async def test_merged_api(hass: HomeAssistant, llm_context: llm.LLMContext) -> N
assert (
instance.api_prompt
== """Follow these instructions for tools from "api-1":
== """Follow these instructions for tools from "api-1" (Tool_1):
This is prompt 1
Follow these instructions for tools from "api-2":
Follow these instructions for tools from "api-2" (Tool_2):
This is prompt 2
"""
)
assert [(tool.name, tool.description) for tool in instance.tools] == [
("api-1__Tool_1", "Description 1"),
("api-2__Tool_2", "Description 2"),
("Tool_1", "Description 1"),
("Tool_2", "Description 2"),
]
# The test tool returns back the provided arguments so we can verify
# the original tool is invoked with the correct tool name and args.
result = await instance.async_call_tool(
llm.ToolInput(tool_name="api-1__Tool_1", tool_args={"arg1": "value1"})
llm.ToolInput(tool_name="Tool_1", tool_args={"arg1": "value1"})
)
assert result.data == {"result": {"Tool_1": {"arg1": "value1"}}}
result = await instance.async_call_tool(
llm.ToolInput(tool_name="api-2__Tool_2", tool_args={"arg2": "value2"})
llm.ToolInput(tool_name="Tool_2", tool_args={"arg2": "value2"})
)
assert result.data == {"result": {"Tool_2": {"arg2": "value2"}}}
@pytest.mark.parametrize(
("tool_name", "expected_api"),
[
("first__test_tool", "first"),
("second__test_tool", "second"),
],
)
async def test_merged_api_conflicting_names(
hass: HomeAssistant,
llm_context: llm.LLMContext,
tool_name: str,
expected_api: str,
) -> None:
"""Conflicting tool names use API IDs regardless of their display names."""
class MyTool(llm.Tool):
name = "test_tool"
integration = "test"
def __init__(self, api_id: str) -> None:
self.api_id = api_id
async def async_call(
self, hass: HomeAssistant, tool_input: llm.ToolInput, _: llm.LLMContext
) -> llm.ToolResult:
return llm.ToolResult(
data={"api": self.api_id, "tool": tool_input.tool_name}
)
first = MyAPI(hass=hass, id="first", name="Second")
first.tools = [MyTool("first")]
second = MyAPI(hass=hass, id="second", name="First")
second.tools = [MyTool("second")]
llm.async_register_api(hass, first)
llm.async_register_api(hass, second)
instance = await llm.async_get_api(hass, ["first", "second"], llm_context)
assert [tool.name for tool in instance.tools] == [
"first__test_tool",
"second__test_tool",
]
result = await instance.async_call_tool(
llm.ToolInput(tool_name=tool_name, tool_args={})
)
assert result.data == {"api": expected_api, "tool": "test_tool"}
async def test_merged_api_equal_tools(
hass: HomeAssistant, llm_context: llm.LLMContext
) -> None:
"""Equal tools are advertised once without an API prefix."""
first = MyAPI(hass=hass, id="first", name="Same name")
first.tools = (
await llm_component.async_get_tools(hass, llm_context, "first")
).tools
second = MyAPI(hass=hass, id="second", name="Same name")
second.tools = (
await llm_component.async_get_tools(hass, llm_context, "second")
).tools
instance = await llm.MergedAPI([first, second]).async_get_api_instance(llm_context)
assert [tool.name for tool in instance.tools] == ["llm__GetDateTime"]
result = await instance.async_call_tool(llm.ToolInput("llm__GetDateTime", {}))
assert "date" in result.data
assert "time" in result.data
async def test_merged_api_equal_tools_with_conflict(
hass: HomeAssistant, llm_context: llm.LLMContext
) -> None:
"""Prompts reference the shared tool's namespace when another tool conflicts."""
first = MyAPI(hass=hass, id="first", name="First")
first.tools = (
await llm_component.async_get_tools(hass, llm_context, "first")
).tools
first.prompt = "First instructions"
second = MyAPI(hass=hass, id="second", name="Second")
second.tools = (
await llm_component.async_get_tools(hass, llm_context, "second")
).tools
second.prompt = "Second instructions"
third = MyAPI(hass=hass, id="third", name="Third")
conflicting_tool = llm.Tool()
conflicting_tool.name = "llm__GetDateTime"
conflicting_tool.integration = "test"
third.tools = [conflicting_tool]
third.prompt = "Third instructions"
instance = await llm.MergedAPI([first, second, third]).async_get_api_instance(
llm_context
)
assert [tool.name for tool in instance.tools] == [
"first__llm__GetDateTime",
"third__llm__GetDateTime",
]
assert instance.api_prompt == (
'Follow these instructions for tools from "first" (first__llm__GetDateTime):\n'
"First instructions\n\n"
'Follow these instructions for tools from "second" (first__llm__GetDateTime):\n'
"Second instructions\n\n"
'Follow these instructions for tools from "third" (third__llm__GetDateTime):\n'
"Third instructions\n\n"
)
result = await instance.async_call_tool(
llm.ToolInput("first__llm__GetDateTime", {})
)
assert "date" in result.data
assert "time" in result.data
async def test_merged_api_generated_name_collision(
hass: HomeAssistant, llm_context: llm.LLMContext
) -> None:
"""Reject collisions between generated prefixes and existing tool names."""
first = MyAPI(hass=hass, id="first", name="First")
first_tool = llm.Tool()
first_tool.name = "test_tool"
first_tool.integration = "test"
first.tools = [first_tool]
second = MyAPI(hass=hass, id="second", name="Second")
second_tool = llm.Tool()
second_tool.name = "test_tool"
second_tool.integration = "test"
colliding_tool = llm.Tool()
colliding_tool.name = "first__test_tool"
colliding_tool.integration = "test"
second.tools = [second_tool, colliding_tool]
with pytest.raises(ValueError, match="Merged tool names must be unique"):
await llm.MergedAPI([first, second]).async_get_api_instance(llm_context)
@pytest.mark.parametrize("api_ids", [("first", "second"), ("second", "first")])
async def test_merged_api_distinct_names(
hass: HomeAssistant, llm_context: llm.LLMContext, api_ids: tuple[str, str]
) -> None:
"""Distinct tool names stay unchanged even when one contains an API prefix."""
class MyTool(llm.Tool):
integration = "test"
def __init__(self, name: str) -> None:
self.name = name
async def async_call(
self, hass: HomeAssistant, tool_input: llm.ToolInput, _: llm.LLMContext
) -> llm.ToolResult:
return llm.ToolResult(data={"tool": tool_input.tool_name})
first = MyAPI(hass=hass, id="first", name="First")
first.tools = [MyTool("test_tool")]
second = MyAPI(hass=hass, id="second", name="Second")
second.tools = [MyTool("first__test_tool")]
llm.async_register_api(hass, first)
llm.async_register_api(hass, second)
instance = await llm.async_get_api(hass, list(api_ids), llm_context)
assert {tool.name for tool in instance.tools} == {
"test_tool",
"first__test_tool",
}
result = await instance.async_call_tool(llm.ToolInput("test_tool", {}))
assert result.data == {"tool": "test_tool"}
result = await instance.async_call_tool(llm.ToolInput("first__test_tool", {}))
assert result.data == {"tool": "first__test_tool"}
async def test_deprecated_async_render_no_api_prompt(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None: