diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index cd8d47ec7..3bf49f721 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -708,6 +708,32 @@ async def menu_price(dish: str) -> float: return None return Tool.from_action(action) + async def list_tools(self) -> list[Tool]: + """Return every tool registered on this app, sorted by name. + + Each is the same handle ``lookup_tool`` returns. Every plugin is initialized + first, so tools a plugin registers in ``init()`` are included, and a plugin + whose ``init()`` fails makes this raise. Tools a plugin only lists in + ``list_actions()`` are registered, and so included, once something has + looked them up. Tools a dynamic action provider serves are not registered + on the app and are left out; pass ``':tool/*'`` in ``tools=[...]`` + to use those. + + Example: + ```python + @ai.tool() + async def menu_price(dish: str) -> float: + return 14.5 + + + [tool.name for tool in await ai.list_tools()] + # => ['menu_price'] + ``` + """ + await self._registry.initialize_all_plugins() + actions = await self._registry.resolve_actions_by_kind(ActionKind.TOOL) + return [Tool.from_action(actions[name]) for name in sorted(actions)] + def lookup_value(self, *, kind: str, name: str) -> object | None: """Return the value defined under ``kind`` and ``name``, or None.""" return self._registry.lookup_value(kind, name) diff --git a/packages/genkit/tests/genkit/veneer/lookup_test.py b/packages/genkit/tests/genkit/veneer/lookup_test.py index c702c8590..9f11f671c 100644 --- a/packages/genkit/tests/genkit/veneer/lookup_test.py +++ b/packages/genkit/tests/genkit/veneer/lookup_test.py @@ -3,7 +3,7 @@ # Copyright 2026 Google LLC # SPDX-License-Identifier: Apache-2.0 -"""What app code and middleware get back from lookup_model, lookup_tool, lookup_value, and define_value.""" +"""What app code and middleware get back from lookup_model, lookup_tool, list_tools, lookup_value, and define_value.""" import re from collections.abc import Awaitable, Callable @@ -164,6 +164,191 @@ async def table_status(table_id: str) -> str: assert Tool.from_action(found) is found +class ToolPlugin(Plugin): + """Registers `catalog/stock` from init, the way a plugin ships tools.""" + + name = 'catalog' + + async def init(self) -> list[Action]: + async def stock(sku: str) -> int: + return 3 + + return [Tool(stock, name='catalog/stock')] + + async def resolve(self, action_type: ActionKind, name: str) -> Action | None: + return None + + async def list_actions(self) -> list[Action]: + return [] + + +@pytest.mark.asyncio +async def test_list_tools_returns_every_defined_tool_as_a_callable_tool() -> None: + """`ai.list_tools()` gives one Tool per defined tool, each describing and running like the decorated one.""" + ai = Genkit() + + @ai.tool() + async def menu_price(dish: str) -> float: + """Price of a dish in dollars.""" + return 14.5 + + @ai.tool() + async def opening_hours() -> str: + """When the restaurant is open.""" + return '9-5' + + tools = {tool.name: tool for tool in await ai.list_tools()} + + assert sorted(tools) == ['menu_price', 'opening_hours'] + assert tools['menu_price'] is menu_price + assert await tools['menu_price']('ramen') == 14.5 + + +@pytest.mark.asyncio +async def test_list_tools_is_sorted_by_name() -> None: + """Tools come back by name, not in the order they were defined.""" + ai = Genkit() + + @ai.tool() + async def opening_hours() -> str: + return '9-5' + + @ai.tool() + async def menu_price(dish: str) -> float: + return 14.5 + + assert [tool.name for tool in await ai.list_tools()] == ['menu_price', 'opening_hours'] + + +@pytest.mark.asyncio +async def test_list_tools_on_an_app_without_tools_is_empty() -> None: + """An app that defines no tools lists none.""" + assert await Genkit().list_tools() == [] + + +@pytest.mark.asyncio +async def test_list_tools_reads_the_app_again_on_every_call() -> None: + """A tool defined after one listing is in the next one.""" + ai = Genkit() + + @ai.tool() + async def menu_price(dish: str) -> float: + return 14.5 + + assert [tool.name for tool in await ai.list_tools()] == ['menu_price'] + + @ai.tool() + async def opening_hours() -> str: + return '9-5' + + assert [tool.name for tool in await ai.list_tools()] == ['menu_price', 'opening_hours'] + + +@pytest.mark.asyncio +async def test_list_tools_includes_interrupts() -> None: + """An interrupt is a tool, so `list_tools` lists it, as `lookup_tool` finds it.""" + ai = Genkit() + ai.define_interrupt('confirm_order', description='Ask the diner to confirm.') + + assert [tool.name for tool in await ai.list_tools()] == ['confirm_order'] + + +@pytest.mark.asyncio +async def test_list_tools_includes_tools_a_plugin_registers_at_init() -> None: + """A plugin's tools are listed before anything has used the plugin.""" + ai = Genkit(plugins=[ToolPlugin()]) + + assert [tool.name for tool in await ai.list_tools()] == ['catalog/stock'] + + +class FailingPlugin(Plugin): + """Fails to start, as a plugin with a bad API key does.""" + + name = 'failing' + + async def init(self) -> list[Action]: + raise RuntimeError('no API key') + + async def resolve(self, action_type: ActionKind, name: str) -> Action | None: + return None + + async def list_actions(self) -> list[Action]: + return [] + + +@pytest.mark.asyncio +async def test_list_tools_raises_when_a_plugin_fails_to_start() -> None: + """A listing that silently dropped a plugin's tools would look complete, so a failed start raises.""" + ai = Genkit(plugins=[FailingPlugin()]) + + @ai.tool() + async def menu_price(dish: str) -> float: + return 14.5 + + with pytest.raises(RuntimeError, match='no API key'): + await ai.list_tools() + + +class AdvertisingToolPlugin(Plugin): + """Lists `shelf/count` in `list_actions()`; the registry gets it only when resolved.""" + + name = 'shelf' + + async def init(self) -> list[Action]: + return [] + + async def resolve(self, action_type: ActionKind, name: str) -> Action | None: + if action_type != ActionKind.TOOL or name != 'count': + return None + return _shelf_count() + + async def list_actions(self) -> list[Action]: + return [_shelf_count()] + + +def _shelf_count() -> Tool: + async def count(sku: str) -> int: + return 7 + + return Tool(count, name='shelf/count') + + +@pytest.mark.asyncio +async def test_list_tools_includes_an_advertised_plugin_tool_only_once_looked_up() -> None: + """Listing does not resolve tools a plugin only advertises; a lookup registers them.""" + ai = Genkit(plugins=[AdvertisingToolPlugin()]) + + assert await ai.list_tools() == [] + assert await ai.lookup_tool('shelf/count') is not None + assert [tool.name for tool in await ai.list_tools()] == ['shelf/count'] + + +@pytest.mark.asyncio +async def test_list_tools_leaves_out_dynamic_action_provider_tools() -> None: + """A provider's tools are not registered on the app, so listing never reaches the provider, even after a lookup.""" + ai = Genkit() + listed = 0 + + async def provide() -> dict[str, list[Action]]: + nonlocal listed + listed += 1 + + async def remote_search(query: str) -> str: + return query + + return {'tool': [Tool(remote_search, name='remote_search')]} + + ai.define_dynamic_action_provider('remote', provide) + + assert await ai.list_tools() == [] + assert listed == 0 + + found = await ai.lookup_tool('remote:tool/remote_search') + assert found is not None + assert await found('ramen') == 'ramen' + assert await ai.list_tools() == [] + + def test_define_value_then_lookup_value_returns_it() -> None: """A value stored with `ai.define_value(...)` comes back from `ai.lookup_value(...)` for the same kind and name.""" ai = Genkit()