Repository navigation
refactor(py): register tools as a single tool.v2 action - #279
genkit-bot wants to merge 1 commit into
Conversation
Requested-by: huangjeff5
genkit-bot
left a comment
There was a problem hiding this comment.
Intentional breaking API change matching issue 183: direct tool calls now return MultipartToolResponse[OutputT], tools register only at /tool.v2/<name>, Tool.wire_action / Tool.model_output_schema / metadata['originalOutputSchema'] are removed, and non-None outputs are validated against the declared return type.
LGTM with comments
Details
Run 29b6061c-6b67-4bc1-969e-1620b5890688 · Cloud Run logs · Dashboard
|
|
||
| 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]): |
There was a problem hiding this comment.
[Nit] Breaking public API change (matching issue 183): Tool now subclasses Action[InputT, MultipartToolResponse[OutputT], ChunkT, None] with kind=ActionKind.TOOL_V2, so direct await tool(...) / .run() / .stream() calls return MultipartToolResponse[OutputT] instead of raw OutputT, /tool/<name> dual registration is dropped, Tool.wire_action and Tool.model_output_schema are removed in favor of tool.output_schema, and non-None outputs are now validated against the declared return type. Worth noting in the release notes or migration guide for callers upgrading from direct Tool invocation or model_output_schema.
| with pytest.raises(GenkitError) as exc: | ||
| await bad_shot() | ||
| assert exc.value.status == 'INTERNAL' | ||
| assert exc.value.reason is ErrorReason.INVALID_OUTPUT |
There was a problem hiding this comment.
This exercises output parsing and INVALID_OUTPUT rejection for a plain -> ShotOut tool (inner is NOT_ENVELOPE in Tool.__init__), while test_multipart_tool_response_allows_none_output_with_typed_schema only checks output=None on -> MultipartToolResponse[ShotOut]. Consider adding a case on a -> MultipartToolResponse[ShotOut] tool returning a non-None dict and an invalid output shape so the peeled-inner branch of _declared_output_type in Tool.__init__ is directly pinned too.
Problem
Tools in Genkit Python were dual-registered under both
/tool/<name>and a hidden companion/tool.v2/<name>action (Tool.wire_action). The/tool.v2/<name>manifest advertised theMultipartToolResponseenvelope as itsoutputSchemawhile stashing the declared return schema undermetadata['originalOutputSchema'](Tool.model_output_schema). Direct tool calls (await tool(x)) returned raw handler values whereas/tool.v2/<name>returned the envelope. This diverged from Genkit Dart and JS v2, doubled tool entries in the registry and reflection listing, and added unnecessary schema indirection.Fix
tool.v2action (packages/genkit/src/genkit/_core/_tool.py,_registry.py,_ai/_tools.py):Toolas a singleActionKind.TOOL_V2(/tool.v2/<name>) action and drop the/tool/<name>dual registration andwire_actioncompanion.Tdirectly asoutput_schema(Nonefor bareMultipartToolResponse/MultipartToolResponse[Any]). RemoveORIGINAL_OUTPUT_SCHEMA_KEY(originalOutputSchema) andTool.model_output_schema.Tool._wrap_responsesoawait tool(x),tool.run(x).response, andtool.stream(x).responsealways returnMultipartToolResponse[T](wrapping plainreturn valueintoMultipartToolResponse(output=value)), validating live parts, JSON-serializable metadata/output, and parsing non-NoneoutputagainstTwhile keepingoutput=Nonevalid.ToolandDefaultedTooloverAction[InputT, MultipartToolResponse[OutputT], ChunkT, None]withCoroutine[Any, Any, MultipartToolResponse[...]]overloads acrossTool,define_tool,@ai.tool, and_ToolDecoratorso-> MultipartToolResponse[T]handlers do not double-wrap statically or at runtime.ActionKind.TOOL_V2with fallback to legacyActionKind.TOOLinGenkit.lookup_tool,resolve_tool, and DAP'tool'bucket resolution (_registry.py,_ai/_aio.py,_ai/_generate.py).BaseModelresponses withmode='json'(_core/_reflection.py,_core/_reflection_v2.py) soMultipartToolResponsecarrying typed Pydantic models ordatetimefields serializes cleanly over reflection.genkit-mcp(_tools.py,_client.py) to sethandle.output_schemadirectly instead ofhandle.model_output_schema.ToolApproval(packages/genkit-middleware/src/genkit_middleware/_tool_approval.py) to emitActionKind.TOOL_V2spans;genkit-otelalready matches both'tool'and'tool.v2'./tool.v2/<name>registration, directoutput_schema,MultipartToolResponsereturn contract, optionaloutput=Nonevalidation, output parsing/validation errors, andlookup_toolfallback ordering.Verification
@ai.tool(name='weather')producedtool_keys: ['/tool.v2/weather', '/tool/weather'],/tool.v2/weatherhad the envelopeoutput_schemawithmetadata={'originalOutputSchema': {'type': 'string'}}, andawait weather('Austin')returned'Sunny in Austin'.@ai.tool(name='weather')producestool_keys: ['/tool.v2/weather'],/tool.v2/weatherhasaction_type='tool.v2',output_schema={'type': 'string'},metadata=None, andawait weather('Austin')returnsMultipartToolResponse(output='Sunny in Austin', content=None, metadata=None).uv run --no-sync --python 3.11 ruff check <modified-files>- passed (0 errors).uv run --no-sync --python 3.11 ruff format --check <modified-files>- passed (35 files formatted).uv run --no-sync --python 3.11 pyright- passed (0 errors, 0 warnings).uv run --no-sync --python 3.11 pyrefly check- passed (0 errors).uv run --no-sync --python 3.11 ty check packages/genkit/src packages/genkit/tests/typecheck packages/genkit/tests/genkit/ai/tool_response_contract_test.py packages/genkit/tests/genkit/ai/streaming_tool_send_chunk_test.py packages/genkit-mcp/src packages/genkit-middleware/src packages/genkit-otel/src- passed (all checks passed).uv run --no-sync --python 3.11 pytest packages/genkit/tests packages/genkit-mcp/tests packages/genkit-middleware/tests packages/genkit-otel/tests packages/genkit-google-cloud/tests -q- 4170 passed, 16 skipped, 2 pre-existing environment/Python 3.11 failures unrelated to this change (packages/genkit/tests/genkit/core/compat_test.py::test_cancelled_history_reads_stamp_from_wait_for_and_timeoutandpackages/genkit-mcp/tests/mcp_connection_test.py::test_close_reaps_what_a_wrapped_server_spawned).uv run --no-sync --python 3.11 pytest packages/genkit-a2ui/tests packages/genkit-amazon-bedrock/tests packages/genkit-anthropic/tests packages/genkit-django/tests packages/genkit-evaluators/tests packages/genkit-fastapi/tests packages/genkit-flask/tests packages/genkit-google-genai/tests packages/genkit-ollama/tests packages/genkit-openai/tests packages/genkit-vertexai/tests -q- 4372 passed, 29 skipped, 0 failed.Follow-ups
supports.toolResponseContentfallback middleware and MCP clienttoolResponseModeremain separate follow-up tasks, as scoped in the issue discussion.Fixes #183