-
Notifications
You must be signed in to change notification settings - Fork 613
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Use .iter()
API to fully replace existing streaming implementation
#951
Merged
Merged
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
6586af3
Use .iter() API to fully replace existing streaming implementation
dmontagu 6659a0d
Use async for in the docs
dmontagu d865202
Merge branch 'main' into dmontagu/graph-run-streaming
dmontagu 633d950
A bit more clean-up
dmontagu 181578b
Fix typeguard import
dmontagu 8f383b4
Update test
dmontagu 6e0e0c7
Fix test
dmontagu 375523d
Merge main
dmontagu 09b4319
Update tests a bit
dmontagu e73b85b
Update coverage
dmontagu File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,15 +2,14 @@ | |
|
||
import asyncio | ||
import dataclasses | ||
from abc import ABC | ||
from collections.abc import AsyncIterator, Iterator, Sequence | ||
from contextlib import asynccontextmanager, contextmanager | ||
from contextvars import ContextVar | ||
from dataclasses import field | ||
from typing import Any, Generic, Literal, Union, cast | ||
|
||
import logfire_api | ||
from typing_extensions import TypeVar, assert_never | ||
from typing_extensions import TypeGuard, TypeVar, assert_never | ||
|
||
from pydantic_graph import BaseNode, Graph, GraphRunContext | ||
from pydantic_graph.nodes import End, NodeRunEndT | ||
|
@@ -55,6 +54,7 @@ | |
logfire._internal.stack_info.NON_USER_CODE_PREFIXES += (str(Path(__file__).parent.absolute()),) | ||
|
||
T = TypeVar('T') | ||
S = TypeVar('S') | ||
NoneType = type(None) | ||
EndStrategy = Literal['early', 'exhaustive'] | ||
"""The strategy for handling multiple tool calls when a final result is found. | ||
|
@@ -107,8 +107,31 @@ class GraphAgentDeps(Generic[DepsT, ResultDataT]): | |
run_span: logfire_api.LogfireSpan | ||
|
||
|
||
class AgentNode(BaseNode[GraphAgentState, GraphAgentDeps[DepsT, Any], result.FinalResult[NodeRunEndT]]): | ||
"""The base class for all agent nodes. | ||
|
||
Using subclass of `BaseNode` for all nodes reduces the amount of boilerplate of generics everywhere | ||
""" | ||
|
||
|
||
def is_agent_node( | ||
node: BaseNode[GraphAgentState, GraphAgentDeps[T, Any], result.FinalResult[S]] | End[result.FinalResult[S]], | ||
) -> TypeGuard[AgentNode[T, S]]: | ||
"""Check if the provided node is an instance of `AgentNode`. | ||
|
||
Usage: | ||
|
||
if is_agent_node(node): | ||
# `node` is an AgentNode | ||
... | ||
|
||
This method preserves the generic parameters on the narrowed type, unlike `isinstance(node, AgentNode)`. | ||
""" | ||
return isinstance(node, AgentNode) | ||
|
||
|
||
@dataclasses.dataclass | ||
class UserPromptNode(BaseNode[GraphAgentState, GraphAgentDeps[DepsT, Any], result.FinalResult[NodeRunEndT]], ABC): | ||
class UserPromptNode(AgentNode[DepsT, NodeRunEndT]): | ||
user_prompt: str | Sequence[_messages.UserContent] | ||
|
||
system_prompts: tuple[str, ...] | ||
|
@@ -215,7 +238,7 @@ async def add_tool(tool: Tool[DepsT]) -> None: | |
|
||
|
||
@dataclasses.dataclass | ||
class ModelRequestNode(BaseNode[GraphAgentState, GraphAgentDeps[DepsT, Any], result.FinalResult[NodeRunEndT]]): | ||
class ModelRequestNode(AgentNode[DepsT, NodeRunEndT]): | ||
"""Make a request to the model using the last message in state.message_history.""" | ||
|
||
request: _messages.ModelRequest | ||
|
@@ -236,12 +259,30 @@ async def run( | |
|
||
return await self._make_request(ctx) | ||
|
||
@asynccontextmanager | ||
async def stream( | ||
self, | ||
ctx: GraphRunContext[GraphAgentState, GraphAgentDeps[DepsT, T]], | ||
) -> AsyncIterator[result.AgentStream[DepsT, T]]: | ||
async with self._stream(ctx) as streamed_response: | ||
agent_stream = result.AgentStream[DepsT, T]( | ||
streamed_response, | ||
ctx.deps.result_schema, | ||
ctx.deps.result_validators, | ||
build_run_context(ctx), | ||
ctx.deps.usage_limits, | ||
) | ||
yield agent_stream | ||
# In case the user didn't manually consume the full stream, ensure it is fully consumed here, | ||
# otherwise usage won't be properly counted: | ||
async for _ in agent_stream: | ||
pass | ||
Comment on lines
+276
to
+279
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @Kludex not 100% sure if we should do this force-consume-the-stream (when there isn't an exception), but I think it's what we should do. (Unless we confirm that you don't get charged for streams you don't consume, but that seems unlikely.) |
||
|
||
@asynccontextmanager | ||
async def _stream( | ||
self, | ||
ctx: GraphRunContext[GraphAgentState, GraphAgentDeps[DepsT, T]], | ||
) -> AsyncIterator[models.StreamedResponse]: | ||
# TODO: Consider changing this to return something more similar to a `StreamedRunResult`, then make it public | ||
assert not self._did_stream, 'stream() should only be called once per node' | ||
|
||
model_settings, model_request_parameters = await self._prepare_request(ctx) | ||
|
@@ -319,7 +360,7 @@ def _finish_handling( | |
|
||
|
||
@dataclasses.dataclass | ||
class HandleResponseNode(BaseNode[GraphAgentState, GraphAgentDeps[DepsT, Any], result.FinalResult[NodeRunEndT]]): | ||
class HandleResponseNode(AgentNode[DepsT, NodeRunEndT]): | ||
"""Process a model response, and decide whether to end the run or make a new request.""" | ||
|
||
model_response: _messages.ModelResponse | ||
|
@@ -575,7 +616,7 @@ async def process_function_tools( | |
for task in done: | ||
index = tasks.index(task) | ||
result = task.result() | ||
yield _messages.FunctionToolResultEvent(result, call_id=call_index_to_event_id[index]) | ||
yield _messages.FunctionToolResultEvent(result, tool_call_id=call_index_to_event_id[index]) | ||
if isinstance(result, (_messages.ToolReturnPart, _messages.RetryPromptPart)): | ||
results_by_index[index] = result | ||
else: | ||
|
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I tried using a type-alias instead of a class here, and it caused some issues because I couldn't inherit from it.
I think may be possible to drop the
AgentNode
class and use a type alias (just inheriting from the non-aliased parametrized BaseNode), and either way I think it's not currently public, but I think having this type allows us to remove most references toBaseNode
inagent.py
, which I think ultimately makes a lot of types more readable.Unless one of you really objects, I would prefer to keep it around for now rather than wrestle with the consequences of removing it (in terms of verbosity and/or type-checking challenges). Especially considering it isn't a public API anyway.