Skip to content

fix(py)!: a Tool is an Action; await tool(x) returns what the function returned - #6681

Merged
huangjeff5 merged 3 commits into
mainfrom
fix/py-tool-call-returns-value
Nov 3, 2026
Merged

huangjeff5 merged 3 commits into
mainfrom
fix/py-tool-call-returns-value

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Stack 1/2. Base PR on main. #6314 stacks on this and adds typed tool chunk streaming.

A Tool is now an Action. await tool(x) returns whatever your function returned, with zero framework wrapping. If your tool returns a string or a Pydantic model, you get back that string or model directly (instead of Genkit forcibly boxing it inside a MultipartToolResponse wire envelope). If your tool explicitly constructs and returns a MultipartToolResponse (to attach media/content parts for the model), you get back that MultipartToolResponse with your live output intact. This matches JS.

from pydantic import BaseModel
from genkit import Genkit, MultipartToolResponse, Part, Role

ai = Genkit(model='googleai/gemini-flash-latest')


class OrderItem(BaseModel):
    sku: str
    quantity: int


class PriceQuote(BaseModel):
    sku: str
    total_cents: int


class DishCheck(BaseModel):
    dish_name: str
    plate_temp_c: int


# 1. Plain typed tool (returns PriceQuote)
@ai.tool()
async def quote_item(item: OrderItem) -> PriceQuote:
    return PriceQuote(sku=item.sku, total_cents=item.quantity * 1450)


# 2. Multipart tool (explicitly returns MultipartToolResponse to attach an image)
@ai.tool()
async def inspect_plating(dish_name: str) -> MultipartToolResponse[DishCheck]:
    photo = Part.from_media('data:image/png;base64,abc', content_type='image/png')
    return MultipartToolResponse(
        output=DishCheck(dish_name=dish_name, plate_temp_c=62),
        content=[photo],
        metadata={'camera_id': 'pass-1'},
    )


# --- BEFORE (on main) ---
# Framework forcibly boxed EVERY return into a MultipartToolResponse envelope
# and pre-dumped its output into an untyped dict:
env = await quote_item(OrderItem(sku='TARTINE-SMOKED-SALMON', quantity=2))
print(type(env), env.output)
# => <class 'MultipartToolResponse'> {'sku': 'TARTINE-SMOKED-SALMON', 'total_cents': 2900}  (not a PriceQuote!)

check_env = await inspect_plating('Duck Confit')
print(type(check_env.output))
# => <class 'dict'>  (pre-dumped to a dict instead of the live DishCheck)


# --- AFTER ---
# The framework never wraps or unwraps your return value:

# A. Plain tool direct call -> returns exactly what the function returned (live PriceQuote)
quote = await quote_item(OrderItem(sku='TARTINE-SMOKED-SALMON', quantity=2))
print(repr(quote))
# => PriceQuote(sku='TARTINE-SMOKED-SALMON', total_cents=2900)

# B. Multipart tool direct call -> returns the MultipartToolResponse your function built,
#    with your live DishCheck model on .output (not pre-dumped to a dict)
check = await inspect_plating('Duck Confit')
print(repr(check.output))
# => DishCheck(dish_name='Duck Confit', plate_temp_c=62)
print(len(check.content), check.metadata)
# => 1 {'camera_id': 'pass-1'}

# C. Plain tool through ai.generate -> Genkit normalizes it to JSON on the wire ToolResponse
res = await ai.generate(prompt='Quote 2 smoked salmon tartines.', tools=[quote_item])
tool_part = next(m for m in res.messages if m.role == Role.TOOL).content[0]
print(tool_part.tool_response.output, tool_part.tool_response.content)
# => {'sku': 'TARTINE-SMOKED-SALMON', 'total_cents': 2900} None

# D. Multipart tool through ai.generate -> model binds DishCheck schema; ToolResponse carries JSON output + media
res = await ai.generate(prompt='Check Duck Confit plating.', tools=[inspect_plating])
tool_part = next(m for m in res.messages if m.role == Role.TOOL).content[0]
print(tool_part.tool_response.output)
# => {'dish_name': 'Duck Confit', 'plate_temp_c': 62}
print(tool_part.tool_response.content)
# => [{'media': {'contentType': 'image/png', 'url': 'data:image/png;base64,abc'}}]
print(tool_part.metadata)
# => {'camera_id': 'pass-1'}

