Skip to content

feat(py): stream typed tool chunks via ToolContext[ChunkT] - #6314

Merged
huangjeff5 merged 2 commits into
fix/py-tool-call-returns-valuefrom
feat/l1-tool-send-chunk
Nov 3, 2026
Merged

huangjeff5 merged 2 commits into
fix/py-tool-call-returns-valuefrom
feat/l1-tool-send-chunk

Conversation

@huangjeff5

@huangjeff5 huangjeff5 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Stack 2/2. Stacked on #6681. Review #6681 first.

Tools can stream typed progress. Annotate ctx: ToolContext[ChunkT] and call ctx.send_chunk(...). tool.stream(x) yields those values as ChunkT. ai.generate_stream, prompt.stream and agent.send_stream surface them as partial ToolResponse parts that never enter history.

from pydantic import BaseModel
from genkit import Genkit, ToolContext

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


class PrepProgress(BaseModel):
    stage_name: str
    percent: int


# 1. Type the context with the chunk you send
@ai.tool()
async def prepare_order(dish: str, ctx: ToolContext[PrepProgress]) -> str:
    ctx.send_chunk(PrepProgress(stage_name='searing', percent=40))
    ctx.send_chunk(PrepProgress(stage_name='plating', percent=90))
    return f'{dish} ready for pickup'


# --- BEFORE (on #6681) ---
# prepare_order.stream(...) already yielded send_chunk values, but typed Any.
# generate_stream dropped them: nothing between the ToolRequest and the final ToolResponse.

# --- AFTER ---
# 2. Direct stream yields live PrepProgress instances; response is the str
direct = prepare_order.stream('Duck Confit')
async for step in direct:
    print(repr(step))
# => PrepProgress(stage_name='searing', percent=40)
#    PrepProgress(stage_name='plating', percent=90)
print(await direct.response)
# => Duck Confit ready for pickup

# 3. generate_stream emits partial ToolResponse parts (JSON-dumped like final outputs), then the final one
stream = ai.generate_stream(prompt='Prepare Duck Confit.', tools=[prepare_order])
async for chunk in stream:
    for part in chunk.tool_responses:
        print(part.is_partial, part.tool_response.output)
# => True {'stage_name': 'searing', 'percent': 40}
#    True {'stage_name': 'plating', 'percent': 90}
#    False Duck Confit ready for pickup

Main Changes

  • Tool[In, Out, Chunk], with 2-arg still valid: Tool gains a third type parameter, ChunkT, defaulted to Any, which @ai.tool, define_tool and Tool(fn) infer from ToolContext[ChunkT]. Tool[In, Out] annotations from fix(py)!: a Tool is an Action; await tool(x) returns what the function returned #6681 keep working, including at runtime on 3.10.
  • Progress shows up in generate streams, not in history: During generate_stream, each send_chunk value becomes a Role.TOOL chunk holding a ToolResponse with the call's name/ref and metadata: {'partial': true}, readable as part.is_partial. History, response.messages, the next model turn and agent snapshots keep only the final return, because replaying progress bars to the model wastes tokens and confuses it.
  • Partials use the same wire shape as the final response: Inside Message / Part, each chunk goes through the same dump_tool_output JSON serialization path as a final ToolResponse (model_dump(mode='json', by_alias=True), keeping snake_case fields on plain BaseModels and honoring aliases when configured), and dicts/lists are snapshotted when sent. Direct tool.stream() has no Part envelope and hands back the live ChunkT object.
  • Progress is best-effort; the return value is authoritative: A partial chunk that can't serialize, or a chunk callback that raises on it, gets logged at debug and dropped, and the tool keeps running. Go does the same in toolStreamer.send (go/ai/generate.go): log at debug, drop the chunk. We kept Go's rule so a flaky progress sink can't abort a side-effecting tool halfway. A raising callback on the final ToolResponse or on a model chunk still fails the turn. send_chunk after the tool returns or interrupts is a no-op. A tool awaited directly inside another tool doesn't stream under the outer call's ref. Without a stream consumer, send_chunk is a no-op.

Parity

  • Go: tool.SendChunk(ctx, *ai.ModelResponseChunk). The tool builds the whole chunk itself, and it uses the same partial: true marker (NewPartialToolResponsePart, Part.IsPartial).
  • JS: no tool chunk streaming (ToolFnOptions extends ActionFnArg<never>).
  • Python sends a typed payload and wraps it in the partial ToolResponse for you. The wire shape matches Go; the authoring API is one level higher.

