Repository navigation
feat(py): stream typed tool chunks via ToolContext[ChunkT] - #6314
Conversation
There was a problem hiding this comment.
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.
51f5443 to
de8691d
Compare
5f1b048 to
177ec3c
Compare
|
@gemini review |
There was a problem hiding this comment.
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.
620a604 to
e0eb4c3
Compare
e0eb4c3 to
5ac1482
Compare
5ac1482 to
71127c2
Compare
Tools can stream typed progress. Annotate
ctx: ToolContext[ChunkT]and callctx.send_chunk(...).tool.stream(x)yields those values asChunkT.ai.generate_stream,prompt.streamandagent.send_streamsurface them as partialToolResponseparts that never enter history.Main Changes
Tool[In, Out, Chunk], with 2-arg still valid:Toolgains a third type parameter,ChunkT, defaulted toAny, which@ai.tool,define_toolandTool(fn)infer fromToolContext[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.generate_stream, eachsend_chunkvalue becomes aRole.TOOLchunk holding aToolResponsewith the call'sname/refandmetadata: {'partial': true}, readable aspart.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.Message/Part, each chunk goes through the samedump_tool_outputJSON serialization path as a finalToolResponse(model_dump(mode='json', by_alias=True), keeping snake_case fields on plainBaseModels and honoring aliases when configured), and dicts/lists are snapshotted when sent. Directtool.stream()has noPartenvelope and hands back the liveChunkTobject.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 finalToolResponseor on a model chunk still fails the turn.send_chunkafter the tool returns or interrupts is a no-op. A tool awaited directly inside another tool doesn't stream under the outer call'sref. Without a stream consumer,send_chunkis a no-op.Parity
tool.SendChunk(ctx, *ai.ModelResponseChunk). The tool builds the whole chunk itself, and it uses the samepartial: truemarker (NewPartialToolResponsePart,Part.IsPartial).ToolFnOptions extends ActionFnArg<never>).ToolResponsefor 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 typedChunkTpayload and wraps it as a partialToolResponsefor the current call'sname/ref. We went one level higher because the tool can't get therefwrong andtool.stream()can yieldChunkTdirectly. The wire is identical, so a client readingmetadata.partialsees 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.pyis 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_compatibilitytest_tool_stream_yields_typed_chunks_and_outputtest_generate_stream_emits_partial_tool_response_before_finaltest_wire_shape_parity_camelcase_basemodel_and_datetime_vs_direct_tool_streamtest_generate_stream_excludes_partial_chunks_from_next_model_turn_and_response_messagestest_agent_send_stream_surfaces_tool_responses_and_excludes_partials_from_messagesThe 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 checkpytest packages/genkit packages/genkit-mcp packages/genkit-middleware packages/genkit-otel: 3189 passed