From 2accedc0ec91300a4a7f6c7a6eedf3df0c5b2aaa Mon Sep 17 00:00:00 2001 From: genkit-bot Date: Thu, 3 Dec 2026 13:55:24 -0500 Subject: [PATCH] refactor(py): register tools as a single tool.v2 action Requested-by: huangjeff5 --- packages/genkit-mcp/src/genkit_mcp/_client.py | 2 +- packages/genkit-mcp/src/genkit_mcp/_tools.py | 4 +- packages/genkit-mcp/tests/mcp_client_test.py | 10 +- packages/genkit-mcp/tests/mcp_host_test.py | 30 +- .../src/genkit_middleware/_tool_approval.py | 2 +- .../genkit-middleware/tests/artifacts_test.py | 17 +- .../tests/skills_sandbox_test.py | 10 +- .../genkit-middleware/tests/skills_test.py | 11 +- .../src/genkit_otel/_genai_instrumentation.py | 2 +- packages/genkit/src/genkit/_ai/_aio.py | 85 ++++- packages/genkit/src/genkit/_ai/_decorators.py | 59 +++- packages/genkit/src/genkit/_ai/_generate.py | 23 +- packages/genkit/src/genkit/_ai/_tools.py | 128 +++++++- packages/genkit/src/genkit/_core/_action.py | 17 +- .../genkit/src/genkit/_core/_reflection.py | 2 +- .../genkit/src/genkit/_core/_reflection_v2.py | 2 +- packages/genkit/src/genkit/_core/_registry.py | 19 +- packages/genkit/src/genkit/_core/_tool.py | 307 ++++++++++++------ .../genkit/tests/genkit/ai/_tools_test.py | 18 +- .../genkit/ai/dynamic_tools_generate_test.py | 14 +- .../tests/genkit/ai/flow_return_test.py | 13 +- .../tests/genkit/ai/generate_loop_test.py | 2 +- .../ai/streaming_tool_send_chunk_test.py | 47 +-- .../tests/genkit/ai/tool_multipart_test.py | 121 +++---- .../tests/genkit/ai/tool_none_input_test.py | 8 +- .../genkit/ai/tool_response_contract_test.py | 155 ++++++--- .../tests/genkit/ai/tool_signature_test.py | 20 +- .../tests/genkit/core/context_types_test.py | 5 +- .../genkit/core/endpoints/reflection_test.py | 23 +- .../tests/genkit/core/run_in_new_span_test.py | 2 +- .../core/telemetry/trace_data_encoder_test.py | 4 +- .../genkit/tests/genkit/veneer/lookup_test.py | 7 +- .../typecheck/action_and_ref_contract_test.py | 5 +- .../tests/typecheck/context_contract_test.py | 7 +- .../flow_tool_shapes_contract_test.py | 20 +- 35 files changed, 812 insertions(+), 389 deletions(-) diff --git a/packages/genkit-mcp/src/genkit_mcp/_client.py b/packages/genkit-mcp/src/genkit_mcp/_client.py index 61751ee59..a11205e41 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_client.py +++ b/packages/genkit-mcp/src/genkit_mcp/_client.py @@ -167,7 +167,7 @@ async def get_active_tools(self) -> list[Tool]: Every call lists from the server, so the answer is what the server serves now whether or not this client is registered, and ``tool.name`` is the - namespaced name a model is shown. ``tool.model_output_schema`` is the + namespaced name a model is shown. ``tool.output_schema`` is the schema the server declared, if any. The list can go straight into ``generate`` as ``tools=``, and each tool diff --git a/packages/genkit-mcp/src/genkit_mcp/_tools.py b/packages/genkit-mcp/src/genkit_mcp/_tools.py index 257de3188..94cad815d 100644 --- a/packages/genkit-mcp/src/genkit_mcp/_tools.py +++ b/packages/genkit-mcp/src/genkit_mcp/_tools.py @@ -287,7 +287,7 @@ def mcp_tools_to_handles( """Build one Genkit tool handle per tool in a server listing. A handle is what ``generate`` accepts in ``tools``, and what a caller can - invoke directly. Its ``model_output_schema`` is the one the server declared. + invoke directly. Its ``output_schema`` is the one the server declared. Args: tools: Tools as listed by the server. @@ -302,5 +302,5 @@ def mcp_tools_to_handles( handles = mcp_tools_to_actions(tools, prefix, call) for handle in handles: output_schema = by_name[handle.name].outputSchema - handle.model_output_schema = dict(output_schema) if output_schema is not None else None + handle.output_schema = dict(output_schema) if output_schema is not None else None return handles diff --git a/packages/genkit-mcp/tests/mcp_client_test.py b/packages/genkit-mcp/tests/mcp_client_test.py index d3df48735..153b6bc6f 100644 --- a/packages/genkit-mcp/tests/mcp_client_test.py +++ b/packages/genkit-mcp/tests/mcp_client_test.py @@ -188,7 +188,7 @@ async def test_wildcard_selector_expands_to_every_tool(tmp_path: Path) -> None: await client.close() assert client.name == 'fake' - assert sorted(expanded) == sorted(f'/tool/fake_{tool}' for tool in ALL_TOOLS) + assert sorted(expanded) == sorted(f'/tool.v2/fake_{tool}' for tool in ALL_TOOLS) @pytest.mark.asyncio @@ -277,10 +277,10 @@ async def test_a_dead_server_drops_the_listing_and_is_replaced(tmp_path: Path) - ai = Genkit() client = define_mcp_client(ai, 'fake', **server(tmp_path), cache_ttl_millis=LONG_TTL_MILLIS) try: - action = await ai._registry.resolve_action(ActionKind.TOOL, 'fake_echo') + action = await ai._registry.resolve_action(ActionKind.TOOL_V2, 'fake_echo') assert action is None await expand_wildcard_tools(ai._registry, ['fake:tool/*']) - action = await ai._registry.resolve_action(ActionKind.TOOL, 'fake_echo') + action = await ai._registry.resolve_action(ActionKind.TOOL_V2, 'fake_echo') assert action is not None assert (await action.run({'message': 'first'})).response.output == 'first' @@ -296,7 +296,7 @@ async def test_a_dead_server_drops_the_listing_and_is_replaced(tmp_path: Path) - # The listing outlives its TTL, so re-listing here is the invalidation, # and a process to list from is the replaced connection. expanded = await expand_wildcard_tools(ai._registry, ['fake:tool/*']) - assert sorted(expanded) == sorted(f'/tool/fake_{tool}' for tool in ALL_TOOLS) + assert sorted(expanded) == sorted(f'/tool.v2/fake_{tool}' for tool in ALL_TOOLS) replaced = server_processes(tmp_path) assert len(replaced) == 1 assert replaced[0].pid != killed[0].pid @@ -1033,7 +1033,7 @@ async def test_get_active_tools_lists_what_the_selector_binds(tmp_path: Path) -> assert [tool.name for tool in tools] == [f'fake_{tool}' for tool in ALL_TOOLS] assert [tool.description for tool in tools][:2] == ['Echo input.', 'Another tool.'] - assert sorted(expanded) == sorted(f'/tool/{tool.name}' for tool in tools) + assert sorted(expanded) == sorted(f'/tool.v2/{tool.name}' for tool in tools) @pytest.mark.asyncio diff --git a/packages/genkit-mcp/tests/mcp_host_test.py b/packages/genkit-mcp/tests/mcp_host_test.py index d9e1c293c..8ff6be4f9 100644 --- a/packages/genkit-mcp/tests/mcp_host_test.py +++ b/packages/genkit-mcp/tests/mcp_host_test.py @@ -337,7 +337,7 @@ async def test_a_wildcard_selector_binds_tools_from_every_server(tmp_path: Path) finally: await host.close() - assert sorted(expanded) == sorted(f'/tool/{name}' for name in hosted('alpha', 'beta')) + assert sorted(expanded) == sorted(f'/tool.v2/{name}' for name in hosted('alpha', 'beta')) @pytest.mark.asyncio @@ -427,8 +427,8 @@ async def test_connect_adds_a_server_and_drops_the_listing(tmp_path: Path) -> No finally: await host.close() - assert sorted(before) == sorted(f'/tool/{name}' for name in hosted('alpha')) - assert sorted(after) == sorted(f'/tool/{name}' for name in hosted('alpha', 'beta')) + assert sorted(before) == sorted(f'/tool.v2/{name}' for name in hosted('alpha')) + assert sorted(after) == sorted(f'/tool.v2/{name}' for name in hosted('alpha', 'beta')) @pytest.mark.asyncio @@ -499,7 +499,7 @@ async def test_connect_reports_a_server_which_cannot_be_started_and_keeps_the_ho finally: await host.close() - assert sorted(expanded) == sorted(f'/tool/{name}' for name in hosted('alpha')) + assert sorted(expanded) == sorted(f'/tool.v2/{name}' for name in hosted('alpha')) assert server_processes() == [] @@ -587,7 +587,7 @@ async def close_and_complain(client: McpClient) -> None: finally: await host.close() - assert sorted(expanded) == sorted(f'/tool/{name}' for name in hosted('alpha')) + assert sorted(expanded) == sorted(f'/tool.v2/{name}' for name in hosted('alpha')) assert server_processes() == [] @@ -613,7 +613,7 @@ async def test_disconnect_removes_one_server_and_stops_it(tmp_path: Path) -> Non finally: await host.close() - assert sorted(expanded) == sorted(f'/tool/{name}' for name in hosted('alpha')) + assert sorted(expanded) == sorted(f'/tool.v2/{name}' for name in hosted('alpha')) assert server_processes() == [] @@ -739,8 +739,8 @@ async def test_a_failed_tool_call_re_lists_every_server(tmp_path: Path) -> None: ) try: await expand_wildcard_tools(ai._registry, ['hosted:tool/*']) - counter = await ai._registry.resolve_action(ActionKind.TOOL, 'alpha_list_requests') - beta_echo = await ai._registry.resolve_action(ActionKind.TOOL, 'beta_echo') + counter = await ai._registry.resolve_action(ActionKind.TOOL_V2, 'alpha_list_requests') + beta_echo = await ai._registry.resolve_action(ActionKind.TOOL_V2, 'beta_echo') assert counter is not None assert beta_echo is not None assert (await counter.run({})).response.output == '1' @@ -773,8 +773,8 @@ async def test_a_server_connected_later_shares_the_same_listing(tmp_path: Path) try: await host.connect('beta', server(tmp_path, pid_name='beta')) await expand_wildcard_tools(ai._registry, ['hosted:tool/*']) - counter = await ai._registry.resolve_action(ActionKind.TOOL, 'alpha_list_requests') - beta_echo = await ai._registry.resolve_action(ActionKind.TOOL, 'beta_echo') + counter = await ai._registry.resolve_action(ActionKind.TOOL_V2, 'alpha_list_requests') + beta_echo = await ai._registry.resolve_action(ActionKind.TOOL_V2, 'beta_echo') assert counter is not None assert beta_echo is not None assert (await counter.run({})).response.output == '1' @@ -807,8 +807,8 @@ async def test_a_disconnected_server_cannot_drop_the_listing(tmp_path: Path) -> ) try: await expand_wildcard_tools(ai._registry, ['hosted:tool/*']) - counter = await ai._registry.resolve_action(ActionKind.TOOL, 'alpha_list_requests') - beta_echo = await ai._registry.resolve_action(ActionKind.TOOL, 'beta_echo') + counter = await ai._registry.resolve_action(ActionKind.TOOL_V2, 'alpha_list_requests') + beta_echo = await ai._registry.resolve_action(ActionKind.TOOL_V2, 'beta_echo') assert counter is not None assert beta_echo is not None assert (await counter.run({})).response.output == '1' @@ -854,7 +854,7 @@ async def test_a_host_name_a_model_would_refuse_is_accepted(tmp_path: Path) -> N finally: await host.close() - assert sorted(expanded) == sorted(f'/tool/{name}' for name in hosted('alpha')) + assert sorted(expanded) == sorted(f'/tool.v2/{name}' for name in hosted('alpha')) @pytest.mark.asyncio @@ -969,7 +969,7 @@ async def test_a_disabled_server_is_never_started_or_listed(tmp_path: Path) -> N finally: await host.close() - assert sorted(expanded) == sorted(f'/tool/{name}' for name in hosted('alpha')) + assert sorted(expanded) == sorted(f'/tool.v2/{name}' for name in hosted('alpha')) assert not (tmp_path / 'beta.pid').exists() @@ -1035,7 +1035,7 @@ async def test_connect_with_a_disabled_entry_removes_the_server_of_that_name(tmp finally: await host.close() - assert sorted(expanded) == sorted(f'/tool/{name}' for name in hosted('alpha')) + assert sorted(expanded) == sorted(f'/tool.v2/{name}' for name in hosted('alpha')) assert not (tmp_path / 'replacement.pid').exists() diff --git a/packages/genkit-middleware/src/genkit_middleware/_tool_approval.py b/packages/genkit-middleware/src/genkit_middleware/_tool_approval.py index 4d6c7a1ce..ad3151166 100644 --- a/packages/genkit-middleware/src/genkit_middleware/_tool_approval.py +++ b/packages/genkit-middleware/src/genkit_middleware/_tool_approval.py @@ -93,7 +93,7 @@ async def body(_span: SpanContext) -> MultipartToolResponse: return await run_in_new_span( tool_name, body, - action_type=str(ActionKind.TOOL), + action_type=str(ActionKind.TOOL_V2), input=tool_input, is_action=True, ) diff --git a/packages/genkit-middleware/tests/artifacts_test.py b/packages/genkit-middleware/tests/artifacts_test.py index d2a57cf60..de1197d7a 100644 --- a/packages/genkit-middleware/tests/artifacts_test.py +++ b/packages/genkit-middleware/tests/artifacts_test.py @@ -128,7 +128,8 @@ async def check(session: SessionRunner) -> None: write = tools['write_artifact'] result = await write.run(input={'name': 'poem.txt', 'content': 'roses are red'}) - assert result.response.status == 'Artifact "poem.txt" saved successfully.' + assert result.response.output is not None + assert result.response.output.status == 'Artifact "poem.txt" saved successfully.' arts = await session.get_artifacts() assert len(arts) == 1 assert arts[0].name == 'poem.txt' @@ -145,9 +146,10 @@ async def check(_session: SessionRunner) -> None: read = next(t for t in mw.tools(ctx) if t.name == 'read_artifact') result = await read.run(input={'name': 'notes.txt'}) - assert result.response.name == 'notes.txt' - assert result.response.content == 'hello' - assert result.response.found is True + assert result.response.output is not None + assert result.response.output.name == 'notes.txt' + assert result.response.output.content == 'hello' + assert result.response.output.found is True await _run_in_agent_turn(check, artifacts=[Artifact(name='notes.txt', parts=[Part.from_text('hello')])]) @@ -157,9 +159,10 @@ async def test_read_artifact_without_session(ctx: MiddlewareContext) -> None: mw = Artifacts() read = next(t for t in mw.tools(ctx) if t.name == 'read_artifact') result = await read.run(input={'name': 'missing.txt'}) - assert result.response.name == 'missing.txt' - assert 'no active agent session' in result.response.content.lower() - assert result.response.found is False + assert result.response.output is not None + assert result.response.output.name == 'missing.txt' + assert 'no active agent session' in result.response.output.content.lower() + assert result.response.output.found is False @pytest.mark.asyncio diff --git a/packages/genkit-middleware/tests/skills_sandbox_test.py b/packages/genkit-middleware/tests/skills_sandbox_test.py index 6875d2a12..2ae006e35 100644 --- a/packages/genkit-middleware/tests/skills_sandbox_test.py +++ b/packages/genkit-middleware/tests/skills_sandbox_test.py @@ -69,7 +69,9 @@ def _sparse_skill(skill_dir: Path, size: int) -> None: async def _use_skill(skills: Skills, ctx: MiddlewareContext, name: str) -> str: (tool,) = skills.tools(ctx) - return await tool({'skill_name': name}) + res = await tool({'skill_name': name}) + assert isinstance(res.output, str) + return res.output # --------------------------------------------------------------------------- @@ -164,7 +166,8 @@ async def test_skill_file_swapped_for_symlink_after_scan_is_not_read( skill_md.unlink() skill_md.symlink_to(sandbox['canary']) - result = await tool({'skill_name': 'allergy-check'}) + result = (await tool({'skill_name': 'allergy-check'})).output + assert isinstance(result, str) assert _CANARY not in result @@ -185,10 +188,11 @@ def swapped(path: Path, _root: Path) -> str: raise ValueError(f'SKILL.md is not a regular file: {path}') monkeypatch.setattr(_skills, '_read_skill_file', swapped) - result = await tool({'skill_name': 'allergy-check'}) + result = (await tool({'skill_name': 'allergy-check'})).output assert len(calls) == 1 assert result == 'Failed to read skill "allergy-check".' + assert isinstance(result, str) assert str(sandbox['root']) not in result diff --git a/packages/genkit-middleware/tests/skills_test.py b/packages/genkit-middleware/tests/skills_test.py index 53c1f309b..868f3e85c 100644 --- a/packages/genkit-middleware/tests/skills_test.py +++ b/packages/genkit-middleware/tests/skills_test.py @@ -182,10 +182,10 @@ async def test_skills_unknown_name_lists_available_skills(tmp_path, ctx) -> None tool = skills.tools(ctx)[0] unknown = await tool(input={'skill_name': 'missing'}) - assert unknown == 'Unknown skill "missing". Available skills: poetry, zebra' + assert unknown.output == 'Unknown skill "missing". Available skills: poetry, zebra' known = await tool(input={'skill_name': 'poetry'}) - assert known == 'Write a poem.' + assert known.output == 'Write a poem.' @pytest.mark.asyncio @@ -374,10 +374,11 @@ async def test_use_skill_unknown_error_escapes_tags_and_matches_catalog_text( skills = Skills(skill_paths=[str(tmp_path)]) (tool,) = skills.tools(ctx) - assert await tool({'skill_name': 'a<skills>'}) == 'Tagged instructions.\n' - assert await tool({'skill_name': 'b<123'}) == 'Entity instructions.\n' + assert (await tool({'skill_name': 'a<skills>'})).output == 'Tagged instructions.\n' + assert (await tool({'skill_name': 'b<123'})).output == 'Entity instructions.\n' - err = await tool({'skill_name': 'inject'}) + err = (await tool({'skill_name': 'inject'})).output + assert isinstance(err, str) assert '' not in err assert '' not in err assert '' not in err diff --git a/packages/genkit-otel/src/genkit_otel/_genai_instrumentation.py b/packages/genkit-otel/src/genkit_otel/_genai_instrumentation.py index d2b3753f3..1df1f2099 100644 --- a/packages/genkit-otel/src/genkit_otel/_genai_instrumentation.py +++ b/packages/genkit-otel/src/genkit_otel/_genai_instrumentation.py @@ -189,7 +189,7 @@ async def run_in_new_span( kind = metadata.action_type if kind == 'model': return await self._run_model_span(metadata, next) - # generate runs 'tool'; the Dev UI runs the 'tool.v2' envelope. + # Tools run as 'tool.v2' (and legacy 'tool' actions registered by other code). if kind in ('tool', 'tool.v2') and self.emit_tool_spans: return await self._run_tool_span(metadata, next) return await self._run_generic_span(metadata, next) diff --git a/packages/genkit/src/genkit/_ai/_aio.py b/packages/genkit/src/genkit/_ai/_aio.py index 1908ab403..f9be3cb36 100644 --- a/packages/genkit/src/genkit/_ai/_aio.py +++ b/packages/genkit/src/genkit/_ai/_aio.py @@ -135,6 +135,7 @@ ModelConfigDict, ModelRef, ModelRequest, + MultipartToolResponse, Part, ToolChoice, ) @@ -530,7 +531,16 @@ def tool( ) -> _ToolDecorator: ... # Same order as Genkit.flow: the `object` shapes catch `(ctx, x: Any)` and - # `(x: Any)` / `(x: object)` before a ctx shape can claim them. + # `(x: Any)` / `(x: object)` before a ctx shape can claim them. Each shape + # matches `MultipartToolResponse[OutputT]` before plain `OutputT` so a + # multipart handler does not double-wrap. + @overload + def tool( + self, + func: Callable[[ToolContext[ChunkT], object], Coroutine[Any, Any, MultipartToolResponse[OutputT]]], + /, + ) -> Tool[Any, OutputT, ChunkT]: ... + @overload def tool( self, @@ -538,6 +548,13 @@ def tool( /, ) -> Tool[Any, OutputT, ChunkT]: ... + @overload + def tool( + self, + func: DefaultInputCtxFn[ToolContext[ChunkT], InputT, MultipartToolResponse[OutputT]], + /, + ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... + @overload def tool( self, @@ -545,6 +562,13 @@ def tool( /, ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... + @overload + def tool( + self, + func: Callable[[InputT, ToolContext[ChunkT]], Coroutine[Any, Any, MultipartToolResponse[OutputT]]], + /, + ) -> Tool[InputT, OutputT, ChunkT]: ... + @overload def tool( self, @@ -552,6 +576,13 @@ def tool( /, ) -> Tool[InputT, OutputT, ChunkT]: ... + @overload + def tool( + self, + func: CtxDefaultInputFn[ToolContext[ChunkT], InputT, MultipartToolResponse[OutputT]], + /, + ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... + @overload def tool( self, @@ -559,6 +590,13 @@ def tool( /, ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... + @overload + def tool( + self, + func: Callable[[ToolContext[ChunkT], InputT], Coroutine[Any, Any, MultipartToolResponse[OutputT]]], + /, + ) -> Tool[InputT, OutputT, ChunkT]: ... + @overload def tool( self, @@ -566,6 +604,13 @@ def tool( /, ) -> Tool[InputT, OutputT, ChunkT]: ... + @overload + def tool( + self, + func: Callable[[object], Coroutine[Any, Any, MultipartToolResponse[OutputT]]], + /, + ) -> Tool[Any, OutputT]: ... + @overload def tool( self, @@ -573,6 +618,13 @@ def tool( /, ) -> Tool[Any, OutputT]: ... + @overload + def tool( + self, + func: Callable[[ToolContext[ChunkT]], Coroutine[Any, Any, MultipartToolResponse[OutputT]]], + /, + ) -> Tool[None, OutputT, ChunkT]: ... + @overload def tool( self, @@ -580,6 +632,13 @@ def tool( /, ) -> Tool[None, OutputT, ChunkT]: ... + @overload + def tool( + self, + func: DefaultInputFn[InputT, MultipartToolResponse[OutputT]], + /, + ) -> DefaultedTool[InputT, OutputT]: ... + @overload def tool( self, @@ -587,6 +646,13 @@ def tool( /, ) -> DefaultedTool[InputT, OutputT]: ... + @overload + def tool( + self, + func: Callable[[InputT], Coroutine[Any, Any, MultipartToolResponse[OutputT]]], + /, + ) -> Tool[InputT, OutputT]: ... + @overload def tool( self, @@ -594,6 +660,13 @@ def tool( /, ) -> Tool[InputT, OutputT]: ... + @overload + def tool( + self, + func: Callable[[], Coroutine[Any, Any, MultipartToolResponse[OutputT]]], + /, + ) -> Tool[None, OutputT]: ... + @overload def tool( self, @@ -613,8 +686,10 @@ def tool( Can be used bare (``@ai.tool``) or with arguments (``@ai.tool()``, ``@ai.tool('custom_name', description='...')``). - The return annotation is what the model binds as ``outputSchema``. - Awaiting the tool directly returns what the function returned. + The return annotation is what the model and manifest bind as + ``outputSchema``. Awaiting the tool directly returns a + ``MultipartToolResponse[T]`` (a plain ``return value`` becomes + ``MultipartToolResponse(output=value)``). A tool takes at most one input, and that input's type is the schema the model fills in. For several fields, use one Pydantic model. To read the @@ -934,7 +1009,9 @@ async def menu_price(dish: str) -> float: # => The ramen is $14.50. ``` """ - action = await self._registry.resolve_action(ActionKind.TOOL, name) + action = await self._registry.resolve_action(ActionKind.TOOL_V2, name) + if action is None: + action = await self._registry.resolve_action(ActionKind.TOOL, name) if action is None: return None return Tool.from_action(action) diff --git a/packages/genkit/src/genkit/_ai/_decorators.py b/packages/genkit/src/genkit/_ai/_decorators.py index fae88e8ca..10661237b 100644 --- a/packages/genkit/src/genkit/_ai/_decorators.py +++ b/packages/genkit/src/genkit/_ai/_decorators.py @@ -18,7 +18,7 @@ from __future__ import annotations -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Coroutine from typing import Any, TypeVar, overload from pydantic import BaseModel @@ -26,6 +26,7 @@ from genkit._ai._tools import define_tool from genkit._core._action import CtxDefaultInputFn, DefaultInputCtxFn, DefaultInputFn, FlowContext from genkit._core._flow import DefaultedFlow, Flow, define_flow +from genkit._core._model import MultipartToolResponse from genkit._core._registry import Registry from genkit._core._tool import DefaultedTool, Tool, ToolContext @@ -101,7 +102,7 @@ def __call__(self, func: Callable[..., Awaitable[Any]]) -> Flow[Any, Any, Any]: class _ToolDecorator: - """Decorator class for tool registration, typed so ``await tool(...)`` returns the function's own type.""" + """Decorator for tool registration where ``await tool(...)`` returns ``MultipartToolResponse[OutputT]``.""" def __init__( self, @@ -116,44 +117,96 @@ def __init__( self._input_schema = input_schema # Same order as define_tool's overloads: context-only before input-only, - # since a ``ctx`` function also fits ``[InputT]``. + # since a ``ctx`` function also fits ``[InputT]``, and + # ``MultipartToolResponse[OutputT]`` before plain ``OutputT`` so a + # multipart handler does not double-wrap. + @overload + def __call__( + self, func: Callable[[ToolContext[ChunkT], object], Coroutine[Any, Any, MultipartToolResponse[OutputT]]] + ) -> Tool[Any, OutputT, ChunkT]: ... + @overload def __call__( self, func: Callable[[ToolContext[ChunkT], object], Awaitable[OutputT]] ) -> Tool[Any, OutputT, ChunkT]: ... + @overload + def __call__( + self, func: DefaultInputCtxFn[ToolContext[ChunkT], InputT, MultipartToolResponse[OutputT]] + ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... + @overload def __call__( self, func: DefaultInputCtxFn[ToolContext[ChunkT], InputT, OutputT] ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... + @overload + def __call__( + self, func: Callable[[InputT, ToolContext[ChunkT]], Coroutine[Any, Any, MultipartToolResponse[OutputT]]] + ) -> Tool[InputT, OutputT, ChunkT]: ... + @overload def __call__( self, func: Callable[[InputT, ToolContext[ChunkT]], Awaitable[OutputT]] ) -> Tool[InputT, OutputT, ChunkT]: ... + @overload + def __call__( + self, func: CtxDefaultInputFn[ToolContext[ChunkT], InputT, MultipartToolResponse[OutputT]] + ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... + @overload def __call__( self, func: CtxDefaultInputFn[ToolContext[ChunkT], InputT, OutputT] ) -> DefaultedTool[InputT, OutputT, ChunkT]: ... + @overload + def __call__( + self, func: Callable[[ToolContext[ChunkT], InputT], Coroutine[Any, Any, MultipartToolResponse[OutputT]]] + ) -> Tool[InputT, OutputT, ChunkT]: ... + @overload def __call__( self, func: Callable[[ToolContext[ChunkT], InputT], Awaitable[OutputT]] ) -> Tool[InputT, OutputT, ChunkT]: ... + @overload + def __call__( + self, func: Callable[[object], Coroutine[Any, Any, MultipartToolResponse[OutputT]]] + ) -> Tool[Any, OutputT]: ... + @overload def __call__(self, func: Callable[[object], Awaitable[OutputT]]) -> Tool[Any, OutputT]: ... + @overload + def __call__( + self, func: Callable[[ToolContext[ChunkT]], Coroutine[Any, Any, MultipartToolResponse[OutputT]]] + ) -> Tool[None, OutputT, ChunkT]: ... + @overload def __call__(self, func: Callable[[ToolContext[ChunkT]], Awaitable[OutputT]]) -> Tool[None, OutputT, ChunkT]: ... + @overload + def __call__( + self, func: DefaultInputFn[InputT, MultipartToolResponse[OutputT]] + ) -> DefaultedTool[InputT, OutputT]: ... + @overload def __call__(self, func: DefaultInputFn[InputT, OutputT]) -> DefaultedTool[InputT, OutputT]: ... + @overload + def __call__( + self, func: Callable[[InputT], Coroutine[Any, Any, MultipartToolResponse[OutputT]]] + ) -> Tool[InputT, OutputT]: ... + @overload def __call__(self, func: Callable[[InputT], Awaitable[OutputT]]) -> Tool[InputT, OutputT]: ... + @overload + def __call__( + self, func: Callable[[], Coroutine[Any, Any, MultipartToolResponse[OutputT]]] + ) -> Tool[None, OutputT]: ... + @overload def __call__(self, func: Callable[[], Awaitable[OutputT]]) -> Tool[None, OutputT]: ... diff --git a/packages/genkit/src/genkit/_ai/_generate.py b/packages/genkit/src/genkit/_ai/_generate.py index 0bc3ec25a..311fdf22c 100644 --- a/packages/genkit/src/genkit/_ai/_generate.py +++ b/packages/genkit/src/genkit/_ai/_generate.py @@ -46,7 +46,6 @@ resolve_model_name, ) from genkit._ai._tools import ( - ORIGINAL_OUTPUT_SCHEMA_KEY, Interrupt, as_multipart_tool_response, dump_tool_metadata, @@ -701,7 +700,7 @@ async def register_tools(registry: Registry, tools: Sequence[str | Tool] | None) continue # If the same action is already reachable through the parent chain, # skip — re-registering would either no-op or trigger a duplicate. - resolved = await registry.resolve_action(ActionKind.TOOL, t.name) + resolved = await registry.resolve_action(t.kind, t.name) if resolved is t: continue registry.register_action_from_instance(t) @@ -2466,17 +2465,11 @@ async def to_model_request( def to_tool_definition(tool: Action) -> ToolDefinition: """Convert an Action to a ToolDefinition for model requests.""" - metadata = tool.metadata or {} - if ORIGINAL_OUTPUT_SCHEMA_KEY in metadata: - original = metadata[ORIGINAL_OUTPUT_SCHEMA_KEY] - output_schema = original if isinstance(original, dict) else None - else: - output_schema = tool.output_schema return ToolDefinition( name=tool.name, description=tool.description or '', input_schema=tool.input_schema, - output_schema=output_schema, + output_schema=tool.output_schema, ) @@ -2741,10 +2734,10 @@ def interrupt_request_part(trp: Part, intr: Interrupt) -> Part: async def resolve_tool(registry: Registry, tool_ref: str | Tool) -> Action: """Resolve a tool already on the registry. - Catalog keys (``/tool/name``, ``/tool.v2/name``) and bare registered - names. A bare name prefers the ``tool`` action and falls back to - ``tool.v2``, like JS. DAP selectors (``mcp:tool/echo``) are bound in - expand, not here. + Catalog keys (``/tool.v2/name``, ``/tool/name``) and bare registered + names. A bare name prefers the ``tool.v2`` action and falls back to + ``tool`` for actions registered by other code. DAP selectors + (``mcp:tool/echo``) are bound in expand, not here. """ if isinstance(tool_ref, Tool): return tool_ref @@ -2776,9 +2769,9 @@ async def resolve_tool(registry: Registry, tool_ref: str | Tool) -> Action: if kind is not None: tool = await registry.resolve_action(kind=kind, name=name) else: - tool = await registry.resolve_action(kind=ActionKind.TOOL, name=name) + tool = await registry.resolve_action(kind=ActionKind.TOOL_V2, name=name) if tool is None: - tool = await registry.resolve_action(kind=ActionKind.TOOL_V2, name=name) + tool = await registry.resolve_action(kind=ActionKind.TOOL, name=name) if tool is None: raise GenkitError( status='NOT_FOUND', diff --git a/packages/genkit/src/genkit/_ai/_tools.py b/packages/genkit/src/genkit/_ai/_tools.py index 78787a854..d2d856ee3 100644 --- a/packages/genkit/src/genkit/_ai/_tools.py +++ b/packages/genkit/src/genkit/_ai/_tools.py @@ -16,7 +16,7 @@ """Tool registration, interruption, and request execution helpers for the Genkit framework.""" -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Coroutine from typing import Any, NoReturn, TypeVar, cast, overload from pydantic import BaseModel, ValidationError @@ -42,7 +42,6 @@ ) from genkit._core._registry import Registry from genkit._core._tool import ( - ORIGINAL_OUTPUT_SCHEMA_KEY as ORIGINAL_OUTPUT_SCHEMA_KEY, DefaultedTool, Tool as _Tool, ToolContext as ToolContext, @@ -265,7 +264,7 @@ def _define_tool( *, input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> _Tool[Any, Any, Any]: - """Build a tool and register it (``/tool/`` and its ``/tool.v2/`` envelope). + """Build a tool and register it under ``/tool.v2/``. The return annotation is what the model binds. ``input_schema=`` is for cases like define_interrupt where the handler signature cannot express @@ -273,7 +272,7 @@ def _define_tool( """ # A defaulted input builds a DefaultedTool, so isinstance agrees with # what define_tool's overloads promise. - cls = DefaultedTool if input_has_default(func, ActionKind.TOOL) else _Tool + cls = DefaultedTool if input_has_default(func, ActionKind.TOOL_V2) else _Tool built: _Tool[Any, Any, Any] = cls(func, name=name, description=description, input_schema=input_schema) registry.register_action_from_instance(built) return built @@ -291,6 +290,19 @@ def _define_tool( # Any arguments makes it ambiguous, and no order fixes that. # - A defaulted input returns ``DefaultedTool``. ``(x = ..., ctx = None)`` # also fits ``[InputT, ToolContext]``, so its shape comes before that one. +# - Each shape matches ``-> MultipartToolResponse[T]`` before plain ``-> T`` +# so ``OutputT`` is not double-wrapped. +@overload +def define_tool( + registry: Registry, + func: Callable[[ToolContext[ToolChunkT], object], Coroutine[Any, Any, MultipartToolResponse[ToolOutputT]]], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> _Tool[Any, ToolOutputT, ToolChunkT]: ... + + @overload def define_tool( registry: Registry, @@ -302,6 +314,17 @@ def define_tool( ) -> _Tool[Any, ToolOutputT, ToolChunkT]: ... +@overload +def define_tool( + registry: Registry, + func: DefaultInputCtxFn[ToolContext[ToolChunkT], ToolInputT, MultipartToolResponse[ToolOutputT]], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> DefaultedTool[ToolInputT, ToolOutputT, ToolChunkT]: ... + + @overload def define_tool( registry: Registry, @@ -313,6 +336,17 @@ def define_tool( ) -> DefaultedTool[ToolInputT, ToolOutputT, ToolChunkT]: ... +@overload +def define_tool( + registry: Registry, + func: Callable[[ToolInputT, ToolContext[ToolChunkT]], Coroutine[Any, Any, MultipartToolResponse[ToolOutputT]]], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> _Tool[ToolInputT, ToolOutputT, ToolChunkT]: ... + + @overload def define_tool( registry: Registry, @@ -324,6 +358,17 @@ def define_tool( ) -> _Tool[ToolInputT, ToolOutputT, ToolChunkT]: ... +@overload +def define_tool( + registry: Registry, + func: CtxDefaultInputFn[ToolContext[ToolChunkT], ToolInputT, MultipartToolResponse[ToolOutputT]], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> DefaultedTool[ToolInputT, ToolOutputT, ToolChunkT]: ... + + @overload def define_tool( registry: Registry, @@ -335,6 +380,17 @@ def define_tool( ) -> DefaultedTool[ToolInputT, ToolOutputT, ToolChunkT]: ... +@overload +def define_tool( + registry: Registry, + func: Callable[[ToolContext[ToolChunkT], ToolInputT], Coroutine[Any, Any, MultipartToolResponse[ToolOutputT]]], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> _Tool[ToolInputT, ToolOutputT, ToolChunkT]: ... + + @overload def define_tool( registry: Registry, @@ -346,6 +402,17 @@ def define_tool( ) -> _Tool[ToolInputT, ToolOutputT, ToolChunkT]: ... +@overload +def define_tool( + registry: Registry, + func: Callable[[object], Coroutine[Any, Any, MultipartToolResponse[ToolOutputT]]], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> _Tool[Any, ToolOutputT]: ... + + @overload def define_tool( registry: Registry, @@ -357,6 +424,17 @@ def define_tool( ) -> _Tool[Any, ToolOutputT]: ... +@overload +def define_tool( + registry: Registry, + func: Callable[[ToolContext[ToolChunkT]], Coroutine[Any, Any, MultipartToolResponse[ToolOutputT]]], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> _Tool[None, ToolOutputT, ToolChunkT]: ... + + @overload def define_tool( registry: Registry, @@ -368,6 +446,17 @@ def define_tool( ) -> _Tool[None, ToolOutputT, ToolChunkT]: ... +@overload +def define_tool( + registry: Registry, + func: DefaultInputFn[ToolInputT, MultipartToolResponse[ToolOutputT]], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> DefaultedTool[ToolInputT, ToolOutputT]: ... + + @overload def define_tool( registry: Registry, @@ -379,6 +468,17 @@ def define_tool( ) -> DefaultedTool[ToolInputT, ToolOutputT]: ... +@overload +def define_tool( + registry: Registry, + func: Callable[[ToolInputT], Coroutine[Any, Any, MultipartToolResponse[ToolOutputT]]], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> _Tool[ToolInputT, ToolOutputT]: ... + + @overload def define_tool( registry: Registry, @@ -390,6 +490,17 @@ def define_tool( ) -> _Tool[ToolInputT, ToolOutputT]: ... +@overload +def define_tool( + registry: Registry, + func: Callable[[], Coroutine[Any, Any, MultipartToolResponse[ToolOutputT]]], + name: str | None = None, + description: str | None = None, + *, + input_schema: type[BaseModel] | dict[str, object] | None = None, +) -> _Tool[None, ToolOutputT]: ... + + @overload def define_tool( registry: Registry, @@ -409,12 +520,11 @@ def define_tool( *, input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> _Tool[Any, Any, Any]: - """Register a function as a tool. + """Register a function as a ``tool.v2`` action. - The model sees the handler's return annotation as ``outputSchema``. - ``await tool(x)`` returns what the function returned. The registry also - stores ``/tool.v2/``, which returns the ``MultipartToolResponse`` - envelope; that's the one the Dev UI runs. + The model and manifest see the handler's declared return annotation as + ``outputSchema``. ``await tool(x)`` returns a ``MultipartToolResponse[T]``; + a plain ``return value`` becomes ``MultipartToolResponse(output=value)``. Args: registry: The registry to register the tool in. diff --git a/packages/genkit/src/genkit/_core/_action.py b/packages/genkit/src/genkit/_core/_action.py index ef80e8512..7d1b5e5a0 100644 --- a/packages/genkit/src/genkit/_core/_action.py +++ b/packages/genkit/src/genkit/_core/_action.py @@ -26,7 +26,7 @@ import sys import time import types -from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable, Iterator, Mapping, Sequence +from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Callable, Coroutine, Iterator, Mapping, Sequence from contextlib import contextmanager from contextvars import ContextVar, copy_context from dataclasses import dataclass @@ -198,10 +198,9 @@ class ActionKind(StrEnum): FLOW = 'flow' MODEL = 'model' PROMPT = 'prompt' - # A tool: run returns what the function returned. Generate runs this one. + # Legacy v1 tool kind, kept as a lookup fallback for actions registered by other code. TOOL = 'tool' - # The same tool returning the MultipartToolResponse envelope. The Dev UI - # lists and runs this one when both exist (same as JS and Go). + # Tool action returning the MultipartToolResponse envelope (matches Dart and JS v2). TOOL_V2 = 'tool.v2' UTIL = 'util' @@ -889,7 +888,7 @@ class DefaultInputFn(Protocol[_FnInputT_contra, _FnOutputT_co]): type-check while ``await create_invoice()`` on a required input doesn't. """ - def __call__(self, input: _FnInputT_contra = ..., /) -> Awaitable[_FnOutputT_co]: ... # noqa: A002 + def __call__(self, input: _FnInputT_contra = ..., /) -> Coroutine[Any, Any, _FnOutputT_co]: ... # noqa: A002 class CtxDefaultInputFn(Protocol[_FnCtxT_contra, _FnInputT_contra, _FnOutputT_co]): @@ -900,7 +899,7 @@ def __call__( ctx: _FnCtxT_contra, input: _FnInputT_contra = ..., # noqa: A002 /, - ) -> Awaitable[_FnOutputT_co]: ... + ) -> Coroutine[Any, Any, _FnOutputT_co]: ... class DefaultInputCtxFn(Protocol[_FnCtxT_contra, _FnInputT_contra, _FnOutputT_co]): @@ -916,7 +915,7 @@ def __call__( input: _FnInputT_contra = ..., # noqa: A002 ctx: _FnCtxT_contra = ..., /, - ) -> Awaitable[_FnOutputT_co]: ... + ) -> Coroutine[Any, Any, _FnOutputT_co]: ... # Generic streaming callback - use Callable[[ChunkT], None] for typed chunks @@ -1138,8 +1137,8 @@ def _context_cls_for_kind(kind: ActionKind) -> type[ActionContext[Any]]: return EmbedContext # Tools and agents wrap or replace this base context in the AI layer: # call_tool_fn wraps it into ToolContext (adding resumed_metadata and - # original_input) for both the tool and its tool.v2 envelope, and - # BidiAction hands init/stream to AgentRuntime.run, which builds AgentContext. + # original_input), and BidiAction hands init/stream to AgentRuntime.run, + # which builds AgentContext. if kind in (ActionKind.TOOL, ActionKind.TOOL_V2, ActionKind.AGENT, ActionKind.CUSTOM): return ActionContext return FlowContext diff --git a/packages/genkit/src/genkit/_core/_reflection.py b/packages/genkit/src/genkit/_core/_reflection.py index b104bcae6..63b67814d 100644 --- a/packages/genkit/src/genkit/_core/_reflection.py +++ b/packages/genkit/src/genkit/_core/_reflection.py @@ -166,7 +166,7 @@ async def execute(self) -> None: init=init, ) result = ( - output.response.model_dump(by_alias=True, exclude_none=True) + output.response.model_dump(by_alias=True, exclude_none=True, mode='json') if isinstance(output.response, BaseModel) else output.response ) diff --git a/packages/genkit/src/genkit/_core/_reflection_v2.py b/packages/genkit/src/genkit/_core/_reflection_v2.py index 30a0b60a2..738b9e5ea 100644 --- a/packages/genkit/src/genkit/_core/_reflection_v2.py +++ b/packages/genkit/src/genkit/_core/_reflection_v2.py @@ -498,7 +498,7 @@ async def notify_stream_chunk(self, sid: str, chunk: object) -> None: @staticmethod def run_action_success_body(result: object, trace_id: str | None) -> dict[str, Any]: if isinstance(result, BaseModel): - result_body = result.model_dump(by_alias=True, exclude_none=True) + result_body = result.model_dump(by_alias=True, exclude_none=True, mode='json') else: result_body = result body: dict[str, Any] = {'result': result_body} diff --git a/packages/genkit/src/genkit/_core/_registry.py b/packages/genkit/src/genkit/_core/_registry.py index 17b1c08d6..66eb86e1e 100644 --- a/packages/genkit/src/genkit/_core/_registry.py +++ b/packages/genkit/src/genkit/_core/_registry.py @@ -55,7 +55,6 @@ ) from genkit._core._operation import Operation from genkit._core._plugin import Plugin, resolved_action_name -from genkit._core._tool import Tool from genkit._core._typing import ActionMetadata, EmbedResponse, EvalResponse, EvaluatorRequest logger = get_logger(__name__) @@ -345,16 +344,11 @@ def register_action_from_instance(self, action: Action) -> None: self._store_locked(action, action.name) def _store_locked(self, action: Action, name: str) -> None: - """Store ``action`` under ``name``; a Tool also stores its ``tool.v2`` envelope action. + """Store ``action`` under ``name``. Caller holds ``self._lock``. """ self._entries.setdefault(action.kind, {})[name] = action - wire = action.wire_action if isinstance(action, Tool) else None - if wire is not None: - # Keep the envelope action's name in step with a namespaced tool. - set_action_name(wire, name) - self._entries.setdefault(wire.kind, {})[name] = wire def registered_action(self, kind: ActionKind, name: str) -> Action | None: """Return an action that is already in this registry. @@ -436,8 +430,7 @@ async def list_actions( key = f'/{meta.action_type}/{name}' catalog[key] = meta.model_copy(update={'key': key, 'name': name}) - # 2. Concrete registered actions. A local tool is ``/tool/`` plus its - # ``/tool.v2/`` envelope; the Dev UI shows the ``tool.v2`` row. + # 2. Concrete registered actions (tools live at ``/tool.v2/``). for kind in ActionKind.__members__.values(): for name, action in (await self.resolve_actions_by_kind(kind)).items(): key = create_action_key(kind, name) @@ -686,7 +679,13 @@ async def _resolve_dap_qualified_action(self, kind: ActionKind, name: str) -> Ac resolved = await dap.get_action(qualified.inner_kind, qualified.inner_name) except Exception as e: raise ValueError(f'Dynamic action provider {dap_host!r} get_action failed for {kind} {name!r}') from e - if resolved is not None and resolved.kind == kind: + if resolved is not None and ( + resolved.kind == kind + or ( + kind in (ActionKind.TOOL, ActionKind.TOOL_V2) + and resolved.kind in (ActionKind.TOOL, ActionKind.TOOL_V2) + ) + ): return resolved if resolved is None: raise ValueError( diff --git a/packages/genkit/src/genkit/_core/_tool.py b/packages/genkit/src/genkit/_core/_tool.py index dfa8ae42a..bce92fb96 100644 --- a/packages/genkit/src/genkit/_core/_tool.py +++ b/packages/genkit/src/genkit/_core/_tool.py @@ -19,12 +19,12 @@ from __future__ import annotations import inspect -from collections.abc import Awaitable, Callable +from collections.abc import Awaitable, Callable, Coroutine from contextvars import ContextVar from types import UnionType -from typing import Any, Union, cast, get_args, get_origin, overload +from typing import Any, Generic, Union, cast, get_args, get_origin, overload -from pydantic import BaseModel, TypeAdapter +from pydantic import BaseModel, TypeAdapter, ValidationError from typing_extensions import TypeVar from genkit._core._action import ( @@ -36,6 +36,7 @@ DefaultInputCtxFn, DefaultInputFn, get_func_description, + json_schema_for, resolve_type_hints, ) from genkit._core._error import ErrorReason, GenkitError @@ -49,7 +50,6 @@ live_payload_error as live_payload_error, wire_part_is_live as wire_part_is_live, ) -from genkit._core._schema import to_json_schema from genkit._core._telemetry._instrumentation import set_custom_metadata_attributes from genkit._core._typing import MultipartToolResponse as MultipartToolResponseData, ToolDefinition @@ -63,10 +63,6 @@ _O = TypeVar('_O') _C = TypeVar('_C') -# Metadata key for the schema the model binds as the tool's ``outputSchema``. -# For ``-> MultipartToolResponse[T]`` that's ``T``; for ``-> T`` it's ``T``. -ORIGINAL_OUTPUT_SCHEMA_KEY = 'originalOutputSchema' - # Context variables for propagating resumed metadata to tools. _tool_resumed_metadata: ContextVar[dict[str, Any] | None] = ContextVar('tool_resumed_metadata', default=None) # Stashed copy of tool_request.input when restart replaces input (JSON; shape is per tool). @@ -141,20 +137,6 @@ def envelope_output_type(ret: object) -> object: return NOT_ENVELOPE -def model_schema_from_return_annotation( - func: Callable[..., Any], - *, - inferred: dict[str, object] | None, -) -> dict[str, object] | None: - """JSON Schema the model should bind, from the handler's return annotation.""" - inner = envelope_output_type(resolve_type_hints(func).get('return')) - if inner is NOT_ENVELOPE: - return inferred - if inner is Any or inner is object: - return None - return to_json_schema(cast(type | dict[str, Any] | str, inner)) - - class ToolContext(ActionContext[ChunkT]): """What a tool sees while it runs: request context, streaming, and resume state. @@ -226,15 +208,11 @@ def is_resumed(self) -> bool: async def call_tool_fn( tool: Action[Any, Any, Any, Any], - func: Callable[..., Awaitable[OutputT]], + func: Callable[..., Awaitable[Any]], raw_input: object, ctx: ActionContext[Any], -) -> OutputT: - """Call a tool function with a ``ToolContext`` carrying resume state. - - Both the ``tool`` action and its ``tool.v2`` envelope action run the - function through here, so resume metadata reaches it either way. - """ +) -> object: + """Call a tool function with a ``ToolContext`` carrying resume state.""" resumed_meta = _tool_resumed_metadata.get() # A bare restart() resumes with {}; it is still a resume. if resumed_meta is not None: @@ -247,22 +225,34 @@ async def call_tool_fn( return await tool.params.call(func, raw_input, tool_ctx) -class Tool(Action[InputT, OutputT, ChunkT, None]): - """A tool the model can call: an :class:`~genkit._core._action.Action` of kind ``tool``. +class Tool(Action[InputT, MultipartToolResponse[OutputT], ChunkT, None], Generic[InputT, OutputT, ChunkT]): + """A tool the model can call: an :class:`~genkit._core._action.Action` of kind ``tool.v2``. - ``await tool(x)`` is ``(await tool.run(x)).response``: what the function - returned. A ``str`` comes back as the string, a Pydantic model as the - instance, and ``response(...)`` as that ``MultipartToolResponse``. + ``await tool(x)`` returns a :class:`~genkit.MultipartToolResponse` envelope + carrying the structured ``output`` (parsed against the declared return type + ``T``) plus optional multipart ``content`` and ``metadata``. A plain + ``return value`` from the handler becomes ``MultipartToolResponse(output=value)``. - Each tool also carries a ``tool.v2`` action that returns the - ``MultipartToolResponse`` envelope. The registry stores both, like JS and - Go; the Dev UI lists and runs the ``tool.v2`` one. + The action manifest's ``output_schema`` (and ``tool.definition().output_schema``) + advertises the declared schema ``T``, not the envelope wrapper. """ - _wire_action: Action[InputT, MultipartToolResponse[Any], ChunkT, None] | None + _declared_output_type: TypeAdapter[Any] | None # One overload per handler shape, same as ``ai.tool`` / ``define_tool``, so # ``Tool(place_order)`` infers ``Tool[Order, Receipt, Step]`` from the function. + # Each shape matches ``-> MultipartToolResponse[_O]`` before plain ``-> _O`` + # so a multipart handler does not double-wrap ``OutputT``. + @overload + def __init__( + self: Tool[Any, _O, _C], + func: Callable[[ToolContext[_C], object], Coroutine[Any, Any, MultipartToolResponse[_O]]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + @overload def __init__( self: Tool[Any, _O, _C], @@ -276,6 +266,16 @@ def __init__( # The defaulted-input shapes are self-typed to DefaultedTool, so they # apply when define_tool builds one. Tool(fn) itself stays a Tool and # skips them. `(x = ..., ctx = None)` also fits (input, ctx); catch it first. + @overload + def __init__( + self: DefaultedTool[_I, _O, _C], + func: DefaultInputCtxFn[ToolContext[_C], _I, MultipartToolResponse[_O]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + @overload def __init__( self: DefaultedTool[_I, _O, _C], @@ -286,6 +286,16 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + @overload + def __init__( + self: Tool[_I, _O, _C], + func: Callable[[_I, ToolContext[_C]], Coroutine[Any, Any, MultipartToolResponse[_O]]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + @overload def __init__( self: Tool[_I, _O, _C], @@ -296,6 +306,16 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + @overload + def __init__( + self: DefaultedTool[_I, _O, _C], + func: CtxDefaultInputFn[ToolContext[_C], _I, MultipartToolResponse[_O]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + @overload def __init__( self: DefaultedTool[_I, _O, _C], @@ -306,6 +326,16 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + @overload + def __init__( + self: Tool[_I, _O, _C], + func: Callable[[ToolContext[_C], _I], Coroutine[Any, Any, MultipartToolResponse[_O]]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + @overload def __init__( self: Tool[_I, _O, _C], @@ -316,6 +346,16 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + @overload + def __init__( + self: Tool[Any, _O, Any], + func: Callable[[object], Coroutine[Any, Any, MultipartToolResponse[_O]]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + @overload def __init__( self: Tool[Any, _O, Any], @@ -326,6 +366,16 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + @overload + def __init__( + self: Tool[None, _O, _C], + func: Callable[[ToolContext[_C]], Coroutine[Any, Any, MultipartToolResponse[_O]]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + @overload def __init__( self: Tool[None, _O, _C], @@ -336,6 +386,16 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + @overload + def __init__( + self: DefaultedTool[_I, _O, Any], + func: DefaultInputFn[_I, MultipartToolResponse[_O]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + @overload def __init__( self: DefaultedTool[_I, _O, Any], @@ -346,6 +406,16 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + @overload + def __init__( + self: Tool[_I, _O, Any], + func: Callable[[_I], Coroutine[Any, Any, MultipartToolResponse[_O]]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + @overload def __init__( self: Tool[_I, _O, Any], @@ -356,6 +426,16 @@ def __init__( input_schema: type[BaseModel] | dict[str, object] | None = None, ) -> None: ... + @overload + def __init__( + self: Tool[None, _O, Any], + func: Callable[[], Coroutine[Any, Any, MultipartToolResponse[_O]]], + *, + name: str | None = None, + description: str | None = None, + input_schema: type[BaseModel] | dict[str, object] | None = None, + ) -> None: ... + @overload def __init__( self: Tool[None, _O, Any], @@ -408,73 +488,54 @@ async def lookup_price(sku: str) -> str: if tool_name is None: raise ValueError(f'Cannot infer a tool name from {func!r}; pass name= explicitly.') tool_description = get_func_description(func, description) - typed_func: Callable[..., Awaitable[OutputT]] = func - self._wire_action = None - async def tool_fn(raw_input: object, ctx: ActionContext[Any]) -> OutputT: - return await call_tool_fn(self, typed_func, raw_input, ctx) + async def tool_fn(raw_input: object, ctx: ActionContext[Any]) -> MultipartToolResponse[OutputT]: + raw = await call_tool_fn(self, func, raw_input, ctx) + return cast(MultipartToolResponse[OutputT], raw) super().__init__( - kind=ActionKind.TOOL, + kind=ActionKind.TOOL_V2, name=tool_name, fn=tool_fn, metadata_fn=func, description=tool_description, input_schema=input_schema, ) - model_schema = model_schema_from_return_annotation(func, inferred=self.output_schema) - self.metadata[ORIGINAL_OUTPUT_SCHEMA_KEY] = model_schema - async def wire_fn(raw_input: object, ctx: ActionContext[Any]) -> MultipartToolResponse[Any]: - raw = await call_tool_fn(self, typed_func, raw_input, ctx) - return as_multipart_tool_response(raw, tool_name=self.name) + inner = envelope_output_type(resolve_type_hints(func).get('return')) + if inner is NOT_ENVELOPE: + self._declared_output_type = self._output_type + elif inner is Any or inner is object: + self._declared_output_type = None + self._set_output_schema(None) + else: + output_adapter, output_schema = json_schema_for( + inner, + kind=self._kind, + name=self._name, + label='output', + ) + self._declared_output_type = output_adapter + self._set_output_schema(output_schema) - wire: Action[InputT, MultipartToolResponse[Any], ChunkT, None] = Action( - kind=ActionKind.TOOL_V2, - name=tool_name, - fn=wire_fn, - metadata_fn=func, - description=tool_description, - input_schema=input_schema, - ) - wire.output_schema = TypeAdapter(MultipartToolResponseData).json_schema() - wire.metadata[ORIGINAL_OUTPUT_SCHEMA_KEY] = model_schema - self._wire_action = wire + @overload + @classmethod + def from_action(cls, action: Tool[InputT, OutputT, ChunkT]) -> Tool[InputT, OutputT, ChunkT]: ... + @overload @classmethod - def from_action(cls, action: Action[InputT, OutputT, ChunkT, Any]) -> Tool[InputT, OutputT, ChunkT]: + def from_action(cls, action: Action[InputT, Any, ChunkT, Any]) -> Tool[InputT, Any, ChunkT]: ... + + @classmethod + def from_action(cls, action: Action[InputT, Any, ChunkT, Any]) -> Tool[InputT, Any, ChunkT]: """View a tool ``Action`` that wasn't built as a ``Tool`` (plugin, DAP, hand-registered) as one. - Shares the action's function and metadata; there is no ``tool.v2`` companion. + Shares the action's function and metadata. """ if isinstance(action, Tool): - return cast(Tool[InputT, OutputT, ChunkT], action) # pyrefly: ignore[redundant-cast] - ty needs it + return cast(Tool[InputT, Any, ChunkT], action) # pyrefly: ignore[redundant-cast] - ty needs it return _ActionTool(action) - @property - def model_output_schema(self) -> dict[str, object] | None: - """JSON Schema the model binds as this tool's ``outputSchema``.""" - if ORIGINAL_OUTPUT_SCHEMA_KEY in self.metadata: - original = self.metadata[ORIGINAL_OUTPUT_SCHEMA_KEY] - return cast(dict[str, object], original) if isinstance(original, dict) else None - return self.output_schema - - @model_output_schema.setter - def model_output_schema(self, value: dict[str, object] | None) -> None: - self._metadata[ORIGINAL_OUTPUT_SCHEMA_KEY] = value - if self._wire_action is not None: - self._wire_action.metadata[ORIGINAL_OUTPUT_SCHEMA_KEY] = value - - @property - def wire_action(self) -> Action[InputT, MultipartToolResponse[Any], ChunkT, None] | None: - """The ``tool.v2`` action: same function, returns the ``MultipartToolResponse`` envelope. - - The registry stores it next to the tool under ``/tool.v2/``; the - Dev UI and other wire consumers run it. ``None`` for a ``Tool`` viewed - from a plain action. - """ - return self._wire_action - def definition(self) -> ToolDefinition: """Return the wire-format ToolDefinition for this tool. @@ -486,22 +547,64 @@ def definition(self) -> ToolDefinition: name=self.name, description=self.description or '', input_schema=self.input_schema, - output_schema=self.model_output_schema, + output_schema=self.output_schema, ) - async def _invoke(self, input: object | None, ctx: ActionContext) -> OutputT: - """Run the function, then check its result the way generate would send it to a model. + def _wrap_response(self, value: object) -> MultipartToolResponse[OutputT]: + """Normalize a handler return into a validated ``MultipartToolResponse``. - A value the model couldn't receive (unserializable output or metadata, - a part with no payload) raises ``INVALID_ARGUMENT`` on every call path, - not just inside ``generate``. The function's own value is returned. + Validates the envelope (live parts, JSON-serializable metadata and + output) and parses non-None ``output`` against the declared return type + ``T`` while keeping ``output`` optional. """ - output = await super()._invoke(input, ctx) - as_multipart_tool_response(output, tool_name=self.name) - return output + if isinstance(value, (MultipartToolResponse, MultipartToolResponseData)): + raw_output: object = value.output + raw_content = value.content + raw_metadata = value.metadata + else: + raw_output = value + raw_content = None + raw_metadata = None + + parts: list[Part] | None = None + if raw_content: + parts = [require_live_part(as_part(part), tool_name=self.name) for part in raw_content] + + if raw_metadata is not None: + dump_tool_metadata(raw_metadata, tool_name=self.name) + + output: object = raw_output + if output is not None and self._declared_output_type is not None: + try: + output = self._declared_output_type.validate_python(output) + except ValidationError as e: + raise GenkitError( + message=f"Tool '{self.name}' returned an output that doesn't match its return annotation", + status='INTERNAL', + cause=e, + reason=ErrorReason.INVALID_OUTPUT, + ) from e + + # Check JSON-serializability on every call path, not just inside generate. + dump_tool_output(output, tool_name=self.name) + + return MultipartToolResponse( + output=cast(OutputT, output), + content=parts, + metadata=raw_metadata, + ) + + async def _invoke(self, input: object | None, ctx: ActionContext) -> MultipartToolResponse[OutputT]: + """Run the function, wrap into ``MultipartToolResponse``, and validate envelope and output.""" + raw = await super()._invoke(input, ctx) + return self._wrap_response(raw) -class DefaultedTool(DefaultedAction[InputT, OutputT, ChunkT, None], Tool[InputT, OutputT, ChunkT]): +class DefaultedTool( + DefaultedAction[InputT, MultipartToolResponse[OutputT], ChunkT, None], + Tool[InputT, OutputT, ChunkT], + Generic[InputT, OutputT, ChunkT], +): """A ``Tool`` whose function gives the input a default. ``@ai.tool`` and ``define_tool`` return one for ``async def @@ -512,10 +615,9 @@ class DefaultedTool(DefaultedAction[InputT, OutputT, ChunkT, None], Tool[InputT, class _ActionTool(Tool[InputT, OutputT, ChunkT]): - """A ``Tool`` view over a plain ``Action`` with no ``tool.v2`` companion.""" + """A ``Tool`` view over a plain ``Action`` registered outside ``Tool``.""" - def __init__(self, action: Action[InputT, OutputT, ChunkT, Any]) -> None: - self._wire_action = None + def __init__(self, action: Action[InputT, Any, ChunkT, Any]) -> None: Action.__init__( self, kind=action.kind, @@ -534,6 +636,13 @@ def __init__(self, action: Action[InputT, OutputT, ChunkT, Any]) -> None: self.input_schema = action.input_schema self._output_type = action._output_type self._set_output_schema(action.output_schema) + inner = envelope_output_type(resolve_type_hints(action._user_fn).get('return')) + if inner is NOT_ENVELOPE: + self._declared_output_type = action._output_type + elif inner is Any or inner is object or isinstance(inner, str): + self._declared_output_type = None + else: + self._declared_output_type = TypeAdapter(inner) self._init_type = action._init_type if hasattr(action, '_init_schema'): self._init_schema = action._init_schema diff --git a/packages/genkit/tests/genkit/ai/_tools_test.py b/packages/genkit/tests/genkit/ai/_tools_test.py index 1b3e944e9..dc42fda90 100644 --- a/packages/genkit/tests/genkit/ai/_tools_test.py +++ b/packages/genkit/tests/genkit/ai/_tools_test.py @@ -71,7 +71,7 @@ async def t2(inp: dict, ctx: ToolContext) -> str: # noqa: ARG001 captured.append((ctx.resumed_metadata, ctx.original_input)) return 'done' - action = await ai._registry.resolve_action(kind=ActionKind.TOOL, name='t2') + action = await ai._registry.resolve_action(kind=ActionKind.TOOL_V2, name='t2') assert action is not None restart_trp = Part.from_tool_request(name='t2', ref='x', input={'q': 1}, metadata={'resumed': True}) @@ -92,7 +92,7 @@ async def t2(inp: dict, ctx: ToolContext) -> str: # noqa: ARG001 captured.append(ctx.resumed_metadata) return 'done' - action = await ai._registry.resolve_action(kind=ActionKind.TOOL, name='t2') + action = await ai._registry.resolve_action(kind=ActionKind.TOOL_V2, name='t2') assert action is not None restart_trp = Part.from_tool_request(name='t2', ref='x', input={}, metadata={'resumed': {'by': 'x'}}) @@ -111,7 +111,7 @@ async def t2(inp: dict, ctx: ToolContext) -> str: # noqa: ARG001 captured.append((inp, ctx.original_input)) return 'done' - action = await ai._registry.resolve_action(kind=ActionKind.TOOL, name='t2') + action = await ai._registry.resolve_action(kind=ActionKind.TOOL_V2, name='t2') assert action is not None restart_trp = Part.from_tool_request( @@ -132,7 +132,7 @@ async def test_run_tool_after_restart_resets_contextvars() -> None: async def t2(inp: dict, ctx: ToolContext) -> str: # noqa: ARG001 return 'done' - action = await ai._registry.resolve_action(kind=ActionKind.TOOL, name='t2') + action = await ai._registry.resolve_action(kind=ActionKind.TOOL_V2, name='t2') assert action is not None restart_trp = Part.from_tool_request(name='t2', ref='x', input={}, metadata={'resumed': True}) @@ -150,7 +150,7 @@ async def test_run_tool_after_restart_nested_interrupt_raises() -> None: async def t2(inp: dict, ctx: ToolContext) -> str: # noqa: ARG001 raise Interrupt() - action = await ai._registry.resolve_action(kind=ActionKind.TOOL, name='t2') + action = await ai._registry.resolve_action(kind=ActionKind.TOOL_V2, name='t2') assert action is not None restart_trp = Part.from_tool_request(name='t2', ref='x', input={}, metadata={'resumed': True}) @@ -182,7 +182,7 @@ async def test_run_tool_after_restart_nested_interrupt_includes_reason() -> None async def t3(inp: dict, ctx: ToolContext) -> str: # noqa: ARG001 raise Interrupt({'message': 'Tool not in approved list: t3'}) - action = await ai._registry.resolve_action(kind=ActionKind.TOOL, name='t3') + action = await ai._registry.resolve_action(kind=ActionKind.TOOL_V2, name='t3') assert action is not None restart_trp = Part.from_tool_request(name='t3', ref='x', input={}, metadata={'resumed': True}) @@ -262,7 +262,7 @@ async def test_run_tool_after_restart_response_preserves_ref() -> None: async def t_ref(inp: dict) -> str: # noqa: ARG001 return 'done' - action = await ai._registry.resolve_action(kind=ActionKind.TOOL, name='t_ref') + action = await ai._registry.resolve_action(kind=ActionKind.TOOL_V2, name='t_ref') assert action is not None restart_trp = Part.from_tool_request(name='t_ref', ref='wire-ref-99', input={}, metadata={'resumed': True}) @@ -289,7 +289,7 @@ async def transfer(inp: dict, ctx: ToolContext) -> str: raise Interrupt({'reason': 'needs_approval'}) return f'transferred {inp.get("amount")}' - action = await ai._registry.resolve_action(kind=ActionKind.TOOL, name='transfer') + action = await ai._registry.resolve_action(kind=ActionKind.TOOL_V2, name='transfer') assert action is not None prior = {'amount': 100, 'confirmed': False} @@ -323,7 +323,7 @@ async def ctx_restart_tool(inp: dict, ctx: ToolContext) -> str: # noqa: ARG001 seen.append(dict(ctx.context)) return 'resumed_ok' - action = await ai._registry.resolve_action(kind=ActionKind.TOOL, name='ctx_restart_tool') + action = await ai._registry.resolve_action(kind=ActionKind.TOOL_V2, name='ctx_restart_tool') assert action is not None restart_trp = Part.from_tool_request(name='ctx_restart_tool', ref='r1', input={}, metadata={'resumed': True}) diff --git a/packages/genkit/tests/genkit/ai/dynamic_tools_generate_test.py b/packages/genkit/tests/genkit/ai/dynamic_tools_generate_test.py index 9ece7b227..d1c947f9a 100644 --- a/packages/genkit/tests/genkit/ai/dynamic_tools_generate_test.py +++ b/packages/genkit/tests/genkit/ai/dynamic_tools_generate_test.py @@ -237,19 +237,21 @@ async def tool_fn(x: str) -> str: @pytest.mark.asyncio -async def test_resolve_tool_prefers_tool_and_falls_back_to_tool_v2() -> None: - """A bare name resolves ``tool`` first, then ``tool.v2`` (JS order); a ``/tool.v2/`` key picks the envelope.""" +async def test_resolve_tool_prefers_tool_v2_and_falls_back_to_tool() -> None: + """A bare name resolves ``tool.v2`` first, then falls back to legacy ``tool`` actions.""" registry = Registry() async def tool_fn(x: str) -> str: return x echo = define_tool(registry, tool_fn, name='echo') - wire_only = registry.register_action(name='shot', kind=ActionKind.TOOL_V2, fn=tool_fn) + legacy_echo = registry.register_action(name='echo', kind=ActionKind.TOOL, fn=tool_fn) + legacy_only = registry.register_action(name='legacy', kind=ActionKind.TOOL, fn=tool_fn) assert await resolve_tool(registry, 'echo') is echo - assert await resolve_tool(registry, '/tool.v2/echo') is echo.wire_action - assert await resolve_tool(registry, 'shot') is wire_only + assert await resolve_tool(registry, '/tool.v2/echo') is echo + assert await resolve_tool(registry, '/tool/echo') is legacy_echo + assert await resolve_tool(registry, 'legacy') is legacy_only @pytest.mark.asyncio @@ -366,7 +368,7 @@ async def dap_fn() -> DapValue: assert call_log == ['hello'] assert pm.last_request is not None assert pm.last_request.tools - # Raw DAP Action — no originalOutputSchema key — still advertises the handler return. + # Raw DAP Action still advertises the handler return schema directly. assert pm.last_request.tools[0].output_schema == {'type': 'string'} # Postcondition: resolving/running the tool via DAP still does not # persist `echo` under the root registry as a static tool (same check as above). diff --git a/packages/genkit/tests/genkit/ai/flow_return_test.py b/packages/genkit/tests/genkit/ai/flow_return_test.py index 7a28ead2e..fead4fc1a 100644 --- a/packages/genkit/tests/genkit/ai/flow_return_test.py +++ b/packages/genkit/tests/genkit/ai/flow_return_test.py @@ -206,16 +206,21 @@ async def login(_name: str) -> Secret: @pytest.mark.asyncio -async def test_tool_returning_wrong_shape_is_not_checked() -> None: - """A `@ai.tool` `-> int` returning `'x'` gives back `'x'`.""" +async def test_tool_returning_wrong_shape_raises_invalid_output() -> None: + """A `@ai.tool` `-> int` returning `'x'` raises INTERNAL / INVALID_OUTPUT.""" ai = Genkit() @ai.tool() async def echo(_name: str) -> int: return 'x' # type: ignore[return-value] - result = await echo('ada') - assert result == 'x' + with pytest.raises(GenkitError) as exc: + await echo('ada') + + assert exc.value.status == 'INTERNAL' + assert exc.value.reason is ErrorReason.INVALID_OUTPUT + assert isinstance(exc.value.__cause__, ValidationError) + assert "Tool 'echo' returned an output that doesn't match its return annotation" in str(exc.value) @pytest.mark.asyncio diff --git a/packages/genkit/tests/genkit/ai/generate_loop_test.py b/packages/genkit/tests/genkit/ai/generate_loop_test.py index 2604990d3..2e9577a7a 100644 --- a/packages/genkit/tests/genkit/ai/generate_loop_test.py +++ b/packages/genkit/tests/genkit/ai/generate_loop_test.py @@ -401,7 +401,7 @@ def __call__(self, dish: str) -> str: tool = Tool(AllergyCheck(), name='allergy_check') assert tool.name == 'allergy_check' assert tool.input_schema == {'type': 'string'} - assert (await tool.run('peanuts')).response == 'peanuts: nut-free' + assert (await tool.run('peanuts')).response.output == 'peanuts: nut-free' with pytest.raises(TypeError, match='must be async'): Tool(SyncCheck(), name='sync_check') # pyright: ignore[reportCallIssue, reportArgumentType] # pyrefly: ignore[no-matching-overload] diff --git a/packages/genkit/tests/genkit/ai/streaming_tool_send_chunk_test.py b/packages/genkit/tests/genkit/ai/streaming_tool_send_chunk_test.py index 07b120204..641eb174a 100644 --- a/packages/genkit/tests/genkit/ai/streaming_tool_send_chunk_test.py +++ b/packages/genkit/tests/genkit/ai/streaming_tool_send_chunk_test.py @@ -163,15 +163,15 @@ async def garnish(ticket: KitchenTicket) -> str: # 5. Streaming ephemeral Tool(fn) yields typed Step chunks stream = ephemeral.stream(KitchenTicket(dish='Short Rib', servings=2)) - assert_type(stream, StreamResponse[Step, Recipe]) # ty: ignore[type-assertion-failure] + assert_type(stream, StreamResponse[Step, MultipartToolResponse[Recipe]]) # ty: ignore[type-assertion-failure] emitted = [chunk async for chunk in stream] assert emitted == [Step(stage='sear:Short Rib', percent=40)] - assert await stream.response == Recipe(title='Short Rib', steps=['sear', 'simmer']) + assert await stream.response == MultipartToolResponse(output=Recipe(title='Short Rib', steps=['sear', 'simmer'])) @pytest.mark.asyncio async def test_tool_stream_yields_typed_chunks_and_output() -> None: - """Direct tool.stream(input) yields ChunkT directly and resolves OutputT directly.""" + """Direct tool.stream(input) yields ChunkT directly and resolves MultipartToolResponse[OutputT].""" ai = Genkit() @ai.tool(name='deploy') @@ -181,24 +181,24 @@ async def deploy(_req: dict[str, Any], ctx: ToolContext[Step]) -> str: return 'https://service.run' stream = deploy.stream({}) - assert_type(stream, StreamResponse[Step, str]) + assert_type(stream, StreamResponse[Step, MultipartToolResponse[str]]) got: list[Step] = [] async for chunk in stream.stream: assert_type(chunk, Step) got.append(chunk) result = await stream.response - assert_type(result, str) + assert_type(result, MultipartToolResponse[str]) assert got == [ Step(stage='compile', percent=30), Step(stage='rollout', percent=90), ] - assert result == 'https://service.run' + assert result == MultipartToolResponse(output='https://service.run') @pytest.mark.asyncio async def test_tool_stream_returns_pydantic_output_directly() -> None: - """Direct tool.stream(input) resolves a Pydantic model OutputT instance directly.""" + """Direct tool.stream(input) resolves MultipartToolResponse carrying a Pydantic model instance.""" ai = Genkit() @ai.tool(name='cook') @@ -207,19 +207,19 @@ async def cook(_req: dict[str, Any], ctx: ToolContext[Step]) -> Recipe: return Recipe(title='Tartine', steps=['toast', 'top']) stream = cook.stream({}) - assert_type(stream, StreamResponse[Step, Recipe]) + assert_type(stream, StreamResponse[Step, MultipartToolResponse[Recipe]]) got = [chunk async for chunk in stream.stream] - recipe = await stream.response - assert_type(recipe, Recipe) + result = await stream.response + assert_type(result, MultipartToolResponse[Recipe]) assert got == [Step(stage='prep', percent=50)] - assert isinstance(recipe, Recipe) - assert recipe == Recipe(title='Tartine', steps=['toast', 'top']) + assert isinstance(result.output, Recipe) + assert result.output == Recipe(title='Tartine', steps=['toast', 'top']) @pytest.mark.asyncio async def test_tool_call_without_stream_is_noop_for_send_chunk() -> None: - """Direct await tool(input) ignores send_chunk and returns OutputT directly.""" + """Direct await tool(input) ignores send_chunk and returns MultipartToolResponse[OutputT].""" ai = Genkit() @ai.tool(name='deploy') @@ -228,7 +228,7 @@ async def deploy(_req: dict[str, Any], ctx: ToolContext[Step]) -> str: return 'done' res = await deploy({}) - assert res == 'done' + assert res == MultipartToolResponse(output='done') @pytest.mark.asyncio @@ -242,13 +242,13 @@ async def deploy(_req: dict[str, Any], ctx: ToolContext[Step]) -> Recipe: return Recipe(title='Sourdough', steps=['mix', 'bake']) stream = deploy.stream({}) - assert_type(stream, StreamResponse[Step, Recipe]) + assert_type(stream, StreamResponse[Step, MultipartToolResponse[Recipe]]) got = [chunk async for chunk in stream.stream] - recipe = await stream.response - assert_type(recipe, Recipe) + result = await stream.response + assert_type(result, MultipartToolResponse[Recipe]) assert got == [Step(stage='bake', percent=80)] - assert recipe == Recipe(title='Sourdough', steps=['mix', 'bake']) + assert result == MultipartToolResponse(output=Recipe(title='Sourdough', steps=['mix', 'bake'])) @pytest.mark.asyncio @@ -331,17 +331,18 @@ async def plate_dish(_req: dict[str, Any], ctx: ToolContext[KitchenUpdate]) -> K } assert _tool_outputs(response.messages) == [final_out] - # 2. Direct tool.stream() yields and resolves live KitchenUpdate BaseModel instances + # 2. Direct tool.stream() yields live KitchenUpdate chunks and resolves MultipartToolResponse[KitchenUpdate] direct = plate_dish.stream({}) - assert_type(direct, StreamResponse[KitchenUpdate, KitchenUpdate]) + assert_type(direct, StreamResponse[KitchenUpdate, MultipartToolResponse[KitchenUpdate]]) direct_chunks = [c async for c in direct] direct_final = await direct.response assert len(direct_chunks) == 1 assert isinstance(direct_chunks[0], KitchenUpdate) assert isinstance(direct_chunks[0].observed_at, datetime) assert direct_chunks[0] == KitchenUpdate(stage_name='torching_glaze', observed_at=prep_ts) - assert isinstance(direct_final, KitchenUpdate) - assert direct_final == KitchenUpdate(stage_name='plated', observed_at=plated_ts) + assert isinstance(direct_final, MultipartToolResponse) + assert isinstance(direct_final.output, KitchenUpdate) + assert direct_final.output == KitchenUpdate(stage_name='plated', observed_at=plated_ts) @pytest.mark.asyncio @@ -797,7 +798,7 @@ async def outer_deploy(_req: dict[str, Any], ctx: ToolContext[str]) -> str: async for item in inner_stream: captured_inner_stream.append(item) await inner_stream.response - ctx.send_chunk(f'outer-after:{inner_res}') + ctx.send_chunk(f'outer-after:{inner_res.output}') return 'outer-done' pm.responses = [_model_calls(('outer_deploy', 'outer-1')), _model_says('ok')] diff --git a/packages/genkit/tests/genkit/ai/tool_multipart_test.py b/packages/genkit/tests/genkit/ai/tool_multipart_test.py index 2029f8a84..17041ba1d 100644 --- a/packages/genkit/tests/genkit/ai/tool_multipart_test.py +++ b/packages/genkit/tests/genkit/ai/tool_multipart_test.py @@ -13,13 +13,12 @@ from datetime import datetime import pytest -from pydantic import BaseModel, ConfigDict, TypeAdapter +from pydantic import BaseModel, ConfigDict from pydantic.alias_generators import to_camel from genkit import Genkit, Message, ModelResponse, Part from genkit._ai._generate import CallScope, generate_action, to_tool_definition from genkit._ai._tools import ( - ORIGINAL_OUTPUT_SCHEMA_KEY, MultipartToolResponse, as_multipart_tool_response, envelope_output_type, @@ -33,7 +32,6 @@ from genkit._core._typing import ( FinishReason, MiddlewareRef, - MultipartToolResponse as MultipartToolResponseData, ) from genkit.middleware import Middleware, MiddlewareContext, ToolHookParams from genkit.plugin_api import ActionKind @@ -47,13 +45,6 @@ def _png() -> Part: WIRE_PNG = {'media': {'contentType': 'image/png', 'url': 'data:image/png;base64,abc'}} -def _wire(tool: Tool) -> Action: - """The ``tool.v2`` envelope action the Dev UI runs for this tool.""" - wire = tool.wire_action - assert wire is not None - return wire - - def test_response_text_part_is_live() -> None: env = MultipartToolResponse(output={'ok': True}, content=[Part.from_text('lab camera')]) assert parts_to_wire(env.content) == [{'text': 'lab camera'}] @@ -137,26 +128,19 @@ def test_returning_unserializable_part_data_is_invalid_argument_naming_the_tool( assert 'content' in ei.value.message -def test_define_tool_stamps_envelope_and_declared_schema() -> None: - """The tool advertises its return type; its tool.v2 action (Dev UI) advertises the envelope.""" +def test_define_tool_registers_single_tool_v2_with_declared_schema() -> None: + """The tool registers as a single tool.v2 action whose output_schema is its declared return type.""" ai = Genkit() @ai.tool(name='weather') async def weather(city: str) -> str: return f'Sunny in {city}' - envelope = TypeAdapter(MultipartToolResponseData).json_schema() - assert weather.kind == ActionKind.TOOL - assert create_action_key(weather.kind, weather.name) == '/tool/weather' + assert weather.kind == ActionKind.TOOL_V2 + assert create_action_key(weather.kind, weather.name) == '/tool.v2/weather' assert weather.output_schema == {'type': 'string'} - assert weather.metadata[ORIGINAL_OUTPUT_SCHEMA_KEY] == {'type': 'string'} - - wire = _wire(weather) - assert wire.kind == ActionKind.TOOL_V2 - assert create_action_key(wire.kind, wire.name) == '/tool.v2/weather' - assert wire.input_schema == weather.input_schema - assert wire.output_schema == envelope - assert wire.metadata[ORIGINAL_OUTPUT_SCHEMA_KEY] == {'type': 'string'} + assert weather.metadata['outputSchema'] == {'type': 'string'} + assert 'originalOutputSchema' not in weather.metadata def test_bare_envelope_annotation_has_no_inner_schema() -> None: @@ -166,18 +150,14 @@ def test_bare_envelope_annotation_has_no_inner_schema() -> None: async def shot() -> MultipartToolResponse: return MultipartToolResponse(output={'ok': True}) - envelope = TypeAdapter(MultipartToolResponseData).json_schema() - assert shot.output_schema == TypeAdapter(MultipartToolResponse).json_schema() - assert shot.metadata['outputSchema'] == shot.output_schema - assert shot.model_output_schema is None - assert _wire(shot).output_schema == envelope - assert _wire(shot).metadata[ORIGINAL_OUTPUT_SCHEMA_KEY] is None - assert shot.metadata[ORIGINAL_OUTPUT_SCHEMA_KEY] is None + assert shot.output_schema is None + assert shot.metadata.get('outputSchema') is None + assert 'originalOutputSchema' not in shot.metadata assert shot.definition().output_schema is None -def test_model_output_schema_leaves_action_output_schema_intact() -> None: - """Setting ``model_output_schema`` updates model binding without altering ``output_schema``.""" +def test_output_schema_reflects_declared_schema_and_override() -> None: + """``output_schema`` holds the declared schema directly and can be overridden (e.g. MCP tools).""" ai = Genkit() @ai.tool(name='typed_shot') @@ -186,52 +166,41 @@ async def typed_shot() -> MultipartToolResponse[CamelOut]: output=CamelOut(content_type='image/png', taken_at=datetime(2026, 8, 25, 12, 0)), ) - typed_envelope = TypeAdapter(MultipartToolResponse[CamelOut]).json_schema() camel_schema = to_json_schema(CamelOut) - assert typed_shot.output_schema == typed_envelope - assert typed_shot.model_output_schema == camel_schema + assert typed_shot.output_schema == camel_schema + assert typed_shot.metadata['outputSchema'] == camel_schema assert typed_shot.definition().output_schema == camel_schema @ai.tool(name='mcp_like') async def mcp_like() -> MultipartToolResponse: return MultipartToolResponse(output={'temperature_c': 21.5}) - bare_envelope = TypeAdapter(MultipartToolResponse).json_schema() declared: dict[str, object] = { 'type': 'object', 'properties': {'temperature_c': {'type': 'number'}}, 'required': ['temperature_c'], } - mcp_like.model_output_schema = declared - assert mcp_like.output_schema == bare_envelope - assert mcp_like.metadata['outputSchema'] == bare_envelope - assert mcp_like.model_output_schema == declared + assert mcp_like.output_schema is None + mcp_like.output_schema = declared + assert mcp_like.output_schema == declared + assert mcp_like.metadata['outputSchema'] == declared assert mcp_like.definition().output_schema == declared - assert _wire(mcp_like).metadata[ORIGINAL_OUTPUT_SCHEMA_KEY] == declared - # Clearing model_output_schema to None keeps the /tool/ action's outputSchema metadata intact. - mcp_like.model_output_schema = None - assert mcp_like.output_schema == bare_envelope - assert mcp_like.metadata['outputSchema'] == bare_envelope - assert mcp_like.model_output_schema is None + mcp_like.output_schema = None + assert mcp_like.output_schema is None + assert mcp_like.metadata.get('outputSchema') is None assert mcp_like.definition().output_schema is None - assert _wire(mcp_like).metadata[ORIGINAL_OUTPUT_SCHEMA_KEY] is None async def echo_fn(x: str) -> str: return x raw_handle = Tool.from_action(Action(name='echo', kind=ActionKind.TOOL, fn=echo_fn)) assert raw_handle.output_schema == {'type': 'string'} - assert raw_handle.model_output_schema == {'type': 'string'} - raw_handle.model_output_schema = None - assert raw_handle.output_schema == {'type': 'string'} - assert raw_handle.metadata['outputSchema'] == {'type': 'string'} - assert raw_handle.model_output_schema is None - assert raw_handle.definition().output_schema is None + assert raw_handle.definition().output_schema == {'type': 'string'} -def test_to_tool_definition_sends_original_schema_not_envelope() -> None: - """The model sees originalOutputSchema. Dev UI / run still see the envelope.""" +def test_to_tool_definition_uses_declared_output_schema() -> None: + """The model and action manifest both see the declared output schema directly.""" ai = Genkit() @ai.tool(name='weather') @@ -240,7 +209,7 @@ async def weather(city: str) -> str: defined = to_tool_definition(weather) assert defined.output_schema == {'type': 'string'} - assert _wire(weather).output_schema == TypeAdapter(MultipartToolResponseData).json_schema() + assert weather.output_schema == {'type': 'string'} @ai.tool(name='shot') async def shot() -> MultipartToolResponse: @@ -252,7 +221,6 @@ async def echo_fn(x: str) -> str: return x raw = Action(name='echo', kind=ActionKind.TOOL, fn=echo_fn, metadata={'name': 'echo'}) - assert ORIGINAL_OUTPUT_SCHEMA_KEY not in (raw.metadata or {}) assert to_tool_definition(raw).output_schema == {'type': 'string'} @@ -264,8 +232,15 @@ async def test_pydantic_return_dumps_json_aliases() -> None: async def shot() -> CamelOut: return CamelOut(content_type='image/png', taken_at=datetime(2026, 8, 25, 12, 0)) - out = (await _wire(shot).run()).response - assert out.output == {'contentType': 'image/png', 'takenAt': '2026-08-25T12:00:00'} + out = (await shot.run()).response + assert isinstance(out.output, CamelOut) + assert out.model_dump(by_alias=True, exclude_none=True, mode='json') == { + 'output': {'contentType': 'image/png', 'takenAt': '2026-08-25T12:00:00'}, + } + assert as_multipart_tool_response(out, tool_name='shot').output == { + 'contentType': 'image/png', + 'takenAt': '2026-08-25T12:00:00', + } @pytest.mark.asyncio @@ -276,8 +251,9 @@ async def test_response_metadata_datetime_is_json() -> None: async def shot() -> MultipartToolResponse: return MultipartToolResponse(output={'ok': True}, metadata={'when': datetime(2026, 8, 25, 12, 0)}) - out = (await _wire(shot).run()).response - assert out.metadata == {'when': '2026-08-25T12:00:00'} + out = (await shot.run()).response + assert out.model_dump(by_alias=True, exclude_none=True, mode='json')['metadata'] == {'when': '2026-08-25T12:00:00'} + assert as_multipart_tool_response(out, tool_name='shot').metadata == {'when': '2026-08-25T12:00:00'} @pytest.mark.asyncio @@ -291,9 +267,14 @@ async def shot() -> MultipartToolResponse: content=[_png()], ) - out = (await _wire(shot).run()).response - assert out.output == {'contentType': 'image/png', 'takenAt': '2026-08-25T12:00:00'} - assert parts_to_wire(out.content) == [WIRE_PNG] + out = (await shot.run()).response + assert out.model_dump(by_alias=True, exclude_none=True, mode='json') == { + 'output': {'contentType': 'image/png', 'takenAt': '2026-08-25T12:00:00'}, + 'content': [WIRE_PNG], + } + wire = as_multipart_tool_response(out, tool_name='shot') + assert wire.output == {'contentType': 'image/png', 'takenAt': '2026-08-25T12:00:00'} + assert parts_to_wire(wire.content) == [WIRE_PNG] @pytest.mark.asyncio @@ -412,8 +393,8 @@ async def screenshot(_: dict) -> object: # noqa: ARG001 @pytest.mark.asyncio -async def test_tool_registers_under_tool_and_tool_v2() -> None: - """``@ai.tool`` stores the tool at /tool/ and its envelope action at /tool.v2/.""" +async def test_tool_registers_only_under_tool_v2() -> None: + """``@ai.tool`` stores a single action at /tool.v2/ and does not register /tool/.""" ai = Genkit() @ai.tool(name='weather') @@ -423,9 +404,11 @@ async def weather(city: str) -> str: assert parse_action_key('/tool/weather') == (ActionKind.TOOL, 'weather') assert parse_action_key('/tool.v2/weather') == (ActionKind.TOOL_V2, 'weather') - assert await ai._registry.resolve_action(ActionKind.TOOL, 'weather') is weather - assert await ai._registry.resolve_action_by_key('/tool/weather') is weather - assert await ai._registry.resolve_action_by_key('/tool.v2/weather') is _wire(weather) + assert await ai._registry.resolve_action(ActionKind.TOOL_V2, 'weather') is weather + assert await ai._registry.resolve_action_by_key('/tool.v2/weather') is weather + assert await ai._registry.resolve_action(ActionKind.TOOL, 'weather') is None + assert await ai._registry.resolve_action_by_key('/tool/weather') is None + assert await ai.lookup_tool('weather') is weather @pytest.mark.asyncio diff --git a/packages/genkit/tests/genkit/ai/tool_none_input_test.py b/packages/genkit/tests/genkit/ai/tool_none_input_test.py index e05f3fcad..0cd0f5131 100644 --- a/packages/genkit/tests/genkit/ai/tool_none_input_test.py +++ b/packages/genkit/tests/genkit/ai/tool_none_input_test.py @@ -10,7 +10,7 @@ from httpx import ASGITransport, AsyncClient from pydantic import BaseModel -from genkit import Genkit, GenkitError, Message, ModelResponse, Part +from genkit import Genkit, GenkitError, Message, ModelResponse, MultipartToolResponse, Part from genkit._core._reflection import create_reflection_asgi_app from genkit._core._typing import FinishReason, Role, ToolRequest from genkit.testing import define_scripted_model @@ -44,7 +44,7 @@ async def test_tool_with_no_input_uses_python_default() -> None: async def todays_soup(day: str = 'monday') -> str: return f'{day}: bouillabaisse' - assert await todays_soup() == 'monday: bouillabaisse' + assert await todays_soup() == MultipartToolResponse(output='monday: bouillabaisse') @pytest.mark.asyncio @@ -116,7 +116,7 @@ async def todays_soup(day: str = 'monday') -> str: return f'{day}: bouillabaisse' async with _dev_ui_client(ai) as client: - response = await client.post('/api/runAction', json={'key': '/tool/todays_soup', 'input': None}) + response = await client.post('/api/runAction', json={'key': '/tool.v2/todays_soup', 'input': None}) assert response.status_code == 200 - assert response.json()['result'] == 'monday: bouillabaisse' + assert response.json()['result'] == {'output': 'monday: bouillabaisse'} diff --git a/packages/genkit/tests/genkit/ai/tool_response_contract_test.py b/packages/genkit/tests/genkit/ai/tool_response_contract_test.py index 1137e187b..f434cda84 100644 --- a/packages/genkit/tests/genkit/ai/tool_response_contract_test.py +++ b/packages/genkit/tests/genkit/ai/tool_response_contract_test.py @@ -1,7 +1,7 @@ # Copyright 2026 Google LLC # SPDX-License-Identifier: Apache-2.0 -"""The return annotation is the schema the model sees. ``await tool(...)`` returns what the function returned.""" +"""The return annotation is the schema the model sees. ``await tool(...)`` returns ``MultipartToolResponse``.""" from __future__ import annotations @@ -120,45 +120,45 @@ async def raw_shot() -> MultipartToolResponse[ShotOut]: @pytest.mark.asyncio -async def test_await_int_tool_returns_int() -> None: - """`await add_pair(Pair(a=2, b=3))` on a `-> int` tool returns 5.""" +async def test_await_int_tool_returns_multipart_response_with_int() -> None: + """`await add_pair(Pair(a=2, b=3))` on a `-> int` tool returns MultipartToolResponse(output=5).""" ai = Genkit() @ai.tool() async def add_pair(pair: Pair) -> int: return pair.a + pair.b - assert await add_pair(Pair(a=2, b=3)) == 5 + assert await add_pair(Pair(a=2, b=3)) == MultipartToolResponse(output=5) @pytest.mark.asyncio -async def test_await_str_tool_returns_string() -> None: - """`await weather('Austin')` on a `-> str` tool returns 'Sunny in Austin'.""" +async def test_await_str_tool_returns_multipart_response_with_string() -> None: + """`await weather('Austin')` on a `-> str` tool returns MultipartToolResponse(output='Sunny in Austin').""" ai = Genkit() @ai.tool(name='weather') async def weather(city: str) -> str: return f'Sunny in {city}' - assert await weather('Austin') == 'Sunny in Austin' + assert await weather('Austin') == MultipartToolResponse(output='Sunny in Austin') assert weather.definition().output_schema == {'type': 'string'} @pytest.mark.asyncio -async def test_await_tool_returning_none_returns_none() -> None: - """`await log_visit('Austin')` on a `-> None` tool returns None.""" +async def test_await_tool_returning_none_returns_multipart_response_with_none() -> None: + """`await log_visit('Austin')` on a `-> None` tool returns MultipartToolResponse(output=None).""" ai = Genkit() @ai.tool() async def log_visit(city: str) -> None: return None - assert await log_visit('Austin') is None + assert await log_visit('Austin') == MultipartToolResponse(output=None) @pytest.mark.asyncio -async def test_await_dict_tool_returns_the_dict() -> None: - """`await stamp()` on a `-> dict` tool returns the dict as built, datetimes still datetimes.""" +async def test_await_dict_tool_returns_multipart_response_with_the_dict() -> None: + """`await stamp()` on a `-> dict` tool returns MultipartToolResponse with datetimes preserved.""" ai = Genkit() when = datetime(2026, 8, 25, 12, 0) @@ -167,8 +167,9 @@ async def stamp() -> dict[str, Any]: return {'when': when, 'ok': True} out = await stamp() - assert out == {'when': when, 'ok': True} - assert isinstance(out['when'], datetime) + assert out == MultipartToolResponse(output={'when': when, 'ok': True}) + assert out.output is not None + assert isinstance(out.output['when'], datetime) @pytest.mark.asyncio @@ -195,17 +196,17 @@ async def weather(city: str) -> str: @pytest.mark.asyncio -async def test_tool_v2_run_str_tool_still_returns_multipart_tool_response() -> None: - """Running `/tool.v2/weather`, what the Dev UI runs, still returns a MultipartToolResponse.""" +async def test_tool_v2_run_str_tool_returns_multipart_tool_response() -> None: + """Running `/tool.v2/weather`, the single registered tool action, returns MultipartToolResponse.""" ai = Genkit() @ai.tool(name='weather') async def weather(city: str) -> str: return f'Sunny in {city}' - assert (await weather.run('Austin')).response == 'Sunny in Austin' + assert (await weather.run('Austin')).response == MultipartToolResponse(output='Sunny in Austin') wire = await ai._registry.resolve_action_by_key('/tool.v2/weather') - assert wire is not None + assert wire is weather ran = await wire.run('Austin') assert isinstance(ran.response, MultipartToolResponse) assert ran.response.output == 'Sunny in Austin' @@ -214,8 +215,8 @@ async def weather(city: str) -> str: @pytest.mark.asyncio -async def test_await_pydantic_tool_returns_the_model_instance() -> None: - """`await shot()` on a `-> ShotOut` tool returns the ShotOut instance, not a dict.""" +async def test_await_pydantic_tool_returns_multipart_response_with_model_instance() -> None: + """`await shot()` on a `-> ShotOut` tool returns MultipartToolResponse carrying ShotOut, not a dict.""" ai = Genkit() @ai.tool(name='shot') @@ -223,8 +224,9 @@ async def shot() -> ShotOut: return ShotOut(ok=True, label='lab') out = await shot() - assert isinstance(out, ShotOut) - assert out == ShotOut(ok=True, label='lab') + assert isinstance(out, MultipartToolResponse) + assert isinstance(out.output, ShotOut) + assert out.output == ShotOut(ok=True, label='lab') assert shot.definition().output_schema == to_json_schema(ShotOut) @@ -333,17 +335,18 @@ async def screenshot() -> MultipartToolResponse: @pytest.mark.asyncio -async def test_await_multipart_annotated_tool_with_bare_return_returns_the_bare_value() -> None: - """`await shot()` on a `-> MultipartToolResponse[ShotOut]` tool that returns a bare ShotOut returns that ShotOut.""" +async def test_await_multipart_annotated_tool_with_bare_return_wraps_in_response() -> None: + """`await shot()` on a `-> MultipartToolResponse[ShotOut]` tool returning bare ShotOut wraps it.""" ai = Genkit() @ai.tool(name='shot') async def shot() -> MultipartToolResponse[ShotOut]: return ShotOut(ok=True, label='lab') # type: ignore[return-value] - out: object = await shot() - assert isinstance(out, ShotOut) - assert out == ShotOut(ok=True, label='lab') + out = await shot() + assert isinstance(out, MultipartToolResponse) + assert isinstance(out.output, ShotOut) + assert out.output == ShotOut(ok=True, label='lab') assert shot.definition().output_schema == to_json_schema(ShotOut) @@ -409,8 +412,8 @@ async def shot() -> MultipartToolResponse[ShotOut]: @pytest.mark.asyncio -async def test_tool_v2_run_multipart_shotout_returns_dump_and_png() -> None: - """Running `/tool.v2/screenshot` still returns a MultipartToolResponse with the {ok, label} dump and the PNG.""" +async def test_tool_v2_run_multipart_shotout_returns_model_and_png() -> None: + """Running `/tool.v2/screenshot` returns MultipartToolResponse with the typed ShotOut and the PNG.""" ai = Genkit() @ai.tool(name='screenshot') @@ -418,10 +421,10 @@ async def screenshot() -> MultipartToolResponse[ShotOut]: return MultipartToolResponse(output=ShotOut(ok=True, label='lab'), content=[_png()], metadata={'src': 'cam'}) wire = await ai._registry.resolve_action_by_key('/tool.v2/screenshot') - assert wire is not None + assert wire is screenshot ran = await wire.run() assert isinstance(ran.response, MultipartToolResponse) - assert ran.response.output == SHOT + assert ran.response.output == ShotOut(ok=True, label='lab') assert ran.response.content == [_png()] assert ran.response.metadata == {'src': 'cam'} @@ -513,7 +516,7 @@ async def screenshot() -> MultipartToolResponse[ShotOut] | None: @pytest.mark.asyncio async def test_await_tool_return_types_match_annotation() -> None: - """Type checkers see `await tool(...)` as the function's own return type, context tools included.""" + """Type checkers see `await tool(...)` as `MultipartToolResponse[T]` without double-wrapping.""" ai = Genkit() @ai.tool() @@ -536,12 +539,12 @@ async def screenshot() -> MultipartToolResponse[ShotOut]: async def whoami(ctx: ToolContext) -> str: return str(ctx.context.get('user')) - assert_type(await add_pair(Pair(a=2, b=3)), int) - assert_type(await shot(), ShotOut) - assert_type(await log_visit('Austin'), None) + assert_type(await add_pair(Pair(a=2, b=3)), MultipartToolResponse[int]) + assert_type(await shot(), MultipartToolResponse[ShotOut]) + assert_type(await log_visit('Austin'), MultipartToolResponse[None]) assert_type(await screenshot(), MultipartToolResponse[ShotOut]) - assert_type(await whoami(context={'user': 'u1'}), str) - assert await whoami(context={'user': 'u1'}) == 'u1' + assert_type(await whoami(context={'user': 'u1'}), MultipartToolResponse[str]) + assert await whoami(context={'user': 'u1'}) == MultipartToolResponse(output='u1') @pytest.mark.asyncio @@ -576,9 +579,9 @@ async def shot() -> ShotOut: # 2-arg runtime subscripting works at runtime. assert get_args(Tool[int, str])[:2] == (int, str) - assert await Tool(add_pair)(Pair(a=2, b=3)) == 5 - assert await Tool(double)(4) == 8 - assert await Tool(shot, name='shot')() == ShotOut(ok=True, label='lab') + assert await Tool(add_pair)(Pair(a=2, b=3)) == MultipartToolResponse(output=5) + assert await Tool(double)(4) == MultipartToolResponse(output=8) + assert await Tool(shot, name='shot')() == MultipartToolResponse(output=ShotOut(ok=True, label='lab')) @pytest.mark.asyncio @@ -604,7 +607,7 @@ async def snap() -> dict[str, Any]: @pytest.mark.asyncio async def test_generate_after_direct_call_sends_model_the_same_tool_output() -> None: - """`await shot()` then `ai.generate(tools=['shot'])`: the caller got ShotOut, the model still gets the dump.""" + """`await shot()` then `ai.generate(tools=['shot'])`: direct call gets response, model gets dump.""" ai = Genkit(model='scriptedModel') pm, _ = define_scripted_model(ai) @@ -616,10 +619,74 @@ async def shot() -> ShotOut: generated = await _generate_tool_turn(ai, pm, name='shot') _assert_closed_tool_round(generated) tool_response, _ = _tool_response(generated) - assert direct == ShotOut(ok=True, label='lab') + assert direct == MultipartToolResponse(output=ShotOut(ok=True, label='lab')) assert tool_response.output == SHOT +@pytest.mark.asyncio +async def test_multipart_tool_response_allows_none_output_with_typed_schema() -> None: + """MultipartToolResponse(content=[...]) with output=None is valid even when T is non-optional.""" + ai = Genkit() + + @ai.tool(name='content_only') + async def content_only() -> MultipartToolResponse[ShotOut]: + return MultipartToolResponse(content=[_png()]) + + out = await content_only() + assert isinstance(out, MultipartToolResponse) + assert out.output is None + assert out.content == [_png()] + assert content_only.output_schema == to_json_schema(ShotOut) + + +@pytest.mark.asyncio +async def test_tool_validates_and_parses_non_none_output_against_declared_type() -> None: + """A dict matching the declared Pydantic output type is parsed; a bad shape raises INVALID_OUTPUT.""" + ai = Genkit() + + @ai.tool(name='dict_shot') + async def dict_shot() -> ShotOut: + return {'ok': True, 'label': 'lab'} # type: ignore[return-value] + + parsed = await dict_shot() + assert isinstance(parsed.output, ShotOut) + assert parsed.output == ShotOut(ok=True, label='lab') + + @ai.tool(name='bad_shot') + async def bad_shot() -> ShotOut: + return {'ok': 'not-a-bool-maybe', 'wrong': 1} # type: ignore[return-value] + + with pytest.raises(GenkitError) as exc: + await bad_shot() + assert exc.value.status == 'INTERNAL' + assert exc.value.reason is ErrorReason.INVALID_OUTPUT + + +@pytest.mark.asyncio +async def test_lookup_tool_prefers_tool_v2_and_falls_back_to_legacy_tool() -> None: + """lookup_tool resolves /tool.v2/ first and falls back to legacy /tool/.""" + ai = Genkit() + + async def legacy_fn() -> str: + return 'legacy' + + ai._registry.register_action_from_instance(Action(name='dual', kind=ActionKind.TOOL, fn=legacy_fn)) + ai._registry.register_action_from_instance(Action(name='legacy_only', kind=ActionKind.TOOL, fn=legacy_fn)) + + @ai.tool(name='dual') + async def dual_v2() -> str: + return 'v2' + + looked_up_dual = await ai.lookup_tool('dual') + assert looked_up_dual is dual_v2 + assert await looked_up_dual() == MultipartToolResponse(output='v2') + + looked_up_legacy = await ai.lookup_tool('legacy_only') + assert looked_up_legacy is not None + assert looked_up_legacy.kind == ActionKind.TOOL + assert await looked_up_legacy() == MultipartToolResponse(output='legacy') + + async def _generate_with_failing_tool(ai: Genkit, pm: ScriptedModel, *, name: str) -> ModelResponse: generated = await _generate_tool_turn(ai, pm, name=name) assert generated.finish_reason == FinishReason.FAILED @@ -738,5 +805,5 @@ async def specials() -> str: assert_type(Tool(echo_any), Tool[Any, str]) # ty: ignore[type-assertion-failure] # 4. Any/object tools take any input at the call site. - assert await Tool(echo_object)(5) == '5' - assert await Tool(ctx_then_any)({'dish': 'soup'}) == "{'dish': 'soup'}" + assert await Tool(echo_object)(5) == MultipartToolResponse(output='5') + assert await Tool(ctx_then_any)({'dish': 'soup'}) == MultipartToolResponse(output="{'dish': 'soup'}") diff --git a/packages/genkit/tests/genkit/ai/tool_signature_test.py b/packages/genkit/tests/genkit/ai/tool_signature_test.py index fcb09141b..dde43d597 100644 --- a/packages/genkit/tests/genkit/ai/tool_signature_test.py +++ b/packages/genkit/tests/genkit/ai/tool_signature_test.py @@ -12,7 +12,17 @@ from pydantic import BaseModel from typing_extensions import TypedDict -from genkit import FlowContext, Genkit, GenkitError, Message, ModelResponse, Part, Tool, ToolContext +from genkit import ( + FlowContext, + Genkit, + GenkitError, + Message, + ModelResponse, + MultipartToolResponse, + Part, + Tool, + ToolContext, +) from genkit._core._schema import to_json_schema from genkit._core._typing import FinishReason, Role, ToolRequest from genkit.testing import ScriptedModel, define_scripted_model @@ -509,7 +519,7 @@ async def days_until(n: int) -> str: await days_until('abc') assert exc.value.status == 'INVALID_ARGUMENT' assert days_until.input_schema == {'type': 'integer'} - assert await days_until(3) == '3 days' + assert await days_until(3) == MultipartToolResponse(output='3 days') @pytest.mark.asyncio @@ -588,8 +598,8 @@ async def test_tool_with_default_input_called_without_input_gets_default() -> No async def weather(city: str = 'Paris') -> str: return f'Sunny in {city}' - assert await weather() == 'Sunny in Paris' - assert await weather('Rome') == 'Sunny in Rome' + assert await weather() == MultipartToolResponse(output='Sunny in Paris') + assert await weather('Rome') == MultipartToolResponse(output='Sunny in Rome') @pytest.mark.asyncio @@ -623,7 +633,7 @@ async def weather(input: WeatherInput, ctx: ToolContext) -> str: result = await weather(WeatherInput(city='Paris')) - assert result == '22C in Paris (ToolContext)' + assert result == MultipartToolResponse(output='22C in Paris (ToolContext)') @pytest.mark.asyncio diff --git a/packages/genkit/tests/genkit/core/context_types_test.py b/packages/genkit/tests/genkit/core/context_types_test.py index a91499dac..2189846d4 100644 --- a/packages/genkit/tests/genkit/core/context_types_test.py +++ b/packages/genkit/tests/genkit/core/context_types_test.py @@ -35,6 +35,7 @@ Message, ModelResponse, ModelResponseChunk, + MultipartToolResponse, Operation, Part, Role, @@ -126,7 +127,9 @@ async def check_allergies(dish: str, ctx: ToolContext) -> str: auth = {'auth': {'uid': 'diner-42'}} assert await reorder_last('tartine', context=auth) == 'tartine for diner-42' - assert await check_allergies('tartine', context=auth) == 'tartine: nut-free for diner-42' + assert await check_allergies('tartine', context=auth) == MultipartToolResponse( + output='tartine: nut-free for diner-42' + ) flow_ctx, tool_ctx = seen assert type(flow_ctx) is FlowContext diff --git a/packages/genkit/tests/genkit/core/endpoints/reflection_test.py b/packages/genkit/tests/genkit/core/endpoints/reflection_test.py index 94764d997..d11d61c6b 100644 --- a/packages/genkit/tests/genkit/core/endpoints/reflection_test.py +++ b/packages/genkit/tests/genkit/core/endpoints/reflection_test.py @@ -560,8 +560,8 @@ class Shot(BaseModel): @pytest.mark.asyncio -async def test_reflection_lists_tool_and_tool_v2_rows_with_their_schemas() -> None: - """A tool lists as /tool/ (its return type) and /tool.v2/ (the envelope the Dev UI shows).""" +async def test_reflection_lists_single_tool_v2_row_with_declared_schema() -> None: + """A tool lists once at /tool.v2/ with its declared return schema as outputSchema.""" ai = Genkit() @ai.tool() @@ -574,17 +574,16 @@ async def snap(label: str) -> Shot: finally: await client.aclose() - tool_row, wire_row = listed['/tool/snap'], listed['/tool.v2/snap'] - assert tool_row['inputSchema'] == wire_row['inputSchema'] == {'type': 'string'} - assert tool_row['outputSchema']['title'] == 'Shot' - assert set(wire_row['outputSchema']['properties']) == {'output', 'content', 'metadata'} - assert tool_row['metadata']['originalOutputSchema']['title'] == 'Shot' - assert wire_row['metadata']['originalOutputSchema']['title'] == 'Shot' + assert '/tool/snap' not in listed + wire_row = listed['/tool.v2/snap'] + assert wire_row['inputSchema'] == {'type': 'string'} + assert wire_row['outputSchema']['title'] == 'Shot' + assert 'originalOutputSchema' not in (wire_row.get('metadata') or {}) @pytest.mark.asyncio -async def test_reflection_run_tool_v2_returns_envelope_and_tool_returns_value() -> None: - """Running /tool.v2/ (what the Dev UI runs) returns the envelope; /tool/ returns the value.""" +async def test_reflection_run_tool_v2_returns_envelope_and_tool_returns_404() -> None: + """Running /tool.v2/ returns the envelope; /tool/ is not registered.""" ai = Genkit() @ai.tool() @@ -594,12 +593,12 @@ async def snap(label: str) -> Shot: client = await _registry_asgi_client(ai._registry) try: wire = (await client.post('/api/runAction', json={'key': '/tool.v2/snap', 'input': 'deck'})).json() - raw = (await client.post('/api/runAction', json={'key': '/tool/snap', 'input': 'deck'})).json() + raw = await client.post('/api/runAction', json={'key': '/tool/snap', 'input': 'deck'}) finally: await client.aclose() assert wire['result'] == {'output': {'label': 'deck'}} - assert raw['result'] == {'label': 'deck'} + assert raw.status_code == 404 @pytest.mark.asyncio diff --git a/packages/genkit/tests/genkit/core/run_in_new_span_test.py b/packages/genkit/tests/genkit/core/run_in_new_span_test.py index 5674230fb..c80b1234d 100644 --- a/packages/genkit/tests/genkit/core/run_in_new_span_test.py +++ b/packages/genkit/tests/genkit/core/run_in_new_span_test.py @@ -271,7 +271,7 @@ async def test_tool_interrupt_marks_the_tool_span_interrupted_without_an_error_t async def transfer(inp: dict, ctx: ToolContext) -> str: # noqa: ARG001 raise Interrupt({'reason': 'needs_approval'}) - action = await ai._registry.resolve_action(kind=ActionKind.TOOL, name='transfer') + action = await ai._registry.resolve_action(kind=ActionKind.TOOL_V2, name='transfer') assert action is not None with caplog.at_level(logging.DEBUG): diff --git a/packages/genkit/tests/genkit/core/telemetry/trace_data_encoder_test.py b/packages/genkit/tests/genkit/core/telemetry/trace_data_encoder_test.py index 1351c37b2..4652d1271 100644 --- a/packages/genkit/tests/genkit/core/telemetry/trace_data_encoder_test.py +++ b/packages/genkit/tests/genkit/core/telemetry/trace_data_encoder_test.py @@ -93,7 +93,9 @@ def dev_ui_heading(span: dict[str, Any]) -> str: if exception.get('exception.message'): return str(exception['exception.message']) attrs = span['attributes'] - interrupted = attrs.get('genkit:metadata:subtype') == 'tool' and bool(attrs.get('genkit:metadata:interrupt')) + interrupted = attrs.get('genkit:metadata:subtype') in ('tool', 'tool.v2') and bool( + attrs.get('genkit:metadata:interrupt') + ) return 'Interrupted' if interrupted else 'Error' diff --git a/packages/genkit/tests/genkit/veneer/lookup_test.py b/packages/genkit/tests/genkit/veneer/lookup_test.py index e1048f2dd..6929c614a 100644 --- a/packages/genkit/tests/genkit/veneer/lookup_test.py +++ b/packages/genkit/tests/genkit/veneer/lookup_test.py @@ -10,7 +10,7 @@ import pytest -from genkit import FinishReason, Genkit, Message, ModelResponse, Operation, Part, Role, Tool +from genkit import FinishReason, Genkit, Message, ModelResponse, MultipartToolResponse, Operation, Part, Role, Tool from genkit._core._typing import MiddlewareRef from genkit.middleware import Middleware, MiddlewareContext, ModelHookParams from genkit.model import GenerateActionOptions, Model, ModelContext, ModelRequest @@ -120,7 +120,7 @@ async def menu_price(dish: str) -> float: assert isinstance(found, Tool) assert found.definition() == menu_price.definition() - assert await found('ramen') == 14.5 + assert await found('ramen') == MultipartToolResponse(output=14.5) @pytest.mark.asyncio @@ -157,10 +157,9 @@ async def table_status(table_id: str) -> str: found = await ai.lookup_tool('table_status') assert isinstance(found, Tool) - assert found.wire_action is None assert found.metadata is raw_action.metadata assert found.definition().output_schema == {'type': 'string'} - assert await found('T4') == 'table T4: seated' + assert await found('T4') == MultipartToolResponse(output='table T4: seated') assert Tool.from_action(found) is found diff --git a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py index 69b139451..1d51485ba 100644 --- a/packages/genkit/tests/typecheck/action_and_ref_contract_test.py +++ b/packages/genkit/tests/typecheck/action_and_ref_contract_test.py @@ -37,6 +37,7 @@ GenkitError, Message, ModelResponse, + MultipartToolResponse, Part, Role, StreamResponse, @@ -131,7 +132,7 @@ async def list_specials(ctx: ToolContext) -> list[str]: assert (await stream_res.response).total_cents == 1800 assert_type(await kitchen_status(), str) - assert_type(await list_specials(), list[str]) + assert_type(await list_specials(), MultipartToolResponse[list[str]]) with pytest.raises(GenkitError): await create_invoice() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] @@ -169,7 +170,7 @@ async def todays_soup(day: str = 'monday') -> str: assert (await suggest_dish.run()).response == 'french: tartine' assert await suggest_dish.stream().response == 'french: tartine' assert await reprint_receipt() == 'last order' - assert await todays_soup() == 'monday: bouillabaisse' + assert await todays_soup() == MultipartToolResponse(output='monday: bouillabaisse') with pytest.raises(GenkitError): await suggest_dish(3) # pyright: ignore[reportArgumentType] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] diff --git a/packages/genkit/tests/typecheck/context_contract_test.py b/packages/genkit/tests/typecheck/context_contract_test.py index 3157396db..335235b2a 100644 --- a/packages/genkit/tests/typecheck/context_contract_test.py +++ b/packages/genkit/tests/typecheck/context_contract_test.py @@ -34,6 +34,7 @@ Message, ModelResponse, ModelResponseChunk, + MultipartToolResponse, Operation, Part, Role, @@ -223,7 +224,7 @@ async def serve_order(dish: str, ctx: FlowContext[str]) -> str: return f'{dish}@{read_table(ctx)}' assert await serve_order('tartine', context={'table': 7}) == 'tartine@7' - assert await check_table('tartine', context={'table': 9}) == 'tartine@9' + assert await check_table('tartine', context={'table': 9}) == MultipartToolResponse(output='tartine@9') @pytest.mark.asyncio @@ -251,4 +252,6 @@ async def check_allergies(dish: str, ctx: ToolContext) -> str: auth = {'auth': {'uid': 'diner-42'}} assert await reorder_last('tartine', context=auth) == 'tartine for diner-42' - assert await check_allergies('tartine', context=auth) == 'tartine: nut-free for diner-42' + assert await check_allergies('tartine', context=auth) == MultipartToolResponse( + output='tartine: nut-free for diner-42' + ) diff --git a/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py b/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py index 0cc590b15..da068d9ee 100644 --- a/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py +++ b/packages/genkit/tests/typecheck/flow_tool_shapes_contract_test.py @@ -36,7 +36,7 @@ from pydantic import BaseModel from typing_extensions import assert_type -from genkit import Flow, FlowContext, Genkit, GenkitError, Tool, ToolContext +from genkit import Flow, FlowContext, Genkit, GenkitError, MultipartToolResponse, Tool, ToolContext from genkit._ai._tools import define_tool from genkit._core._flow import DefaultedFlow, define_flow from genkit._core._registry import Registry @@ -428,12 +428,12 @@ async def find_table(res_id: str | None = 'R-100') -> str: return res_id or 'bar seat' # 1. Omit the input to use the default, or pass a str - assert await check_allergens() == 'pad thai: peanuts' - assert await check_allergens('larb') == 'larb: peanuts' + assert await check_allergens() == MultipartToolResponse(output='pad thai: peanuts') + assert await check_allergens('larb') == MultipartToolResponse(output='larb: peanuts') # 2. Omitting the input uses the default; an explicit None is a value, same as flows - assert await find_table() == 'R-100' - assert await find_table(None) == 'bar seat' + assert await find_table() == MultipartToolResponse(output='R-100') + assert await find_table(None) == MultipartToolResponse(output='bar seat') # 3. None isn't a str with pytest.raises(GenkitError): @@ -472,14 +472,14 @@ def menu_tool(t: Tool[str, str]) -> str: async def call_flow_no_input(f: Flow[str, str]) -> str: return await f() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] - async def call_tool_no_input(t: Tool[str, str]) -> str: + async def call_tool_no_input(t: Tool[str, str]) -> MultipartToolResponse[str]: return await t() # pyright: ignore[reportCallIssue] # pyrefly: ignore[no-matching-overload] # ty: ignore[invalid-argument-type] # 3. Through a Flow[str, str] / Tool[str, str] parameter, passing str works and omitting input fails the type check assert await by_cuisine('thai') == 'thai: risotto' - assert await allergens('larb') == 'larb: peanuts' + assert await allergens('larb') == MultipartToolResponse(output='larb: peanuts') assert await call_flow_no_input(todays_special) == 'italian: risotto' - assert await call_tool_no_input(check_allergens) == 'pad thai: peanuts' + assert await call_tool_no_input(check_allergens) == MultipartToolResponse(output='pad thai: peanuts') @pytest.mark.asyncio @@ -496,8 +496,8 @@ async def check_allergens(dish: str = 'pad thai') -> str: deep = copy.deepcopy(check_allergens) assert isinstance(shallow, DefaultedTool) assert isinstance(deep, DefaultedTool) - assert await shallow() == 'pad thai: peanuts' - assert await deep() == 'pad thai: peanuts' + assert await shallow() == MultipartToolResponse(output='pad thai: peanuts') + assert await deep() == MultipartToolResponse(output='pad thai: peanuts') # 2. Tool.from_action returns the same object assert Tool.from_action(check_allergens) is check_allergens