-
Notifications
You must be signed in to change notification settings - Fork 642
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
Changes from 5 commits
6586af3
6659a0d
d865202
633d950
181578b
8f383b4
6e0e0c7
375523d
09b4319
e73b85b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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]]): | ||
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. 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 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. |
||
"""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: | ||
|
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 think the main question I have is whether we should have these node-narrowing typeguards as:
Agent
, as I have hereAgentRun
is_type_of
staticmethod; I'll note I tried this and felt it was worse/more confusing)so far I think static method on
Agent
is best, but I see merits to each of these, though I'll note that static methods on the node types was what I implemented first and was my least favorite of the alternatives for various reasons.