Compare commits

...
Author SHA1 Message Date
Elior Nataf Lackritz 5527cc166e fix(langgraph): return an awaited @task's value while streaming
With stream=True, arun_with_retry drains the task's astream() and returned
nothing, so a @task awaited inside a node got None whenever the node ran in
streaming mode: under astream_events (v1 and v2) and anything built on it.
Return the value the task wrote instead, on both stream paths.

Same idea as #9295 by AaronG18 and the lookup amishaguptaberk suggested.
2026-10-23 07:24:18 -04:00
2 changed files with 42 additions and 3 deletions

No files matched your search

+9 -3
View File
@@ -34,6 +34,7 @@ from langgraph._internal._constants import (
CONFIG_KEY_THREAD_ID,
CONFIG_KEY_TIMED_ATTEMPT_OBSERVER,
NS_SEP,
RETURN,
)
from langgraph._internal._runnable import create_task_in_config_context
from langgraph._internal._timeout import sync_timeout_unsupported
@@ -733,15 +734,14 @@ async def arun_with_retry(
if stream:
async for _ in task.proc.astream(task.input, config):
pass
break
return _return_value(task)
return await task.proc.ainvoke(task.input, config)
result = await _arun_with_timeout(
task, config, resolved_timeout, attempt_ctx, stream=stream
)
_finish_timed_attempt(config, attempt_ctx)
if stream:
# if successful, end
break
return _return_value(task)
return result
except ParentCommand as exc:
ns: str = config[CONF][CONFIG_KEY_CHECKPOINT_NS]
@@ -831,6 +831,12 @@ async def arun_with_retry(
config = patch_configurable(config, {CONFIG_KEY_RESUMING: True})
def _return_value(task: PregelExecutableTask) -> Any:
# Streaming drains the task instead of returning its result, so a caller
# awaiting a `@task` needs the value the task wrote.
return next((value for channel, value in task.writes if channel == RETURN), None)
def _should_retry_on(retry_policy: RetryPolicy, exc: Exception) -> bool:
"""Check if the given exception should be retried based on the retry policy."""
if isinstance(retry_policy.retry_on, Sequence):
+33
View File
@@ -7495,6 +7495,39 @@ async def test_entrypoint_from_async_generator() -> None:
yield "b"
@NEEDS_CONTEXTVARS
@pytest.mark.parametrize("version", ["v1", "v2"])
async def test_awaited_task_returns_its_value_under_astream_events(
version: Literal["v1", "v2"],
) -> None:
class State(TypedDict):
doubled: int
zeroed: int
@task
async def double(x: int) -> int:
return x * 2
@task
async def zero() -> int:
return 0
async def node(state: State) -> State:
return {"doubled": await double(21), "zeroed": await zero()}
graph = StateGraph(State).add_node("node", node).add_edge(START, "node").compile()
outputs = [
event["data"]["output"]
async for event in graph.astream_events(
{"doubled": 0, "zeroed": 1}, version=version
)
if event["event"] == "on_chain_end" and event["name"] == "node"
]
assert outputs == [{"doubled": 42, "zeroed": 0}]
@NEEDS_CONTEXTVARS
async def test_named_tasks_functional() -> None:
class Foo: