Compare commits

..
Author SHA1 Message Date
byhow 677faf987f chore(prebuilt): merge the read_state branch 2026-11-18 18:09:35 -08:00
byhow 30da2a6ceb fix(langgraph): tell state keys from routing channels by the graph's own list
`read_state` and `write_state` told state keys from the channels a graph
adds to route and trigger nodes by name, which refused a legal state key
with a colon in it. The run loop now passes the graph's state keys to its
nodes under a private config key, and both functions check against that.

A named read of a key that is not state now raises `KeyError`, where it
returned an empty dict for a routing channel.
2026-11-18 18:09:17 -08:00
byhow bcb3bd880d refactor(prebuilt): read ToolNode state with read_state
`_extract_state` read the channel map out of the partial stored under
`CONFIG_KEY_READ`. `langgraph.config.read_state` returns the same values
without relying on that shape, and leaves out the channels a graph adds
to route and trigger nodes. The tests that faked the partial now run a
small graph that reaches the node with `Send`.

`read_state` does not work in async code on Python 3.10, so this waits
for 3.10 support to end. It also needs a `langgraph` release that has
`read_state`.
2026-11-18 17:27:31 -08:00
byhow 375786ca38 refactor(langgraph): drop config from read_state and write_state
Both functions now find the running node through the runnable config
context variable only, as `get_store` and `get_stream_writer` do. They
share those functions' limit: they do not work in async code on Python
< 3.11.
2026-11-18 17:26:51 -08:00
byhow 90014f36ff fix(langgraph): take config in read_state and write_state, and write state keys only
Async code on Python 3.10 does not carry the runnable config context
variable, so both functions now accept the node's `config` and require it
there. Without it an async subgraph could read and write its parent's
state.

`write_state` rejected only names that were not channels. It now rejects
the channels a graph adds to route and trigger nodes, such as
`branch:to:<node>` and `__start__`, and `read_state` with no keys leaves
them out.

The per-task lock is gone. A read takes a snapshot of the node's queued
writes instead, so a write from another thread cannot break it.
`read_state` takes keys as arguments and `write_state` takes a dict only.
2026-11-18 17:09:54 -08:00
byhow 06646f85b3 feat(langgraph): add read_state and write_state to langgraph.config
Code that runs inside a task, such as a tool, can now read state with the
task's own queued updates applied, and queue a state update without
returning it from the node.

`write_state` checks the update against the task's earlier updates before
it queues anything. A second value for a key that takes one value per
step raises `InvalidUpdateError` at the call, and none of that update is
queued. A lock on the task's scratchpad makes the check and the queue one
step, and stops a read from iterating the task's writes while another
thread adds to them.

Both functions find the task through the runnable config context
variable, as `get_store` does. Outside a task they raise `NotInTaskError`.
2026-11-18 16:26:39 -08:00
26 changed files with 864 additions and 911 deletions

No files matched your search

+4 -6
View File
@@ -150,10 +150,6 @@ def _resources(payload: object) -> list[dict[str, Any]]:
return [item for item in resources if isinstance(item, dict)]
def _secrets_to_replace(secrets: list[dict[str, str]] | None) -> dict[str, Any]:
return {"secrets": secrets} if secrets else {}
class HostBackendError(click.ClickException):
"""Raised when the host backend returns an error response."""
@@ -472,7 +468,8 @@ class HostBackendClient(_JsonClient):
payload["revision_source"] = revision_source
if tracked_packages:
payload["tracked_packages"] = tracked_packages
payload.update(_secrets_to_replace(secrets))
if secrets is not None:
payload["secrets"] = secrets
return self._request("PATCH", f"/v2/deployments/{deployment_id}", payload)
def update_deployment_internal_source(
@@ -504,7 +501,8 @@ class HostBackendClient(_JsonClient):
if source_config:
payload["source_config"] = source_config
payload.update(_secrets_to_replace(secrets))
if secrets is not None:
payload["secrets"] = secrets
return self._request("PATCH", f"/v2/deployments/{deployment_id}", payload)
def list_revisions(
@@ -731,6 +731,7 @@ def test_local_deploy_records_the_pushed_digest_and_tracked_packages(
assert deploy_project.control_plane.bodies[_patch(CREATED_ID)] == {
"revision_source": "internal_docker",
"source_revision_config": {"image_uri": PUSHED_DIGEST},
"secrets": [],
"tracked_packages": TRACKED_PACKAGES,
}
@@ -851,6 +852,7 @@ def test_remote_build_creates_an_internal_source_deployment_and_uploads_the_arch
"langgraph_config_path": ARCHIVE[2],
},
"source_config": {"install_command": "yarn install"},
"secrets": [],
"tracked_packages": TRACKED_PACKAGES,
}
assert "Build triggered" in result.output
@@ -960,6 +962,7 @@ def test_push_to_updates_an_existing_external_deployment_with_the_new_image(
]
assert deploy_project.control_plane.bodies[_patch("dep-ext")] == {
"source_revision_config": {"image_uri": EXTERNAL_DIGEST},
"secrets": [],
"tracked_packages": TRACKED_PACKAGES,
}
@@ -1027,6 +1030,7 @@ def test_image_uri_updates_an_existing_external_deployment_without_any_docker_wo
assert deploy_project.timeline == [LIST_DEPLOYMENTS, _patch("dep-ext")]
assert deploy_project.control_plane.bodies[_patch("dep-ext")] == {
"source_revision_config": {"image_uri": EXTERNAL_DIGEST},
"secrets": [],
"tracked_packages": TRACKED_PACKAGES,
}
+2 -33
View File
@@ -233,21 +233,6 @@ def _routing_client(seen: dict) -> HostBackendClient:
},
id="internal_docker_revision_names_its_source",
),
pytest.param(
lambda c: c.update_deployment(
"dep-123",
"registry.example.com/app@sha256:abc",
revision_source="internal_docker",
secrets=[],
),
{
"revision_source": "internal_docker",
"source_revision_config": {
"image_uri": "registry.example.com/app@sha256:abc"
},
},
id="revision_omits_an_empty_secrets_list",
),
pytest.param(
lambda c: c.update_deployment_internal_source(
"dep-123",
@@ -267,25 +252,9 @@ def _routing_client(seen: dict) -> HostBackendClient:
"install_command": "yarn install",
"build_command": "yarn build",
},
"secrets": [],
},
id="internal_source_revision_sends_build_commands_and_omits_empty_secrets",
),
pytest.param(
lambda c: c.update_deployment_internal_source(
"dep-123",
source_tarball_path="tarballs/src.tgz",
config_path="langgraph.json",
secrets=[{"name": "KEY", "value": "val"}],
),
{
"revision_source": "internal_source",
"source_revision_config": {
"source_tarball_path": "tarballs/src.tgz",
"langgraph_config_path": "langgraph.json",
},
"secrets": [{"name": "KEY", "value": "val"}],
},
id="internal_source_revision_forwards_secrets",
id="internal_source_revision_sends_js_build_commands",
),
pytest.param(
lambda c: c.update_deployment_internal_source(
@@ -37,10 +37,6 @@ CONFIG_KEY_SEND = sys.intern("__pregel_send")
# holds the `write` function that accepts writes to state/edges/reserved keys
CONFIG_KEY_READ = sys.intern("__pregel_read")
# holds the `read` function that returns a copy of the current state
CONFIG_KEY_READ_STATE = sys.intern("__pregel_read_state")
# holds a function that returns the state as the task's node gets it from an edge,
# set on Send tasks, whose input is the Send arg instead. Other tasks set it to None
# so a graph running inside a Send task never reads its parent's state
CONFIG_KEY_CALL = sys.intern("__pregel_call")
# holds the `call` function that accepts a node/func, args and returns a future
CONFIG_KEY_CHECKPOINTER = sys.intern("__pregel_checkpointer")
@@ -76,6 +72,8 @@ CONFIG_KEY_DURABILITY = sys.intern("__pregel_durability")
# holds the durability mode, one of "sync", "async", or "exit"
CONFIG_KEY_RUNTIME = sys.intern("__pregel_runtime")
# holds a `Runtime` instance with context, store, stream writer, etc.
CONFIG_KEY_STATE_KEYS = sys.intern("__pregel_state_keys")
# holds the names of the graph's state channels
CONFIG_KEY_RESUME_MAP = sys.intern("__pregel_resume_map")
# holds a mapping of task ns -> resume value for resuming tasks
CONFIG_KEY_STRICT_RESUME = sys.intern("__pregel_strict_resume")
+2 -2
View File
@@ -119,7 +119,7 @@ class DeltaChannel(Generic[Value], BaseChannel[Any, Any, Any]):
"""Initialize from a stored blob.
Blob types:
* `MISSING` or `None`: start empty; caller replays writes.
* `MISSING`: start empty; caller replays writes.
* `_DeltaSnapshot(value)`: restore value directly from snapshot.
* plain value (migration from old `BinaryOperatorAggregate` blobs):
use directly.
@@ -128,7 +128,7 @@ class DeltaChannel(Generic[Value], BaseChannel[Any, Any, Any]):
self.reducer, self.typ, snapshot_frequency=self.snapshot_frequency
)
new.key = self.key
if checkpoint is MISSING or checkpoint is None:
if checkpoint is MISSING:
new.value = self.typ()
elif isinstance(checkpoint, _DeltaSnapshot):
new.value = checkpoint.value
+76 -1
View File
@@ -1,12 +1,20 @@
import asyncio
import sys
from collections.abc import Mapping
from typing import Any
from langchain_core.runnables import RunnableConfig
from langchain_core.runnables.config import var_child_runnable_config
from langgraph.store.base import BaseStore
from langgraph._internal._constants import CONF, CONFIG_KEY_RUNTIME
from langgraph._internal._constants import (
CONF,
CONFIG_KEY_READ,
CONFIG_KEY_RUNTIME,
CONFIG_KEY_SEND,
CONFIG_KEY_STATE_KEYS,
)
from langgraph.errors import InvalidUpdateError, NotInTaskError
from langgraph.types import StreamWriter
@@ -194,3 +202,70 @@ def get_stream_writer() -> StreamWriter:
"""
runtime = get_config()[CONF][CONFIG_KEY_RUNTIME]
return runtime.stream_writer
def _task_conf(caller: str) -> dict[str, Any]:
conf = (var_child_runnable_config.get() or {}).get(CONF, {})
if CONFIG_KEY_READ not in conf:
msg = f"Called {caller} outside of a graph node or task"
raise NotInTaskError(msg)
return conf
def read_state(*keys: str) -> dict[str, Any]:
"""Read graph state from inside a node or tool, with its own updates applied.
A node receives state as it was when the step started. This also applies
the updates the node has queued since, such as with
[`write_state`][langgraph.config.write_state]. A key that holds its value
for one step, such as an `EphemeralValue`, reads as unset unless the node
wrote it. Like `get_store`, this does not work in async code on
Python < 3.11.
!!! version-added "Added in version 1.2.23"
Args:
*keys: The state keys to read. Reads every state key when omitted.
Returns:
The values by key. A key with no value is left out.
Raises:
KeyError: When a key is not a state key.
NotInTaskError: When called outside of a graph node or task.
"""
conf = _task_conf("read_state")
state_keys = conf.get(CONFIG_KEY_STATE_KEYS, ())
for key in keys:
if key not in state_keys:
msg = f"'{key}' is not a state key"
raise KeyError(msg)
return conf[CONFIG_KEY_READ](list(keys or state_keys), True)
def write_state(update: Mapping[str, Any]) -> None:
"""Queue a state update from inside a node or tool.
The update is applied when the step ends, and
[`read_state`][langgraph.config.read_state] sees it at once. Like
`get_store`, this does not work in async code on Python < 3.11.
!!! version-added "Added in version 1.2.23"
Args:
update: The values to write, by state key.
Raises:
InvalidUpdateError: When a key is not a state key, or takes one value
per step and the node already wrote it. Nothing is queued.
NotInTaskError: When called outside of a graph node or task.
"""
conf = _task_conf("write_state")
state_keys = conf.get(CONFIG_KEY_STATE_KEYS, ())
for key in update:
if key not in state_keys:
msg = f"Cannot write to '{key}': it is not a state key"
raise InvalidUpdateError(msg)
writes = list(update.items())
conf[CONFIG_KEY_READ](list(update), True, proposed=writes)
conf[CONFIG_KEY_SEND](writes)
+5
View File
@@ -25,6 +25,7 @@ __all__ = (
"NodeError",
"NodeInterrupt",
"NodeTimeoutError",
"NotInTaskError",
"ParentCommand",
"EmptyInputError",
"TaskNotFound",
@@ -101,6 +102,10 @@ class InvalidUpdateError(Exception):
pass
class NotInTaskError(RuntimeError):
"""Raised when task state is read or written outside of a running graph task."""
class GraphInterrupt(GraphBubbleUp):
"""Raised when a subgraph is interrupted, suppressed by the root graph.
Never raised directly, or surfaced to the user."""
+2 -3
View File
@@ -24,9 +24,6 @@ from typing_extensions import TypedDict, deprecated
from langgraph._internal._constants import CONF, CONFIG_KEY_SEND
from langgraph.graph.state import StateGraph
from langgraph.pregel._messages import (
REMOVE_ALL_MESSAGES as REMOVE_ALL_MESSAGES,
)
from langgraph.pregel._messages import (
_messages_delta_reducer as _messages_delta_reducer,
)
@@ -41,6 +38,8 @@ __all__ = (
Messages = list[MessageLikeRepresentation] | MessageLikeRepresentation
REMOVE_ALL_MESSAGES = "__remove_all__"
def _add_messages_wrapper(func: Callable) -> Callable[[Messages, Messages], Messages]:
def _add_messages(
+10 -16
View File
@@ -42,7 +42,6 @@ from langgraph._internal._constants import (
CONFIG_KEY_CHECKPOINTER,
CONFIG_KEY_NODE_ERROR,
CONFIG_KEY_READ,
CONFIG_KEY_READ_STATE,
CONFIG_KEY_RESUME_MAP,
CONFIG_KEY_RUNTIME,
CONFIG_KEY_SCRATCHPAD,
@@ -195,20 +194,27 @@ def local_read(
task: WritesProtocol,
select: list[str] | str,
fresh: bool = False,
*,
proposed: Sequence[tuple[str, Any]] = (),
) -> dict[str, Any] | Any:
"""Function injected under CONFIG_KEY_READ in task config, to read current state.
Used by conditional edges to read a copy of the state with reflecting the writes
from that node only."""
from that node only.
`proposed` writes are applied after the task's own without being queued, so a
fresh read raises `InvalidUpdateError` for an update the step would reject."""
# a snapshot, so another thread queuing a write cannot break the loops below
writes = (*task.writes, *proposed)
updated: dict[str, list[Any]] = defaultdict(list)
if isinstance(select, str):
managed_keys = []
for c, v in task.writes:
for c, v in writes:
if c == select:
updated[c].append(v)
else:
managed_keys = [k for k in select if k in managed]
select = [k for k in select if k not in managed]
for c, v in task.writes:
for c, v in writes:
if c in select:
updated[c].append(v)
if fresh:
@@ -735,7 +741,6 @@ def prepare_single_task(
triggers,
),
),
CONFIG_KEY_READ_STATE: None,
CONFIG_KEY_CHECKPOINTER: (
checkpointer
or configurable.get(CONFIG_KEY_CHECKPOINTER)
@@ -913,7 +918,6 @@ def prepare_push_task_functional(
managed,
PregelTaskWrites(in_progress_task_path, name, writes, triggers),
),
CONFIG_KEY_READ_STATE: None,
CONFIG_KEY_CHECKPOINTER: (
checkpointer or configurable.get(CONFIG_KEY_CHECKPOINTER)
),
@@ -1084,15 +1088,6 @@ def prepare_push_task_send(
translated_task_path, packet.node, writes, triggers
),
),
CONFIG_KEY_READ_STATE: partial(
_proc_input,
proc,
managed,
channels,
for_execution=True,
scratchpad=scratchpad,
input_cache=None,
),
CONFIG_KEY_CHECKPOINTER: (
checkpointer or configurable.get(CONFIG_KEY_CHECKPOINTER)
),
@@ -1234,7 +1229,6 @@ def prepare_node_error_handler_task(
PUSH_TRIGGER,
),
),
CONFIG_KEY_READ_STATE: None,
CONFIG_KEY_CHECKPOINTER: (
checkpointer or configurable.get(CONFIG_KEY_CHECKPOINTER)
),
+15 -23
View File
@@ -4,7 +4,7 @@ import asyncio
import binascii
import concurrent.futures
from collections import defaultdict, deque
from collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence
from collections.abc import Callable, Iterator, Mapping, Sequence
from contextlib import (
AbstractAsyncContextManager,
AbstractContextManager,
@@ -47,6 +47,7 @@ from langgraph._internal._constants import (
CONFIG_KEY_RESUMING,
CONFIG_KEY_RUNTIME,
CONFIG_KEY_SCRATCHPAD,
CONFIG_KEY_STATE_KEYS,
CONFIG_KEY_STREAM,
CONFIG_KEY_STRICT_RESUME,
CONFIG_KEY_TASK_ID,
@@ -74,7 +75,7 @@ from langgraph.channels.base import BaseChannel
from langgraph.channels.binop import _get_overwrite
from langgraph.channels.delta import DeltaChannel
from langgraph.channels.untracked_value import UntrackedValue
from langgraph.constants import TAG_HIDDEN
from langgraph.constants import END, TAG_HIDDEN
from langgraph.errors import (
EmptyInputError,
GraphInterrupt,
@@ -200,28 +201,16 @@ class PregelLoop:
Callable[
[
concurrent.futures.Future | None,
Sequence[concurrent.futures.Future],
Sequence[Any],
RunnableConfig,
Checkpoint,
CheckpointMetadata,
str,
ChannelVersions,
],
RunnableConfig,
]
| Callable[
[
asyncio.Task | None,
Sequence[asyncio.Future],
RunnableConfig,
Checkpoint,
CheckpointMetadata,
ChannelVersions,
],
Awaitable[RunnableConfig],
Any,
]
| None
)
_migrate_checkpoint: Callable[[Checkpoint], None] | None
submit: Submit
channels: Mapping[str, BaseChannel]
@@ -361,6 +350,11 @@ class PregelLoop:
self.input_keys = input_keys
self.output_keys = output_keys
self.stream_keys = stream_keys
keys = [stream_keys] if isinstance(stream_keys, str) else stream_keys
# an entrypoint streams its return value through END, which is not state
self.config = patch_configurable(
self.config, {CONFIG_KEY_STATE_KEYS: [k for k in keys if k != END]}
)
self.interrupt_after = interrupt_after
self.interrupt_before = interrupt_before
self.manager = manager
@@ -1746,7 +1740,6 @@ class SyncPregelLoop(PregelLoop, AbstractContextManager):
)
self.stack = ExitStack()
if checkpointer:
self._checkpointer_put_after_previous = self._put_checkpoint_after_previous
self.checkpointer_get_next_version = checkpointer.get_next_version
self.checkpointer_put_writes = checkpointer.put_writes
self.checkpointer_put_writes_accepts_task_path = (
@@ -1754,11 +1747,11 @@ class SyncPregelLoop(PregelLoop, AbstractContextManager):
)
else:
self.checkpointer_get_next_version = increment
self._checkpointer_put_after_previous = None
self._checkpointer_put_after_previous = None # type: ignore[assignment]
self.checkpointer_put_writes = None
self.checkpointer_put_writes_accepts_task_path = False
def _put_checkpoint_after_previous(
def _checkpointer_put_after_previous(
self,
prev: concurrent.futures.Future | None,
delta_write_futs: Sequence[concurrent.futures.Future],
@@ -2003,7 +1996,6 @@ class AsyncPregelLoop(PregelLoop, AbstractAsyncContextManager):
)
self.stack = AsyncExitStack()
if checkpointer:
self._checkpointer_put_after_previous = self._put_checkpoint_after_previous
self.checkpointer_get_next_version = checkpointer.get_next_version
self.checkpointer_put_writes = checkpointer.aput_writes
self.checkpointer_put_writes_accepts_task_path = (
@@ -2011,11 +2003,11 @@ class AsyncPregelLoop(PregelLoop, AbstractAsyncContextManager):
)
else:
self.checkpointer_get_next_version = increment
self._checkpointer_put_after_previous = None
self._checkpointer_put_after_previous = None # type: ignore[assignment]
self.checkpointer_put_writes = None
self.checkpointer_put_writes_accepts_task_path = False
async def _put_checkpoint_after_previous(
async def _checkpointer_put_after_previous(
self,
prev: asyncio.Task | None,
delta_write_futs: Sequence[asyncio.Future],
+3 -13
View File
@@ -433,24 +433,21 @@ class StreamMessagesHandlerV2(StreamMessagesHandler, _V2StreamingCallbackHandler
# Defined here rather than in `langgraph.graph.message`, which re-exports it:
# `ensure_message_ids` has to recognize it, and importing that module from the
# loop would be an import cycle.
REMOVE_ALL_MESSAGES = "__remove_all__"
def _messages_delta_reducer(
state: list[AnyMessage], writes: list[list[AnyMessage]]
) -> list[AnyMessage]:
"""**Experimental.** Batch reducer for use with `DeltaChannel`.
Processes all writes in one pass — dedup by ID, `RemoveMessage`
tombstoning, `REMOVE_ALL_MESSAGES` reset — without calling `add_messages`.
tombstoning — without calling `add_messages`.
This reducer is batching-invariant, as required by `DeltaChannel`:
`reducer(reducer(state, xs), ys) == reducer(state, xs + ys)`.
Raw dict / string / tuple inputs are coerced to typed `BaseMessage`
objects so that HTTP-driven graphs work without a separate coercion
step. This is not full `add_messages` parity — unknown-id
`RemoveMessage` errors, missing-id UUID assignment, and
step. This is not full `add_messages` parity — `REMOVE_ALL_MESSAGES`,
unknown-id `RemoveMessage` errors, missing-id UUID assignment, and
`BaseMessageChunk` conversion are not handled here.
Example::
@@ -481,13 +478,6 @@ def _messages_delta_reducer(
state_msgs = cast("list[AnyMessage]", convert_to_messages(state))
msgs = cast("list[AnyMessage]", convert_to_messages(flat))
for idx in range(len(msgs) - 1, -1, -1):
m = msgs[idx]
if isinstance(m, RemoveMessage) and m.id == REMOVE_ALL_MESSAGES:
state_msgs = []
msgs = msgs[idx + 1 :]
break
index: dict[str, int] = {
m.id: i for i, m in enumerate(state_msgs) if m.id is not None
}
+4 -1
View File
@@ -76,6 +76,7 @@ from langgraph._internal._constants import (
CONFIG_KEY_RUNNER_SUBMIT,
CONFIG_KEY_RUNTIME,
CONFIG_KEY_SEND,
CONFIG_KEY_STATE_KEYS,
CONFIG_KEY_STREAM,
CONFIG_KEY_STREAM_MESSAGES_V2,
CONFIG_KEY_TASK_ID,
@@ -756,7 +757,7 @@ class Pregel(
config: RunnableConfig | None = None
name: str | None = "LangGraph"
name: str = "LangGraph"
trigger_to_nodes: Mapping[str, Sequence[str]]
node_error_handler_map: Mapping[str, str]
@@ -2047,6 +2048,7 @@ class Pregel(
# deque.extend is thread-safe
CONFIG_KEY_SEND: writes.extend,
CONFIG_KEY_TASK_ID: task_id,
CONFIG_KEY_STATE_KEYS: self.stream_channels_list,
CONFIG_KEY_READ: partial(
local_read,
_scratchpad(
@@ -2547,6 +2549,7 @@ class Pregel(
# deque.extend is thread-safe
CONFIG_KEY_SEND: writes.extend,
CONFIG_KEY_TASK_ID: task_id,
CONFIG_KEY_STATE_KEYS: self.stream_channels_list,
CONFIG_KEY_READ: partial(
local_read,
_scratchpad(
+3 -3
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "langgraph"
version = "1.2.24"
version = "1.2.22"
description = "Building stateful, multi-actor applications with LLMs"
authors = []
requires-python = ">=3.10"
@@ -27,7 +27,7 @@ dependencies = [
"langchain-core>=1.4.7,<2",
"langgraph-checkpoint>=4.3.0,<5.0.0",
"langgraph-sdk>=0.4.6,<0.5.0",
"langgraph-prebuilt>=1.1.3,<1.2.0",
"langgraph-prebuilt>=1.1.0,<1.2.0",
"xxhash>=3.5.0",
"pydantic>=2.7.4",
]
@@ -60,7 +60,7 @@ test = [
"langgraph-checkpoint-postgres",
"langgraph-sdk",
"psycopg[binary]",
"uvloop==0.23.0",
"uvloop==0.22.1",
"pyperf",
"py-spy",
"pycryptodome",
+1 -20
View File
@@ -18,7 +18,7 @@ from langgraph.channels.topic import Topic
from langgraph.channels.untracked_value import UntrackedValue
from langgraph.errors import EmptyChannelError, InvalidUpdateError
from langgraph.graph import START, StateGraph
from langgraph.graph.message import REMOVE_ALL_MESSAGES, _messages_delta_reducer
from langgraph.graph.message import _messages_delta_reducer
from langgraph.graph.state import _get_channel
from langgraph.pregel._checkpoint import delta_channels_to_snapshot
from langgraph.types import Overwrite
@@ -153,25 +153,6 @@ def test_delta_channel_basic_two_steps() -> None:
assert ch.get()[1].content == "hello"
def test_delta_channel_from_none_checkpoint_replays_from_empty() -> None:
ch = DeltaChannel(_messages_delta_reducer, list).from_checkpoint(None)
msg = HumanMessage(content="hi", id="h1")
ch.replay_writes([("t0", "messages", [msg])])
assert ch.get() == [msg]
def test_messages_delta_reducer_remove_all() -> None:
old = HumanMessage(content="old", id="h0")
dropped = HumanMessage(content="dropped", id="h1")
kept = AIMessage(content="kept", id="a1")
writes = [[dropped], [RemoveMessage(id=REMOVE_ALL_MESSAGES), kept]]
assert _messages_delta_reducer([old], writes) == [kept]
state = [old]
for w in writes:
state = _messages_delta_reducer(state, [w])
assert state == [kept]
def test_delta_channel_from_checkpoint_writes_list() -> None:
"""replay_writes on a fresh channel replays through the operator."""
spec = DeltaChannel(_messages_delta_reducer, list)
+12 -14
View File
@@ -3463,13 +3463,10 @@ def test_stream_buffering_single_node(sync_checkpointer: BaseCheckpointSaver) ->
class State(TypedDict):
my_key: Annotated[str, operator.add]
received = threading.Event()
def node(state: State, writer: StreamWriter):
writer("Before wait")
if not received.wait(timeout=10):
raise TimeoutError("Custom event was not streamed before node completion")
writer("After wait")
writer("Before sleep")
time.sleep(0.2)
writer("After sleep")
return {"my_key": "got here"}
builder = StateGraph(State)
@@ -3478,15 +3475,16 @@ def test_stream_buffering_single_node(sync_checkpointer: BaseCheckpointSaver) ->
builder.add_edge("node", END)
graph = builder.compile(checkpointer=sync_checkpointer)
start = time.perf_counter()
chunks: list[tuple[float, Any]] = []
config = {"configurable": {"thread_id": "2"}}
stream = graph.stream({"my_key": ""}, config, stream_mode="custom")
try:
assert next(stream) == "Before wait"
received.set()
assert list(stream) == ["After wait"]
finally:
received.set()
stream.close()
for c in graph.stream({"my_key": ""}, config, stream_mode="custom"):
chunks.append((round(time.perf_counter() - start, 1), c))
assert chunks == [
(FloatBetween(0.0, 0.1), "Before sleep"),
(FloatBetween(0.2, 0.3), "After sleep"),
]
def test_nested_graph_interrupts_parallel(
+246
View File
@@ -0,0 +1,246 @@
import operator
import sys
from collections.abc import Callable
from typing import Annotated, Any
import pytest
from langchain_core.runnables import RunnableConfig, RunnableLambda
from langgraph.checkpoint.memory import InMemorySaver
from typing_extensions import TypedDict
from langgraph.channels.ephemeral_value import EphemeralValue
from langgraph.channels.untracked_value import UntrackedValue
from langgraph.config import read_state, write_state
from langgraph.errors import InvalidUpdateError, NotInTaskError
from langgraph.func import entrypoint
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, Overwrite, interrupt
pytestmark = pytest.mark.anyio
NEEDS_CONTEXTVARS = pytest.mark.skipif(
sys.version_info < (3, 11),
reason="Python 3.11+ is required for async contextvars support",
)
class State(TypedDict, total=False):
one: str
many: Annotated[list[int], operator.add]
ephemeral: Annotated[str, EphemeralValue(str)]
untracked: Annotated[str, UntrackedValue(str)]
def run(node: Callable[..., Any], input: State | None = None) -> dict[str, Any]:
graph = StateGraph(State).add_node("node", node).add_edge(START, "node").compile()
return graph.invoke(input or {"many": [0]})
def test_read_state_applies_the_nodes_own_updates() -> None:
seen: dict[str, Any] = {}
def node(state: State) -> None:
seen["start"] = read_state()
write_state({"one": "a", "many": [1]})
seen["all"] = read_state()
seen["one"] = read_state("one")
seen["both"] = read_state("one", "many")
seen["input"] = dict(state)
assert run(node) == {"one": "a", "many": [0, 1]}
assert seen == {
"start": {"many": [0]},
"all": {"one": "a", "many": [0, 1]},
"one": {"one": "a"},
"both": {"one": "a", "many": [0, 1]},
"input": {"many": [0]},
}
def test_write_state_adds_to_the_update_the_node_returns() -> None:
def node(state: State) -> State:
write_state({"many": [1]})
write_state({"many": [2]})
return {"many": [3]}
assert run(node) == {"many": [0, 1, 2, 3]}
@NEEDS_CONTEXTVARS
async def test_an_async_node_finds_its_task_from_context() -> None:
async def node(state: State) -> None:
write_state({"one": "a"})
assert read_state("one") == {"one": "a"}
graph = StateGraph(State).add_node("node", node).add_edge(START, "node").compile()
assert await graph.ainvoke({"many": [0]}) == {"one": "a", "many": [0]}
@pytest.mark.parametrize(
("first", "second"),
[
({"one": "a"}, {"one": "b"}),
({"many": Overwrite([1])}, {"many": Overwrite([2])}),
({"ephemeral": "a"}, {"ephemeral": "b"}),
({"untracked": "a"}, {"untracked": "b"}),
],
ids=["last-value", "overwrite", "ephemeral", "untracked"],
)
def test_write_state_rejects_a_second_value_for_a_one_value_key(
first: dict[str, Any], second: dict[str, Any]
) -> None:
after: dict[str, Any] = {}
def node(state: State) -> None:
write_state(first)
before = read_state()
with pytest.raises(InvalidUpdateError):
write_state(second)
after.update(unchanged=read_state() == before)
assert run(node) == run(lambda state: first)
assert after == {"unchanged": True}
def test_a_rejected_update_queues_none_of_its_keys() -> None:
def node(state: State) -> None:
write_state({"one": "a"})
with pytest.raises(InvalidUpdateError):
write_state({"many": [1], "one": "b"})
assert run(node) == {"one": "a", "many": [0]}
@pytest.mark.parametrize(
"key", ["missing", "__pregel_tasks", "__start__", "branch:to:other"]
)
def test_write_state_rejects_a_key_that_is_not_state(key: str) -> None:
ran: list[str] = []
def node(state: State) -> None:
with pytest.raises(InvalidUpdateError, match="not a state key"):
write_state({"many": [1], key: None})
graph = (
StateGraph(State)
.add_node("node", node)
.add_node("other", lambda state: ran.append("other"))
.add_edge(START, "node")
.add_edge("other", END)
.compile()
)
assert graph.invoke({"many": [0]}) == {"many": [0]}
assert ran == []
def test_read_state_returns_state_keys_only() -> None:
seen: list[dict[str, Any]] = []
graph = (
StateGraph(State)
.add_node("a", lambda state: {"many": [1]})
.add_node("b", lambda state: {"many": [2]})
.add_node("joined", lambda state: seen.append(read_state()))
.add_edge(START, "a")
.add_edge(START, "b")
.add_edge(["a", "b"], "joined")
.compile()
)
graph.invoke({"many": [0]})
assert [sorted(state) for state in seen] == [["many"]]
def test_read_state_rejects_a_key_that_is_not_state() -> None:
def node(state: State) -> None:
for key in ("missing", "__start__", "branch:to:node"):
with pytest.raises(KeyError, match="not a state key"):
read_state(key)
assert run(node) == {"many": [0]}
def test_a_state_key_may_contain_a_colon() -> None:
Colon = TypedDict("Colon", {"user:name": str})
def node(state: Any) -> None:
write_state({"user:name": "a"})
assert read_state() == {"user:name": "a"}
graph = StateGraph(Colon).add_node("node", node).add_edge(START, "node").compile()
assert graph.invoke({}) == {"user:name": "a"}
def test_a_one_step_key_reads_as_unset_until_the_node_writes_it() -> None:
seen: list[dict[str, Any]] = []
def node(state: State) -> None:
seen.append(read_state("ephemeral"))
write_state({"ephemeral": "b"})
seen.append(read_state("ephemeral"))
run(node, {"ephemeral": "a"})
assert seen == [{}, {"ephemeral": "b"}]
def test_read_and_write_state_need_a_running_graph() -> None:
with pytest.raises(NotInTaskError, match="read_state outside"):
read_state()
with pytest.raises(NotInTaskError, match="write_state outside"):
write_state({"one": "a"})
with pytest.raises(NotInTaskError):
RunnableLambda(lambda _: read_state()).invoke(None)
with pytest.raises(NotInTaskError):
RunnableLambda(lambda _: write_state({"one": "a"})).invoke(None)
def test_an_entrypoint_has_no_state_keys() -> None:
@entrypoint()
def workflow(value: int) -> dict[str, Any]:
for key in (END, "__previous__"):
with pytest.raises(InvalidUpdateError, match="not a state key"):
write_state({key: value})
return read_state()
assert workflow.invoke(1) == {}
def test_updates_written_before_an_interrupt_apply_once_after_resume() -> None:
def node(state: State) -> State:
write_state({"many": [1]})
answer = interrupt("ok?")
write_state({"one": answer})
return {"many": [2]}
graph = (
StateGraph(State)
.add_node("node", node)
.add_edge(START, "node")
.compile(checkpointer=InMemorySaver())
)
config: RunnableConfig = {"configurable": {"thread_id": "1"}}
graph.invoke({"many": [0]}, config)
assert graph.get_state(config).values == {"many": [0]}
assert graph.invoke(Command(resume="yes"), config) == {
"one": "yes",
"many": [0, 1, 2],
}
def test_read_state_in_a_conditional_edge_during_update_state() -> None:
seen: list[dict[str, Any]] = []
def route(state: State) -> str:
seen.append(read_state("one"))
return "end"
graph = (
StateGraph(State)
.add_node("node", lambda state: None)
.add_edge(START, "node")
.add_conditional_edges("node", route, {"end": "__end__"})
.compile(checkpointer=InMemorySaver())
)
config: RunnableConfig = {"configurable": {"thread_id": "1"}}
graph.invoke({"one": "a"}, config)
graph.update_state(config, {"one": "b"}, as_node="node")
assert seen == [{"one": "a"}, {"one": "b"}]
+408 -577
View File
File diff suppressed because it is too large. Load diff
+6 -20
View File
@@ -82,9 +82,9 @@ from langchain_core.tools.base import (
_is_injected_arg_type,
get_all_basemodel_annotations,
)
from langgraph._internal._constants import CONF, CONFIG_KEY_READ
from langgraph._internal._runnable import RunnableCallable
from langgraph.errors import GraphBubbleUp
from langgraph.config import read_state
from langgraph.errors import GraphBubbleUp, NotInTaskError
from langgraph.graph.message import REMOVE_ALL_MESSAGES
from langgraph.pregel._tools import _tool_call_writer
from langgraph.runtime import ExecutionInfo, ServerInfo
@@ -107,12 +107,6 @@ except ImportError: # `langgraph` before `is_invalid_resume` never marks resume
return False
try:
from langgraph._internal._constants import CONFIG_KEY_READ_STATE
except ImportError: # `langgraph` before `CONFIG_KEY_READ_STATE` never sets the key
CONFIG_KEY_READ_STATE = "__pregel_read_state"
# right now we use a dict as the default, can change this to AgentState, but depends
# on if this lives in LangChain or LangGraph... ideally would have some typed
# messages key
@@ -1338,8 +1332,7 @@ class ToolNode(RunnableCallable):
- `ToolCallWithContext` dict — legacy Send payload carrying an inlined
state snapshot; return `input["state"]`.
- list of `ToolCall` dicts — new Send payload with no inlined state;
read the state this node would get from an edge, coerced to its
input schema (raw channel values on older `langgraph`).
hydrate state from channels with `read_state`.
- regular graph state (dict/list/BaseModel) — return `input` as-is.
"""
if isinstance(input, dict) and input.get("__type") == "tool_call_with_context":
@@ -1350,18 +1343,11 @@ class ToolNode(RunnableCallable):
and isinstance(input[-1], dict)
and input[-1].get("type") == "tool_call"
):
conf = config.get(CONF, {})
if (read_state := conf.get(CONFIG_KEY_READ_STATE)) is not None:
try:
return read_state()
read = conf.get(CONFIG_KEY_READ)
if read is None:
except NotInTaskError:
# not running in a graph, so there is no state to read
return {}
# Pregel installs CONFIG_KEY_READ as
# `functools.partial(local_read, scratchpad, channels, managed, task)`.
# Match the previous inlined-state contract by reading channels only;
# managed values have their own injection path (`ToolRuntime.context`).
channels = read.args[1]
return cast("dict[str, Any]", read(list(channels), True))
return input
def _inject_tool_args(
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "langgraph-prebuilt"
version = "1.1.3"
version = "1.1.2"
description = "Library with high-level APIs for creating and executing LangGraph agents and tools."
authors = []
requires-python = ">=3.10"
+41 -66
View File
@@ -1,6 +1,5 @@
"""Unit tests for tool call interceptor in ToolNode."""
import functools
from collections.abc import Awaitable, Callable
from dataclasses import replace
from typing import Annotated
@@ -10,8 +9,10 @@ import pytest
from langchain_core.messages import AIMessage, ToolCall, ToolMessage
from langchain_core.runnables import RunnableConfig
from langchain_core.tools import tool
from langgraph.graph import START, MessagesState, StateGraph
from langgraph.graph.state import CompiledStateGraph
from langgraph.store.base import BaseStore
from langgraph.types import Command
from langgraph.types import Command, Send
from langgraph.prebuilt.tool_node import (
InjectedState,
@@ -1325,82 +1326,59 @@ async def test_state_extraction_with_tool_call_with_context_async() -> None:
assert "tool_call" not in state_seen[0]
def _config_with_channel_read(
channel_values: dict[str, object],
store: BaseStore | None = None,
) -> RunnableConfig:
"""Build a config that mimics `CONFIG_KEY_READ` as Pregel installs it.
Pregel always installs a `functools.partial(local_read, scratchpad,
channels, managed, task)`, and `ToolNode` introspects that partial to
learn channel names. The stub matches the shape: partial whose second and
third positional args are `channels` and `managed` mappings.
"""
channels_stub = {k: None for k in channel_values}
managed_stub: dict[str, object] = {}
# Shape matches pregel's real partial:
# functools.partial(local_read, scratchpad, channels, managed, task)
def _read(scratchpad, channels, managed, task, select, fresh):
if isinstance(select, str):
return channel_values[select]
return {k: channel_values[k] for k in select if k in channel_values}
read = functools.partial(_read, None, channels_stub, managed_stub, None)
cfg = _create_config_with_runtime(store)
cfg["configurable"]["__pregel_read"] = read
return cfg
class _FilesState(MessagesState):
files: dict[str, str]
def test_list_form_send_hydrates_state_from_channel_read() -> None:
"""Send('tools', [tool_call]) with no inlined state should hydrate
ToolRuntime.state from CONFIG_KEY_READ (full state read)."""
state_seen = []
def state_inspector_handler(
request: ToolCallRequest,
execute: Callable[[ToolCallRequest], ToolMessage | Command],
) -> ToolMessage | Command:
state_seen.append(request.state)
return execute(request)
channel_values = {
"messages": [AIMessage("from channels")],
"files": {"/a.md": "body"},
}
tool_node = ToolNode([add], wrap_tool_call=state_inspector_handler)
def _send_tool_call_graph(tool_node: ToolNode) -> CompiledStateGraph:
"""A graph that reaches `tool_node` with `Send("tools", [tool_call])`."""
tool_call: ToolCall = {
"name": "add",
"args": {"a": 1, "b": 2},
"id": "call_1",
"type": "tool_call",
}
return (
StateGraph(_FilesState)
.add_node("tools", tool_node)
.add_conditional_edges(START, lambda _: [Send("tools", [tool_call])], ["tools"])
.compile()
)
tool_node.invoke([tool_call], config=_config_with_channel_read(channel_values))
assert len(state_seen) == 1
got = state_seen[0]
assert got == channel_values
assert "messages" in got and "files" in got
def _state_seen_by(tool_node_state: list[object]) -> ToolNode:
def state_inspector_handler(
request: ToolCallRequest,
execute: Callable[[ToolCallRequest], ToolMessage | Command],
) -> ToolMessage | Command:
tool_node_state.append(request.state)
return execute(request)
return ToolNode([add], wrap_tool_call=state_inspector_handler)
def test_list_form_send_hydrates_state_from_graph_state() -> None:
"""Send('tools', [tool_call]) with no inlined state hydrates
ToolRuntime.state with the full graph state."""
state_seen: list[object] = []
state = {"messages": [AIMessage("from channels", id="1")], "files": {"/a.md": "b"}}
_send_tool_call_graph(_state_seen_by(state_seen)).invoke(state)
assert state_seen == [state]
async def test_list_form_send_hydrates_state_async() -> None:
state_seen = []
state_seen: list[object] = []
state = {"messages": [AIMessage("from channels", id="1")], "files": {}}
def state_inspector_handler(
request: ToolCallRequest,
execute: Callable[[ToolCallRequest], ToolMessage | Command],
) -> ToolMessage | Command:
state_seen.append(request.state)
return execute(request)
await _send_tool_call_graph(_state_seen_by(state_seen)).ainvoke(state)
channel_values = {"messages": [AIMessage("from channels")], "files": {}}
assert state_seen == [state]
tool_node = ToolNode([add], wrap_tool_call=state_inspector_handler)
def test_list_form_send_outside_a_graph_has_empty_state() -> None:
state_seen: list[object] = []
tool_call: ToolCall = {
"name": "add",
"args": {"a": 1, "b": 2},
@@ -1408,12 +1386,9 @@ async def test_list_form_send_hydrates_state_async() -> None:
"type": "tool_call",
}
await tool_node.ainvoke(
[tool_call], config=_config_with_channel_read(channel_values)
)
_state_seen_by(state_seen).invoke([tool_call], config=_create_config_with_runtime())
assert len(state_seen) == 1
assert state_seen[0] == channel_values
assert state_seen == [{}]
def test_tool_call_request_is_frozen() -> None:
-61
View File
@@ -3,7 +3,6 @@ import dataclasses
import json
import sys
import warnings
from collections.abc import Callable
from functools import partial
from typing import (
Annotated,
@@ -1574,66 +1573,6 @@ def test_tool_node_inject_state(schema_: type[T]) -> None:
assert tool_message.content == "hi?"
@pytest.mark.parametrize("schema_", _INJECTED_STATE_SCHEMAS)
def test_tool_node_send_tool_call_gets_same_state_as_edge(schema_: type[T]) -> None:
call = ToolCall(name="record", args={}, id="call_1", type="tool_call")
seen: list[tuple[type, type]] = []
def record(runtime: ToolRuntime, state: Annotated[T, InjectedState]) -> str:
"""Record the state types the tool gets."""
seen.append((type(runtime.state), type(state)))
return "ok"
def agent(state: Any) -> dict:
return {"messages": [AIMessage("", tool_calls=[call])]}
def state_types(route: Callable[[Any], str | list[Send]]) -> tuple[type, type]:
seen.clear()
graph = (
StateGraph(schema_)
.add_node("agent", agent)
.add_node("tools", ToolNode([record]))
.add_edge(START, "agent")
.add_conditional_edges("agent", route, ["tools"])
.compile()
)
graph.invoke({"messages": [], "foo": "bar"})
return seen[0]
by_send = state_types(lambda _: [Send("tools", [call])])
by_edge = state_types(lambda _: "tools")
assert by_send == by_edge
def test_tool_node_in_graph_run_by_send_gets_that_graphs_state() -> None:
call = ToolCall(name="record", args={}, id="call_1", type="tool_call")
seen: list[Any] = []
def record(runtime: ToolRuntime) -> str:
"""Record the state the tool gets."""
seen.append(runtime.state)
return "ok"
class State(TypedDict):
value: str
def call_tools(state: State) -> dict:
ToolNode([record]).invoke([call])
return {}
inner = StateGraph(State).add_node(call_tools).add_edge(START, "call_tools")
outer = (
StateGraph(State)
.add_node("inner", inner.compile())
.add_conditional_edges(
START, lambda _: [Send("inner", {"value": "inner"})], ["inner"]
)
.compile()
)
outer.invoke({"value": "outer"})
assert seen == [{"value": "inner"}]
def test_tool_node_inject_store() -> None:
store = InMemoryStore()
namespace = ("test",)
+4 -4
View File
@@ -381,7 +381,7 @@ wheels = [
[[package]]
name = "langgraph"
version = "1.2.24"
version = "1.2.22"
source = { editable = "../langgraph" }
dependencies = [
{ name = "langchain-core" },
@@ -430,7 +430,7 @@ dev = [
{ name = "syrupy" },
{ name = "ty" },
{ name = "types-requests" },
{ name = "uvloop", specifier = "==0.23.0" },
{ name = "uvloop", specifier = "==0.22.1" },
]
lint = [
{ name = "ruff" },
@@ -460,7 +460,7 @@ test = [
{ name = "pytest-xdist", extras = ["psutil"] },
{ name = "redis" },
{ name = "syrupy" },
{ name = "uvloop", specifier = "==0.23.0" },
{ name = "uvloop", specifier = "==0.22.1" },
]
[[package]]
@@ -607,7 +607,7 @@ test = [
[[package]]
name = "langgraph-prebuilt"
version = "1.1.3"
version = "1.1.2"
source = { editable = "." }
dependencies = [
{ name = "langchain-core" },
@@ -13,10 +13,8 @@ Each node is designed to surface a specific v3 channel:
- `subgraph` is a nested `StateGraph` invoked once so `thread.subgraphs` has
exactly one direct child (`tasks` + `messages` under a namespace).
Extensions: every node writes `{"name": "progress", ...}` with
`get_stream_writer()`, and `ProgressTransformer` relays the root-level ones
onto a named `progress` channel, so `thread.extensions["progress"]` produces
deterministic events.
Extensions: every node calls `get_stream_writer()("progress", {...})` so
`thread.extensions["progress"]` produces deterministic events.
No real LLM is used — message streaming is simulated by yielding a list of
`AIMessageChunk`s from the node. This keeps the integration suite
@@ -40,7 +38,6 @@ from langchain_core.tools import tool
from langgraph.config import get_stream_writer
from langgraph.graph import StateGraph
from langgraph.graph.message import add_messages
from langgraph.stream import ProtocolEvent, StreamChannel, StreamTransformer
from langgraph.stream.transformers import CustomTransformer, UpdatesTransformer
from langgraph.types import interrupt
@@ -275,33 +272,6 @@ def run_subgraph(state: AgentState) -> dict[str, Any]:
}
class ProgressTransformer(StreamTransformer):
"""The server only routes named channels to `thread.extensions[name]`."""
required_stream_modes = ("custom",)
def __init__(self, scope: tuple[str, ...] = ()) -> None:
super().__init__(scope)
self._channel: StreamChannel[dict[str, Any]] = StreamChannel("progress")
self._scope_list = list(scope)
def init(self) -> dict[str, Any]:
return {"progress": self._channel}
def process(self, event: ProtocolEvent) -> bool:
if event["method"] != "custom":
return True
params = event["params"]
data = params["data"]
if (
params["namespace"] == self._scope_list
and isinstance(data, dict)
and data.get("name") == "progress"
):
self._channel.push(data)
return True
# ---------------------------------------------------------------------------
# Top-level graph
# ---------------------------------------------------------------------------
@@ -326,5 +296,5 @@ graph = _builder.compile(
# auto-registered by the v3 mux for any graph that streams a chat
# model. ``ValuesTransformer`` / ``LifecycleTransformer`` are also
# always-on natives.
transformers=[CustomTransformer, UpdatesTransformer, ProgressTransformer],
transformers=[CustomTransformer, UpdatesTransformer],
)
@@ -1,7 +1,7 @@
"""Exercise `thread.extensions[name]` against the integration API.
Every node in the example graph writes `{"name": "progress", ...}` via
`get_stream_writer`, relayed onto the named `progress` channel. This script verifies the `extensions["progress"]`
Every node in the example graph writes `("progress", {...})` via
`get_stream_writer`. This script verifies the `extensions["progress"]`
projection yields each progress event in order.
"""
@@ -32,7 +32,7 @@ async def run_async() -> None:
print(f" total progress events: {len(events)}")
assert events, "expected at least one progress event"
# Verify ordering covers the node sequence.
steps = [e["payload"]["step"] for e in events]
steps = [e.get("step") for e in events]
print(f" step sequence: {steps}")
finally:
await raw.aclose()
@@ -51,7 +51,7 @@ def run_sync() -> None:
events.append(event)
print(f" total progress events: {len(events)}")
assert events, "expected at least one progress event"
steps = [e["payload"]["step"] for e in events]
steps = [e.get("step") for e in events]
print(f" step sequence: {steps}")
finally:
raw.close()
@@ -28,7 +28,7 @@ async def test_extensions_async(async_threads) -> None:
# Iterator exits at the `ask_human` interrupt via `_signal_paused`,
# so we capture exactly the pre-interrupt progress sequence.
steps = [e["payload"]["step"] for e in events]
steps = [e.get("step") for e in events]
assert steps == _EXPECTED_PRE_INTERRUPT_STEPS, (
f"unexpected step sequence: {steps}"
)
@@ -43,7 +43,7 @@ def test_extensions_sync(sync_threads) -> None:
for event in thread.extensions["progress"]:
events.append(event)
steps = [e["payload"]["step"] for e in events]
steps = [e.get("step") for e in events]
assert steps == _EXPECTED_PRE_INTERRUPT_STEPS, (
f"unexpected step sequence: {steps}"
)
+4 -4
View File
@@ -394,7 +394,7 @@ wheels = [
[[package]]
name = "langgraph"
version = "1.2.24"
version = "1.2.22"
source = { editable = "../langgraph" }
dependencies = [
{ name = "langchain-core" },
@@ -443,7 +443,7 @@ dev = [
{ name = "syrupy" },
{ name = "ty" },
{ name = "types-requests" },
{ name = "uvloop", specifier = "==0.23.0" },
{ name = "uvloop", specifier = "==0.22.1" },
]
lint = [
{ name = "ruff" },
@@ -473,7 +473,7 @@ test = [
{ name = "pytest-xdist", extras = ["psutil"] },
{ name = "redis" },
{ name = "syrupy" },
{ name = "uvloop", specifier = "==0.23.0" },
{ name = "uvloop", specifier = "==0.22.1" },
]
[[package]]
@@ -526,7 +526,7 @@ test = [
[[package]]
name = "langgraph-prebuilt"
version = "1.1.3"
version = "1.1.2"
source = { editable = "../prebuilt" }
dependencies = [
{ name = "langchain-core" },