Decision for reviewers

Go makes the tool build the whole ModelResponseChunk. Python takes a typed ChunkT payload and wraps it as a partial ToolResponse for the current call's name/ref. We went one level higher because the tool can't get the ref wrong and tool.stream() can yield ChunkT directly. The wire is identical, so a client reading metadata.partial sees the same parts from a Go or Python tool. If we'd rather match Go's lower-level API, that's a follow-up that only changes the authoring side.

Reviewing the tests

streaming_tool_send_chunk_test.py is 1328 lines across 37 tests, and each test's name and docstring say what it covers. These 6 are the contract:

  • test_tool_chunk_type_inference_and_two_arg_compatibility
  • test_tool_stream_yields_typed_chunks_and_output
  • test_generate_stream_emits_partial_tool_response_before_final
  • test_wire_shape_parity_camelcase_basemodel_and_datetime_vs_direct_tool_stream
  • test_generate_stream_excludes_partial_chunks_from_next_model_turn_and_response_messages
  • test_agent_send_stream_surfaces_tool_responses_and_excludes_partials_from_messages

The rest are edge cases (concurrency, interrupt/resume, cancellation, max_turns, middleware) and can be skimmed by name.

Verification

  • ruff format --check, ruff check --preview, pyright, pyrefly check, ty check
  • pytest packages/genkit packages/genkit-mcp packages/genkit-middleware packages/genkit-otel: 3189 passed

@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 implements support for streaming tool-role chunks via ToolRunContext.send_chunk during generate_stream. It updates the chunk accumulator to handle role changes properly, propagates the tool chunk streaming callback through the tool execution pipeline, and adds comprehensive tests. Feedback is provided on normalize_send_chunk_parts to optimize list validation by avoiding an unnecessary list copy and using typing.cast instead.

@huangjeff5
huangjeff5 force-pushed the feat/l1-tool-send-chunk branch from 51f5443 to de8691d Compare September 9, 2026 06:34
@huangjeff5 huangjeff5 changed the title feat(py): stream tool send_chunk on generate feat(py): stream tool send_chunk and send_partial on generate Sep 9, 2026
@huangjeff5
huangjeff5 force-pushed the feat/l1-tool-send-chunk branch from 5f1b048 to 177ec3c Compare October 12, 2026 05:15
@huangjeff5 huangjeff5 changed the title feat(py): stream tool send_chunk and send_partial on generate feat(py): stream typed tool chunks via ToolContext[ChunkT] Oct 12, 2026
@huangjeff5
huangjeff5 changed the base branch from main to feat/py-stream-response October 12, 2026 07:44
@huangjeff5
huangjeff5 added this pull request to stack #6772 October 12, 2026 07:47
@huangjeff5

Copy link
Copy Markdown
Contributor Author

@gemini review

@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 introduces support for streaming partial tool responses during tool execution via ToolContext.send_chunk and refactors the Tool class to be generic, allowing direct tool calls to return the function's actual return type instead of a wrapped envelope. Feedback points out a critical runtime crash on Python 3.10–3.12 when subscripting Tool with fewer than three type arguments, which can be resolved by inheriting from typing_extensions.Generic instead of typing.Generic.

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 feat/l1-tool-send-chunk branch from 620a604 to e0eb4c3 Compare November 1, 2026 02:21
@huangjeff5
huangjeff5 removed this pull request from stack #6772 November 1, 2026 02:22
@huangjeff5
huangjeff5 changed the base branch from main to fix/py-tool-call-returns-value November 1, 2026 02:23
@huangjeff5
huangjeff5 added this pull request to stack #6989 November 1, 2026 02:23
@huangjeff5
huangjeff5 force-pushed the feat/l1-tool-send-chunk branch from e0eb4c3 to 5ac1482 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 feat/l1-tool-send-chunk branch from 5ac1482 to 71127c2 Compare November 3, 2026 00:46
@huangjeff5
huangjeff5 merged commit 15a8f8f into main Nov 3, 2026
25 checks passed
@huangjeff5
huangjeff5 deleted the feat/l1-tool-send-chunk 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 python Python

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants