mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-11-22 13:51:01 +01:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
677faf987f | ||
|
|
30da2a6ceb | ||
|
|
bcb3bd880d | ||
|
|
375786ca38 | ||
|
|
90014f36ff | ||
|
|
06646f85b3 |
No files matched your search
@@ -72,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")
|
||||
|
||||
@@ -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)
|
||||
@@ -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."""
|
||||
|
||||
@@ -194,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:
|
||||
|
||||
@@ -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,
|
||||
@@ -349,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
|
||||
|
||||
@@ -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,
|
||||
@@ -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(
|
||||
|
||||
@@ -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"}]
|
||||
@@ -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
|
||||
@@ -1332,7 +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;
|
||||
hydrate state from channels via `CONFIG_KEY_READ`.
|
||||
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":
|
||||
@@ -1343,15 +1343,11 @@ class ToolNode(RunnableCallable):
|
||||
and isinstance(input[-1], dict)
|
||||
and input[-1].get("type") == "tool_call"
|
||||
):
|
||||
read = config.get(CONF, {}).get(CONFIG_KEY_READ)
|
||||
if read is None:
|
||||
try:
|
||||
return read_state()
|
||||
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,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:
|
||||
|
||||
Reference in new issue
Block a user