Main Changes

  • Tool subclasses Action instead of wrapping one: Previously, Tool wrapped a private Action because register_action only built plain Action instances and forcibly adapted every tool function to return a MultipartToolResponse envelope—so the inner Action and outer Tool disagreed on both output schema and return type. Making Tool a real Action subclass (like Flow) drops that wrapper indirection while keeping Tool a distinct type so tools=[...] still rejects flows and models.

  • Tool always returns what the function returned (OutputT): Previously, await tool(x) returned a framework-constructed MultipartToolResponse envelope with output pre-dumped to JSON. Now /tool/<name> returns OutputT on every call path:

    • If the function returned PriceQuote, direct invocation yields PriceQuote.
    • If the function returned str, direct invocation yields str.
    • If the function explicitly returned MultipartToolResponse[DishCheck] (because it attaches media parts for the model), direct invocation yields that MultipartToolResponse, but with the live DishCheck instance preserved on .output rather than pre-dumped to a dictionary.
  • Envelope conversion moves exclusively to wire boundaries: Inside ai.generate, the tool execution loop runs Tool and normalizes OutputT via as_multipart_tool_response only when constructing the Role.TOOL Part for the model turn (dump_tool_output runs model_dump(mode='json', by_alias=True), keeping snake_case fields as-is on standard BaseModels and honoring configured aliases). Return annotations written -> MultipartToolResponse[T] peel T for tool.definition().output_schema so the model sees DishCheck's schema rather than the wire envelope. For the Dev UI and external HTTP callers, a separate /tool.v2/<name> registry entry returns the wire envelope—matching JS's dual tool / tool.v2 registration.

  • Direct calls still catch unserializable outputs early: Tool._invoke dry-runs as_multipart_tool_response before returning OutputT. Returning a non-serializable object or an empty media part raises INVALID_ARGUMENT immediately in a unit test (await tool(x)), not only inside ai.generate.

Breaking changes

  • await tool(x) returns the function's value directly. Drop .output on plain tool results (e.g. res = await quote(...) gives PriceQuote, not res.output).
  • On -> MultipartToolResponse[T] tools, res.output is now the live typed T instance instead of a pre-dumped dict.
  • Tool.action() is removed; pass the Tool itself (it is an Action).
  • ActionKind.TOOL is 'tool' and ActionKind.TOOL_V2 is 'tool.v2'. Tool spans inside generate now report action type tool instead of tool.v2.
  • For -> MultipartToolResponse[T], tool.output_schema is the envelope schema; the schema bound by the model is tool.definition().output_schema.

Parity

  • JS: defineTool registers tool (raw output) and tool.v2 (envelope), and await tool(x) returns the raw output. Python now matches 1:1.
  • Go: registers one tool.v2 action under both keys, and RunRaw returns the unwrapped output.

Landing notes

Import-line conflicts only (_tools.py with #6767, _registry.py with #6947).

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request refactors tool registration and invocation in the Genkit Python SDK so that directly awaiting a tool returns the underlying function's actual return type rather than a wrapped MultipartToolResponse envelope. This is achieved by introducing a generic Tool class, a new _ToolDecorator with overloads for type safety, and a direct_call context variable to intercept direct calls. Additionally, the test suite has been updated to reflect these changes. Feedback on the changes points out a typo in a type-ignore comment (# ty: ignore instead of # type: ignore) in the test suite.

@huangjeff5
huangjeff5 changed the base branch from main to feat/py-stream-response October 12, 2026 19:28
@huangjeff5 huangjeff5 changed the title fix(py)!: calling a tool directly returns what the function returned fix(py)!: Tool is an Action[In, Out, Chunk]; calling a tool returns what the function returned Oct 12, 2026
Base automatically changed from feat/py-stream-response to main October 29, 2026 17:13
@github-actions github-actions Bot added the docs Improvements or additions to documentation label Oct 31, 2026
@huangjeff5
huangjeff5 force-pushed the fix/py-tool-call-returns-value branch from 6347b07 to bd09f7e Compare November 1, 2026 02:21
@huangjeff5 huangjeff5 changed the title fix(py)!: Tool is an Action[In, Out, Chunk]; calling a tool returns what the function returned fix(py)!: Tool is an Action[In, Out]; calling a tool returns what the function returned Nov 1, 2026
@huangjeff5
huangjeff5 added this pull request to stack #6989 November 1, 2026 02:23
@huangjeff5 huangjeff5 changed the title fix(py)!: Tool is an Action[In, Out]; calling a tool returns what the function returned fix(py)!: a Tool is an Action; await tool(x) returns what the function returned Nov 2, 2026
@huangjeff5
huangjeff5 force-pushed the fix/py-tool-call-returns-value branch from bd09f7e to 01c6751 Compare November 2, 2026 12:43
@huangjeff5
huangjeff5 requested a review from pavelgj November 2, 2026 17:21

@pavelgj pavelgj left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM with comments

@huangjeff5
huangjeff5 force-pushed the fix/py-tool-call-returns-value branch from 01c6751 to 5e54343 Compare November 2, 2026 23:05
@huangjeff5
huangjeff5 force-pushed the fix/py-tool-call-returns-value branch from 5e54343 to 6427a91 Compare November 2, 2026 23:57
@huangjeff5
huangjeff5 force-pushed the fix/py-tool-call-returns-value branch from 6427a91 to 00d7a99 Compare November 3, 2026 00:46
@huangjeff5
huangjeff5 merged commit 2ecb9fa into main Nov 3, 2026
25 checks passed
@huangjeff5
huangjeff5 deleted the fix/py-tool-call-returns-value branch November 3, 2026 02:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation fix python Python

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants