Skip to content

refactor(py): register tools as a single tool.v2 action - #279

Open
genkit-bot wants to merge 1 commit into
genkit-ai:mainfrom
genkit-bot:factory/issue-183-d86e2563
Open

genkit-bot wants to merge 1 commit into
genkit-ai:mainfrom
genkit-bot:factory/issue-183-d86e2563

Conversation

@genkit-bot

Copy link
Copy Markdown

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 the MultipartToolResponse envelope as its outputSchema while stashing the declared return schema under metadata['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

  • Single tool.v2 action (packages/genkit/src/genkit/_core/_tool.py, _registry.py, _ai/_tools.py):
    • Register every Tool as a single ActionKind.TOOL_V2 (/tool.v2/<name>) action and drop the /tool/<name> dual registration and wire_action companion.
    • Advertise the declared return type T directly as output_schema (None for bare MultipartToolResponse / MultipartToolResponse[Any]). Remove ORIGINAL_OUTPUT_SCHEMA_KEY (originalOutputSchema) and Tool.model_output_schema.
    • Wrap handler returns in Tool._wrap_response so await tool(x), tool.run(x).response, and tool.stream(x).response always return MultipartToolResponse[T] (wrapping plain return value into MultipartToolResponse(output=value)), validating live parts, JSON-serializable metadata/output, and parsing non-None output against T while keeping output=None valid.
    • Parameterize Tool and DefaultedTool over Action[InputT, MultipartToolResponse[OutputT], ChunkT, None] with Coroutine[Any, Any, MultipartToolResponse[...]] overloads across Tool, define_tool, @ai.tool, and _ToolDecorator so -> MultipartToolResponse[T] handlers do not double-wrap statically or at runtime.
  • Lookups, DAP resolution, reflection, and sibling packages:
    • Prefer ActionKind.TOOL_V2 with fallback to legacy ActionKind.TOOL in Genkit.lookup_tool, resolve_tool, and DAP 'tool' bucket resolution (_registry.py, _ai/_aio.py, _ai/_generate.py).
    • Serialize reflection v1/v2 BaseModel responses with mode='json' (_core/_reflection.py, _core/_reflection_v2.py) so MultipartToolResponse carrying typed Pydantic models or datetime fields serializes cleanly over reflection.
    • Update genkit-mcp (_tools.py, _client.py) to set handle.output_schema directly instead of handle.model_output_schema.
    • Update ToolApproval (packages/genkit-middleware/src/genkit_middleware/_tool_approval.py) to emit ActionKind.TOOL_V2 spans; genkit-otel already matches both 'tool' and 'tool.v2'.
  • Tests:
    • Updated unit, reflection, telemetry, MCP, middleware, and typecheck contract tests for single /tool.v2/<name> registration, direct output_schema, MultipartToolResponse return contract, optional output=None validation, output parsing/validation errors, and lookup_tool fallback ordering.

Verification

  • Before/after reproduction:
    • Before: registering @ai.tool(name='weather') produced tool_keys: ['/tool.v2/weather', '/tool/weather'], /tool.v2/weather had the envelope output_schema with metadata={'originalOutputSchema': {'type': 'string'}}, and await weather('Austin') returned 'Sunny in Austin'.
    • After: registering @ai.tool(name='weather') produces tool_keys: ['/tool.v2/weather'], /tool.v2/weather has action_type='tool.v2', output_schema={'type': 'string'}, metadata=None, and await weather('Austin') returns MultipartToolResponse(output='Sunny in Austin', content=None, metadata=None).
  • Linters and formatting:
    • 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).
  • Typecheckers:
    • 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).
  • Tests:
    • 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_timeout and packages/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.toolResponseContent fallback middleware and MCP client toolResponseMode remain separate follow-up tasks, as scoped in the issue discussion.

Fixes #183

@genkit-bot genkit-bot left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]):

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Register tools as a single tool.v2 action (match Genkit Dart and JS v2)

2 participants