Add an API for streaming tool calls performed by HandleResponseNode #831
+157
−62
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This adds a
run_stream
method toHandleResponseNode
in the Agent graph. That method is an AsyncContextManager yielding a stream (the pattern we use to ensure async-generator-wrapping spans get closed), and that stream yields events with information about tool calls being performed by the agent.(We can eventually add other events if desired, including possibly a way for users to emit custom events in their tools through a method on the GraphContext, but I think this is more than enough to start with.)
Once we expose a way to call the
Agent
graph'snext
method, I believe this will be usable as a way to handle full agent event streaming — you'll usenext
to transition between nodes, and nodes with interesting events will have arun_stream
(or similar) method for streaming those events.I'm okay not merging this until we have a more fully-baked implementation of agent streaming (which I'll work on now), but I'm opening this PR now to get some early feedback.
I'll note that if we want to provide a way to inject control over the operation of the agent as part of the streaming (e.g., being able to see the list of tool calls and programmatically modify it before they are executed), instead of just providing a stream of events we could make use of a nested graph and expose its
next
call to the user. But I don't currently see a compelling use case for that (at least forpydantic_ai.Agent
; I could imagine it being useful in more sophisticated graph-based applications), and I don't think it's worth the extra complexity.