Compare commits

..
Author SHA1 Message Date
Hugo DURAND 3e3dbd42c5 feat(cli): add url to deploy list --json (#9793) 2026-11-25 15:48:14 -05:00
Hugo DURAND ad48a3597d release(cli): 0.4.44 (#9794) 2026-11-25 14:43:12 -05:00
Sera f96105368f fix(langgraph): give add_messages writes and StateGraph input message ids before they are saved (#9772)
Servers reading checkpoints key messages by id, so messages need ids
before saving. On `add_messages` channels and `StateGraph` input only
the reducer assigns them: `updates` shows `id=None`, `Overwrite` saves
none, and replays mint new ones. Fixes #9757.

## Changes
- `add_messages` writes, `Overwrite` and `format=` partials included,
get ids before saving; only `None` counts as missing.
- `StateGraph` input gets ids by channel, saved with the input
checkpoint (uuid4, not run-derived). Input is copied; only message
fields change.
- DeltaChannels: `id=""` message objects get ids; in an `Overwrite`, a
pair stays one message, and on `_messages_delta_reducer` channels a lone
one becomes a list.

## Reviewer notes
- Message dicts in `updates`, history and saved writes gain an `"id"`;
two langgraph-api exact-match tests break.
- Strings, `(role, content)` tuples and JSON pair lists can't carry an
id, so become messages there, and in an `Overwrite`'s state.
- JS needs the same change; langgraphjs#3412 covers input.

## Where message ids are set

Before: the reducer mints the id after the write is saved.

```mermaid
sequenceDiagram
    participant W as Node return or client input
    participant C as Checkpoint (saved write, input)
    participant S as updates and history
    participant R as add_messages
    W->>C: role/content dict, no id
    W->>S: no id
    C->>R: apply saved write
    R-->>C: state gets id A
    Note over C,R: Replay, fork or resume applies the write again: id B
```

After: the id is set before the write is saved.

```mermaid
sequenceDiagram
    participant W as Node return or client input
    participant E as ensure_message_ids
    participant C as Checkpoint (saved write, input)
    participant S as updates and history
    participant R as add_messages
    W->>E: role/content dict
    E->>C: same dict + id A
    E->>S: same dict + id A
    C->>R: apply saved write
    R-->>C: state keeps id A
    Note over C,R: Replay, fork or resume applies the write again: still id A
```

| Written | Saved and streamed as |
|---|---|
| Message dict | Same dict, plus `"id"` |
| Message object | Same object, `id` set |
| String, `(role, content)`, `["user", "hi"]` | Message object |
| `Overwrite` in any form | Same form, items get ids |

## Test Plan
- [x] `updates` ids equal saved ids for dict, tuple and string node
outputs
- [x] `Overwrite` ids stable across `get_state` and a fork
- [x] Replay from the first checkpoint keeps input ids (sync, async,
exit; dict, Pydantic, dataclass and root-channel input)
- [x] `add_messages` keeps `id=""`; a DeltaChannel message with `id=""`
gets an id
- [x] Dict input keeps its keys and order; dataclass input (frozen too)
isn't re-initialized
- [x] Saved ids match applied ids after resume, `Command.update`,
`update_state` and async runs, on every checkpointer
- [x] In an `Overwrite`, a pair stays one message and a lone message
survives the next write (#9757 repro)
- [x] langchain v1 and deepagents unit tests unchanged
2026-11-24 15:11:23 -05:00
Elior Nataf Lackritz 732da52047 fix(langgraph): stream tool events live with stream_mode="tools" alone (#9779)
`graph.stream(..., stream_mode="tools")` on its own delivered every tool
event of a step only when the step ended. `Pregel.stream` and `astream`
hand events to the caller in the middle of a step only when they start a
waiter on the stream queue, and they started it for `"messages"`,
`"custom"`, `subgraphs=True` and `stream_eager`, not for `"tools"`.
Without the waiter the caller gets control back only when a task of the
step finishes, and a step's only task runs inline in the caller. So a
tool that reports progress with `runtime.emit_output_delta(...)` showed
none of it until the tool returned, unless the caller also asked for one
of the other modes.

`"tools"` now starts the waiter too, in both `stream` and `astream`. As
with `"messages"` and `"custom"`, a step's only node then runs on the
executor (a worker thread for sync, its own task for async) instead of
inline in the caller.

With a tool that emits a delta, sleeps 0.3 s, emits another and sleeps
0.3 s, the four events all arrive at 0.61 s on `main`. Here they arrive
at 0.00, 0.00, 0.31 and 0.61 s, sync and async.

The two new tests hold the tool until the consumer has received its
first delta. Both fail on `main`, where the delta arrives after the tool
has returned.

## Release note

`stream_mode="tools"` now streams tool events as they happen when it is
the only mode requested. Before, they arrived together when the step
ended unless `"messages"`, `"custom"` or `subgraphs=True` was also set.
2026-11-24 15:38:30 +00:00
Elior Nataf Lackritz 58d4a1c8d7 fix(langgraph): add "tools" to the public StreamMode type (#9778)
`graph.stream(..., stream_mode="tools")` works at run time and emits
`tool-started`, `tool-output-delta`, `tool-finished` and `tool-error`
events for each tool call. The public types did not know about it.
`StreamMode` did not list `"tools"`, so a type checker rejected the
call, and `StreamPart` had no member for it, so a `version="v2"` part
with `type == "tools"` could not be narrowed.

This adds `"tools"` to `StreamMode`, and a `ToolsStreamPart` to the
`StreamPart` union. Its `data` is a new `ToolsPayload`, one typed dict
per event, told apart by the `event` key. The `stream` and `astream`
docstrings now list the mode. Only types and docstrings change, nothing
at run time.

Code that matches `StreamPart` exhaustively (an `assert_never` in the
last branch) gets a type error until it handles `"tools"`.

`test_v2_parts_have_the_declared_keys` runs a tool that streams a chunk
and then returns or raises, and checks the keys of every part and
payload against the declared types, so they cannot drift from what the
handler emits. It fails on `main`. mypy agrees: `graph.stream({},
stream_mode="tools", version="v2")` is a `call-overload` error on `main`
and passes here.

## Release note

`"tools"` is now part of the `StreamMode` type, and `StreamPart` has a
`ToolsStreamPart` member with a typed `ToolsPayload`.
`stream_mode="tools"` passes a type checker, and its `version="v2"`
parts narrow by `type` and then by `event`.
2026-11-24 10:29:28 -05:00
Sera b4fe40f810 refactor(langgraph): name the __root__ channel with a ROOT constant (#9775)
`__root__`, the single channel StateGraph creates for a field-less state
schema, was a bare string repeated across the engine, unlike `START`,
`NS_SEP` and the other reserved names.

## Changes
- Add `ROOT` to `_internal/_constants.py` and use it in
`graph/state.py`, `pregel/_draw.py` and `types.py`. No behavior change.

## Reviewer notes
- `ROOT` is not added to the reserved-names set, so node-name validation
is unchanged.

## Test Plan
- [x] `make lint` (ruff, ty) and state/pregel/messages tests pass

[no screenshot]

🤖 Generated with [Claude Code](https://claude.com/claude-code)
2026-11-24 10:48:27 +00:00
14 changed files with 871 additions and 140 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
__version__ = "0.4.43"
__version__ = "0.4.44"
+4 -2
View File
@@ -670,7 +670,7 @@ class DeploymentRow:
return (self.id, self.name, self.url)
def as_json(self) -> dict[str, str | None]:
return {"id": self.id, "name": self.name}
return {"id": self.id, "name": self.name, "url": self.url}
DEPLOYMENTS_TABLE = Table(
@@ -2728,7 +2728,9 @@ def _deploy_cmd(
"json_output",
is_flag=True,
default=False,
help="Print the Agent Servers as a JSON array of {id, name} instead of a table.",
help=(
"Print the Agent Servers as a JSON array of {id, name, url} instead of a table."
),
)
@deploy.command("list", help="[Beta] List Agent Servers.")
def deploy_list(
+8 -4
View File
@@ -615,8 +615,8 @@ def test_deploy_list_command_json(monkeypatch) -> None:
assert result.exit_code == 0, result.output
assert json.loads(result.stdout) == [
{"id": "dep-123", "name": "alpha"},
{"id": "dep-456", "name": "beta"},
{"id": "dep-123", "name": "alpha", "url": "https://alpha.example.com"},
{"id": "dep-456", "name": "beta", "url": None},
]
@@ -635,7 +635,9 @@ def test_deploy_list_json_never_prints_deployment_secrets(monkeypatch) -> None:
assert result.exit_code == 0, result.output
assert "sk-plain-value" not in result.output
assert json.loads(result.stdout) == [{"id": "dep-123", "name": "alpha"}]
assert json.loads(result.stdout) == [
{"id": "dep-123", "name": "alpha", "url": None}
]
def test_deploy_list_command_json_no_results(monkeypatch) -> None:
@@ -663,7 +665,9 @@ def test_deploy_list_json_keeps_the_agent_note_off_stdout(monkeypatch) -> None:
)
assert result.exit_code == 0, result.output
assert json.loads(result.stdout) == [{"id": "dep-123", "name": "alpha"}]
assert json.loads(result.stdout) == [
{"id": "dep-123", "name": "alpha", "url": None}
]
assert "private beta" in result.stderr
@@ -93,6 +93,8 @@ PUSH = sys.intern("__pregel_push")
# denotes push-style tasks, ie. those created by Send objects
PULL = sys.intern("__pregel_pull")
# denotes pull-style tasks, ie. those triggered by edges
ROOT = sys.intern("__root__")
# the single channel of a StateGraph whose state schema has no fields
NS_SEP = sys.intern("|")
# for checkpoint_ns, separates each level (ie. graph|subgraph|subsubgraph)
NS_END = sys.intern(":")
+14 -13
View File
@@ -37,6 +37,7 @@ from langgraph._internal._constants import (
INTERRUPT,
NS_END,
NS_SEP,
ROOT,
TASKS,
)
from langgraph._internal._fields import (
@@ -1268,9 +1269,9 @@ class StateGraph(Generic[StateT, ContextT, InputT, OutputT]):
# prepare output channels
output_channels = (
"__root__"
ROOT
if len(self.schemas[self.output_schema]) == 1
and "__root__" in self.schemas[self.output_schema]
and ROOT in self.schemas[self.output_schema]
else [
key
for key, val in self.schemas[self.output_schema].items()
@@ -1278,8 +1279,8 @@ class StateGraph(Generic[StateT, ContextT, InputT, OutputT]):
]
)
stream_channels = (
"__root__"
if len(self.channels) == 1 and "__root__" in self.channels
ROOT
if len(self.channels) == 1 and ROOT in self.channels
else [
key for key, val in self.channels.items() if not is_managed_value(val)
]
@@ -1498,7 +1499,7 @@ class CompiledStateGraph(
# state updaters
write_entries: tuple[ChannelWriteEntry | ChannelWriteTupleEntry, ...] = (
ChannelWriteTupleEntry(
mapper=_get_root if output_keys == ["__root__"] else _get_updates
mapper=_get_root if output_keys == [ROOT] else _get_updates
),
ChannelWriteTupleEntry(
mapper=_control_branch,
@@ -1519,7 +1520,7 @@ class CompiledStateGraph(
elif node is not None:
input_schema = node.input_schema if node else self.builder.state_schema
input_channels = list(self.builder.schemas[input_schema])
is_single_input = len(input_channels) == 1 and "__root__" in input_channels
is_single_input = len(input_channels) == 1 and ROOT in input_channels
if input_schema in self.schema_to_mapper:
mapper = self.schema_to_mapper[input_schema]
else:
@@ -1535,7 +1536,7 @@ class CompiledStateGraph(
self.nodes[key] = PregelNode(
triggers=[branch_channel],
# read state keys and managed values
channels=("__root__" if is_single_input else input_channels),
channels=(ROOT if is_single_input else input_channels),
# coerce state dict to schema class (eg. pydantic model)
mapper=mapper,
# publish to state keys
@@ -1616,7 +1617,7 @@ class CompiledStateGraph(
# create reader
reader: Callable[[RunnableConfig], Any] | None = partial(
ChannelRead.do_read,
select=channels[0] if channels == ["__root__"] else channels,
select=channels[0] if channels == [ROOT] else channels,
fresh=True,
# coerce state dict to schema class (eg. pydantic model)
mapper=mapper,
@@ -1736,7 +1737,7 @@ class CompiledStateGraph(
def _pick_mapper(
state_keys: Sequence[str], schema: type[Any]
) -> Callable[[Any], Any] | None:
if state_keys == ["__root__"]:
if state_keys == [ROOT]:
return None
if isclass(schema) and (issubclass(schema, BaseModel) or is_dataclass(schema)):
return partial(_coerce_state, schema)
@@ -1810,10 +1811,10 @@ def _get_root(input: Any) -> Sequence[tuple[str, Any]] | None:
continue
updates.extend(i._update_as_tuples())
else:
updates.append(("__root__", i))
updates.append((ROOT, i))
return updates
elif input is not None:
return [("__root__", input)]
return [(ROOT, input)]
def _get_channels(
@@ -1821,7 +1822,7 @@ def _get_channels(
) -> tuple[dict[str, BaseChannel], dict[str, ManagedValueSpec], dict[str, Any]]:
if not hasattr(schema, "__annotations__"):
return (
{"__root__": _get_channel("__root__", schema, allow_managed=False)},
{ROOT: _get_channel(ROOT, schema, allow_managed=False)},
{},
{},
)
@@ -1957,7 +1958,7 @@ def _get_json_schema(
return TypeAdapter(typ).json_schema()
else:
keys = list(schemas[typ].keys())
if len(keys) == 1 and keys[0] == "__root__":
if len(keys) == 1 and keys[0] == ROOT:
return create_model(
name,
root=(channels[keys[0]].UpdateType, None),
+3 -3
View File
@@ -8,7 +8,7 @@ from langchain_core.runnables.config import RunnableConfig
from langchain_core.runnables.graph import Graph, Node
from langgraph.checkpoint.base import BaseCheckpointSaver
from langgraph._internal._constants import CONF, CONFIG_KEY_SEND, INPUT
from langgraph._internal._constants import CONF, CONFIG_KEY_SEND, INPUT, ROOT
from langgraph.channels.base import BaseChannel
from langgraph.channels.last_value import LastValueAfterFinish
from langgraph.constants import END, START
@@ -125,8 +125,8 @@ def draw_graph(
# apply regular writes
if isinstance(w, ChannelWrite):
empty_input = (
cast(BaseChannel, specs["__root__"]).ValueType()
if "__root__" in specs
cast(BaseChannel, specs[ROOT]).ValueType()
if ROOT in specs
else None
)
w.invoke(empty_input, task.config)
+186 -75
View File
@@ -1,5 +1,7 @@
from __future__ import annotations
import copy
import uuid
from collections.abc import (
AsyncIterator,
Callable,
@@ -9,8 +11,10 @@ from collections.abc import (
Sequence,
)
from dataclasses import fields, is_dataclass
from functools import cache, partial
from typing import (
Any,
TypeGuard,
TypeVar,
cast,
)
@@ -23,10 +27,10 @@ from langchain_core.outputs import ChatGeneration, ChatGenerationChunk, LLMResul
from pydantic import BaseModel
from langgraph._internal._config import filter_to_user_tags
from langgraph._internal._constants import NS_SEP, PUSH
from langgraph.channels.binop import _get_overwrite
from langgraph._internal._constants import NS_SEP, OVERWRITE, PUSH, ROOT
from langgraph.channels.binop import BinaryOperatorAggregate, _get_overwrite
from langgraph.channels.delta import DeltaChannel
from langgraph.constants import TAG_HIDDEN, TAG_NOSTREAM
from langgraph.constants import START, TAG_HIDDEN, TAG_NOSTREAM
from langgraph.pregel.protocol import StreamChunk
from langgraph.types import Command, Overwrite
@@ -46,12 +50,16 @@ Meta = tuple[tuple[str, ...], dict[str, Any]]
def _state_values(obj: Any) -> Sequence[Any]:
"""Extract top-level field values from a state object (dict, BaseModel, or dataclass)."""
return [v for _, v in _state_items(obj)]
def _state_items(obj: object) -> Sequence[tuple[str, object]]:
if isinstance(obj, dict):
return list(obj.values())
return list(obj.items())
elif isinstance(obj, BaseModel):
return [getattr(obj, k) for k in type(obj).model_fields]
return [(k, getattr(obj, k)) for k in type(obj).model_fields]
elif is_dataclass(obj) and not isinstance(obj, type):
return [getattr(obj, f.name) for f in fields(obj)]
return [(f.name, getattr(obj, f.name)) for f in fields(obj)]
return ()
@@ -524,102 +532,205 @@ def _is_message_dict(item: dict) -> bool:
def ensure_message_ids(
channels: Mapping[str, Any], writes: Sequence[tuple[str, Any]]
channels: Mapping[str, object], writes: Sequence[tuple[str, object]]
) -> None:
"""Give the messages written to DeltaChannels stable ids.
"""Give the messages written to messages channels stable ids.
A `DeltaChannel` replays its saved writes on every read, and its reducer
may not assign missing ids (`_messages_delta_reducer` doesn't), so a
message saved without an id comes back without one, or with a new one on
every read, and nothing can target it by id, for example `RemoveMessage`.
A message saved without an id gets one later, when a reducer reads it, so
the `updates` stream, the saved write and the state can each show a
different id, and a replay or fork from that checkpoint mints a new one.
A `DeltaChannel` replays its saved writes on every read, so there the id
can change on every read.
In a channel whose reducer is `_messages_delta_reducer`, every message-like
it accepts (a message, a dict, a string, a `(role, content)` tuple; alone,
in a list or in an `Overwrite`) becomes a message with an id. Other
DeltaChannels may hold other data, so there only message objects get ids,
plus message dicts outside an `Overwrite`: one in a list becomes a message.
Anything that can't become a message is left as it is, so it fails where
it always has: a message dict in a list raises here, anything else when
the reducer reads it. An empty id counts as missing.
A `StateGraph` input is one write to `START`; the values in it get ids by
the channel they go to, so the input checkpoint saves them. In a graph
with one root channel, the whole input goes to that channel.
A write that changes is replaced in `writes`: lists and dicts the caller
passed in are never changed, only the ids of message objects.
"""
for i, (ch, value) in enumerate(writes):
spec = channels.get(ch)
if not isinstance(spec, DeltaChannel):
continue
if spec.reducer is _messages_delta_reducer:
new_value = _with_message_ids(value)
if ch == START:
new_value = _input_with_message_ids(channels, value)
else:
new_value = _with_base_message_ids(value)
new_value = _channel_value_with_message_ids(channels.get(ch), value)
if new_value is not value:
cast(MutableSequence[tuple[str, Any]], writes)[i] = (ch, new_value)
cast(MutableSequence[tuple[str, object]], writes)[i] = (ch, new_value)
def _with_message_ids(value: Any) -> Any:
is_overwrite, overwrite_value = _get_overwrite(value)
if not is_overwrite:
if isinstance(value, list):
return _map_messages(value, _list_item_with_id)
return _message_with_id(value)
if isinstance(overwrite_value, (list, tuple)):
items = _map_messages(overwrite_value, _message_with_id)
if items is not overwrite_value:
return Overwrite(items)
def _channel_value_with_message_ids(spec: object, value: object) -> object:
if isinstance(spec, DeltaChannel):
if spec.reducer is _messages_delta_reducer:
return _delta_messages_ids(value)
return _delta_ids(value)
if isinstance(spec, BinaryOperatorAggregate) and _is_add_messages(spec.operator):
return _add_messages_ids(value)
return value
def _with_base_message_ids(value: Any) -> Any:
is_overwrite, overwrite_value = _get_overwrite(value)
if is_overwrite:
if isinstance(overwrite_value, (list, tuple)):
for item in overwrite_value:
_stamp_message_id(item)
def _input_with_message_ids(channels: Mapping[str, object], value: object) -> object:
if ROOT in channels:
return _channel_value_with_message_ids(channels[ROOT], value)
changed = {
name: new
for name, old in _state_items(value)
if (new := _channel_value_with_message_ids(channels.get(name), old)) is not old
}
if not changed:
return value
if isinstance(value, list):
return _map_messages(value, _base_list_item_with_id)
if isinstance(value, dict) and _is_message_dict(value) and not value.get("id"):
return {**value, "id": str(uuid4())}
_stamp_message_id(value)
return value
if isinstance(value, dict):
return {k: changed.get(k, v) for k, v in value.items()}
if isinstance(value, BaseModel):
return value.model_copy(update=changed)
# Not `dataclasses.replace`, which reruns `__post_init__`.
new_value = copy.copy(value)
for name, field_value in changed.items():
object.__setattr__(new_value, name, field_value)
return new_value
def _map_messages(items: list | tuple, fn: Callable[[Any], Any]) -> list | tuple:
mapped = [fn(item) for item in items]
@cache
def _add_messages_reducers() -> tuple[object, object]:
# Imported here: `langgraph.graph.message` imports this module.
from langgraph.graph.message import add_messages
return add_messages, cast(Callable[[], partial], add_messages)().func
def _is_add_messages(operator: object) -> bool:
add_messages, func = _add_messages_reducers()
if isinstance(operator, partial):
return operator.func is func
return operator is add_messages
def _add_messages_ids(value: object) -> object:
is_overwrite, items = _unwrap(value)
if _is_many(items, is_overwrite):
new = _map_messages(items, _add_messages_item)
else:
new = _add_messages_item(items)
return _rewrap(value, is_overwrite, items, new)
def _delta_messages_ids(value: object) -> object:
is_overwrite, items = _unwrap(value)
if not _is_many(items, is_overwrite):
new = _message(items)
if is_overwrite and isinstance(new, BaseMessage):
new = [new]
elif is_overwrite:
new = _map_messages(items, _message)
else:
new = _map_messages(items, _delta_messages_list_item)
return _rewrap(value, is_overwrite, items, new)
def _delta_ids(value: object) -> object:
"""Other DeltaChannels may hold other data, so less is converted."""
is_overwrite, items = _unwrap(value)
if is_overwrite:
many = _is_many(items, is_overwrite)
new = _map_messages(items, _stamped) if many else _stamped(items)
elif isinstance(items, list):
new = _map_messages(items, _delta_list_item)
else:
new = _dict_with_id(items)
return _rewrap(value, is_overwrite, items, new)
def _unwrap(value: object) -> tuple[bool, object]:
is_overwrite, items = _get_overwrite(value)
return is_overwrite, items if is_overwrite else value
def _rewrap(value: object, is_overwrite: bool, items: object, new: object) -> object:
if new is items:
return value
if not is_overwrite:
return new
if isinstance(value, dict):
return {OVERWRITE: new} if OVERWRITE in value else {**value, "value": new}
return Overwrite(new)
def _is_many(
items: object, is_overwrite: bool
) -> TypeGuard[list[object] | tuple[object, ...]]:
"""In an `Overwrite`, a tuple is many messages unless it's a `(role, content)` pair."""
if isinstance(items, list):
return True
return is_overwrite and isinstance(items, tuple) and not _is_message_pair(items)
def _is_message_pair(items: tuple[object, ...]) -> bool:
if len(items) != 2 or not isinstance(items[0], str):
return False
try:
convert_to_messages([items])
except Exception:
return False
return True
def _map_messages(
items: list[object] | tuple[object, ...], step: Callable[[object], object]
) -> list[object] | tuple[object, ...]:
mapped = [step(item) for item in items]
if all(new is old for new, old in zip(mapped, items)):
return items
return mapped if isinstance(items, list) else tuple(mapped)
def _list_item_with_id(item: Any) -> Any:
if isinstance(item, dict) and _is_message_dict(item):
return _message_with_id(item, strict=True)
return _message_with_id(item)
def _new_id() -> str:
return str(uuid.uuid4())
def _base_list_item_with_id(item: Any) -> Any:
if isinstance(item, dict) and _is_message_dict(item):
return _message_with_id(item, strict=True)
_stamp_message_id(item)
def _needs_id(id: object, *, keep_empty: bool) -> bool:
return id is None or (not keep_empty and not id)
def _stamped(item: T, *, keep_empty: bool = False) -> T:
if isinstance(item, BaseMessage) and _needs_id(item.id, keep_empty=keep_empty):
item.id = _new_id()
return item
def _message_with_id(item: Any, *, strict: bool = False) -> Any:
if isinstance(item, BaseMessage):
_stamp_message_id(item)
return item
try:
message = convert_to_messages([item])[0]
except Exception:
if strict:
raise
return item
if not message.id:
message.id = str(uuid4())
return message
def _dict_with_id(item: object, *, keep_empty: bool = False) -> object:
if not isinstance(item, dict):
return _stamped(item, keep_empty=keep_empty)
if _is_message_dict(item) and _needs_id(item.get("id"), keep_empty=keep_empty):
return {**item, "id": _new_id()}
return item
def _stamp_message_id(item: Any) -> None:
if isinstance(item, BaseMessage) and not item.id:
item.id = str(uuid4())
def _message(item: object, *, strict: bool = False, keep_empty: bool = False) -> object:
if not isinstance(item, BaseMessage):
try:
item = convert_to_messages([item])[0]
except Exception:
if strict:
raise
return item
return _stamped(item, keep_empty=keep_empty)
def _is_list_message_dict(item: object) -> TypeGuard[dict[str, object]]:
# Raises here, before it is saved, if it can't become a message.
return isinstance(item, dict) and _is_message_dict(item)
def _delta_messages_list_item(item: object) -> object:
return _message(item, strict=_is_list_message_dict(item))
def _delta_list_item(item: object) -> object:
if _is_list_message_dict(item):
return _message(item, strict=True)
return _dict_with_id(item)
def _add_messages_item(item: object) -> object:
if isinstance(item, dict):
return _dict_with_id(item, keep_empty=True)
return _message(item, keep_empty=True)
+5 -1
View File
@@ -717,7 +717,7 @@ class Pregel(
stream_eager: bool = False
"""Whether to force emitting stream events eagerly, automatically turned on
for stream_mode "messages" and "custom"."""
for stream_mode "messages", "custom" and "tools"."""
output_channels: str | Sequence[str]
@@ -2803,6 +2803,7 @@ class Pregel(
- `"checkpoints"`: Emit an event when a checkpoint is created, in the same format as returned by `get_state()`.
- `"tasks"`: Emit events when tasks start and finish, including their results and errors.
- `"debug"`: Emit debug events with as much information as possible for each step.
- `"tools"`: Emit events when tool calls start, stream partial output, finish, and fail.
You can pass a list as the `stream_mode` parameter to stream multiple modes at once.
The streamed outputs will be tuples of `(mode, data)`.
@@ -3056,6 +3057,7 @@ class Pregel(
or subgraphs
or "messages" in stream_modes
or "custom" in stream_modes
or "tools" in stream_modes
):
# we are careful to have a single waiter live at any one time
# because on exit we increment semaphore count by exactly 1
@@ -3216,6 +3218,7 @@ class Pregel(
- `"checkpoints"`: Emit an event when a checkpoint is created, in the same format as returned by `get_state()`.
- `"tasks"`: Emit events when tasks start and finish, including their results and errors.
- `"debug"`: Emit debug events with as much information as possible for each step.
- `"tools"`: Emit events when tool calls start, stream partial output, finish, and fail.
You can pass a list as the `stream_mode` parameter to stream multiple modes at once.
The streamed outputs will be tuples of `(mode, data)`.
@@ -3510,6 +3513,7 @@ class Pregel(
or subgraphs
or "messages" in stream_modes
or "custom" in stream_modes
or "tools" in stream_modes
):
# Keep a single waiter task alive; ensure cleanup on exit.
waiter: asyncio.Task[None] | None = None
+74 -4
View File
@@ -33,7 +33,7 @@ from xxhash import xxh3_128_hexdigest
from langgraph._internal._cache import default_cache_key
from langgraph._internal._constants import INTERRUPT as _INTERRUPT_KEY
from langgraph._internal._constants import NS_SEP
from langgraph._internal._constants import NS_SEP, ROOT
from langgraph._internal._fields import get_cached_annotated_keys, get_update_as_tuples
from langgraph._internal._retry import default_retry_on
from langgraph._internal._typing import MISSING, DeprecatedKwargs
@@ -72,8 +72,10 @@ __all__ = (
"CheckpointStreamPart",
"TasksStreamPart",
"DebugStreamPart",
"ToolsStreamPart",
"TaskPayload",
"TaskResultPayload",
"ToolsPayload",
"CheckpointTask",
"CheckpointPayload",
"DebugPayload",
@@ -130,7 +132,7 @@ def ensure_valid_checkpointer(checkpointer: Checkpointer) -> Checkpointer:
StreamMode = Literal[
"values", "updates", "checkpoints", "tasks", "debug", "messages", "custom"
"values", "updates", "checkpoints", "tasks", "debug", "messages", "custom", "tools"
]
"""How the stream method should emit outputs.
@@ -143,6 +145,7 @@ StreamMode = Literal[
- `"checkpoints"`: Emit an event when a checkpoint is created, in the same format as returned by `get_state()`.
- `"tasks"`: Emit events when tasks start and finish, including their results and errors.
- `"debug"`: Emit `"checkpoints"` and `"tasks"` events for debugging purposes.
- `"tools"`: Emit events when tool calls start, stream partial output, finish, and fail.
"""
StreamWriter = Callable[[Any], None]
@@ -271,6 +274,59 @@ DebugPayload = TypeAliasType(
"""Wrapper payload for debug events. Discriminate on `type`."""
class _ToolStartedPayload(TypedDict):
event: Literal["tool-started"]
"""Event type discriminator, always `"tool-started"`."""
tool_call_id: str
"""ID of the tool call, or the ID of the tool's run if it was not called with one."""
tool_name: str
"""Name of the tool being called."""
input: NotRequired[dict[str, Any]]
"""Arguments passed to the tool, without injected ones.
Absent when the tool was called with a plain string.
"""
class _ToolOutputDeltaPayload(TypedDict):
event: Literal["tool-output-delta"]
"""Event type discriminator, always `"tool-output-delta"`."""
tool_call_id: str
"""ID of the tool call that emitted this delta."""
delta: Any
"""Partial output the tool passed to `ToolRuntime.emit_output_delta`."""
class _ToolFinishedPayload(TypedDict):
event: Literal["tool-finished"]
"""Event type discriminator, always `"tool-finished"`."""
tool_call_id: str
"""ID of the tool call that finished."""
output: Any
"""Output of the tool call.
In a `ToolNode`, a plain return value arrives wrapped in a `ToolMessage`.
"""
class _ToolErrorPayload(TypedDict):
event: Literal["tool-error"]
"""Event type discriminator, always `"tool-error"`."""
tool_call_id: str
"""ID of the tool call that failed."""
message: str
"""Error message."""
ToolsPayload = (
_ToolStartedPayload
| _ToolOutputDeltaPayload
| _ToolFinishedPayload
| _ToolErrorPayload
)
"""Payload for a tool call event. Discriminate on `event`."""
class ValuesStreamPart(TypedDict, Generic[OutputT]):
"""Stream part emitted for `stream_mode="values"`.
@@ -350,6 +406,19 @@ class DebugStreamPart(TypedDict, Generic[StateT]):
data: DebugPayload[StateT]
class ToolsStreamPart(TypedDict):
"""Stream part emitted for `stream_mode="tools"`.
`data` is a `ToolsPayload`: one of the `tool-started`,
`tool-output-delta`, `tool-finished` and `tool-error` events,
told apart by its `event` key.
"""
type: Literal["tools"]
ns: tuple[str, ...]
data: ToolsPayload
StreamPart = TypeAliasType(
"StreamPart",
ValuesStreamPart[OutputT]
@@ -358,7 +427,8 @@ StreamPart = TypeAliasType(
| CustomStreamPart
| CheckpointStreamPart[StateT]
| TasksStreamPart
| DebugStreamPart[StateT],
| DebugStreamPart[StateT]
| ToolsStreamPart,
type_params=(StateT, OutputT),
)
"""A discriminated union of all v2 stream part types.
@@ -885,7 +955,7 @@ class Command(Generic[N], ToolOutputMixin):
elif keys := get_cached_annotated_keys(type(self.update)):
return get_update_as_tuples(self.update, keys)
elif self.update is not None:
return [("__root__", self.update)]
return [(ROOT, self.update)]
else:
return []
@@ -8,19 +8,22 @@ ID in each LangSmith trace / on every resumed invocation.
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Annotated, Any
import pytest
from langchain_core.messages import AIMessage, AnyMessage, HumanMessage
from langchain_core.messages import AIMessage, AnyMessage, HumanMessage, SystemMessage
from langgraph.checkpoint.base import BaseCheckpointSaver
from langgraph.checkpoint.memory import InMemorySaver
from pydantic import BaseModel
from typing_extensions import TypedDict
from langgraph.channels.delta import DeltaChannel
from langgraph.channels.last_value import LastValue
from langgraph.graph import END, START, StateGraph
from langgraph.graph.message import _messages_delta_reducer
from langgraph.graph.message import _messages_delta_reducer, add_messages
from langgraph.pregel import NodeBuilder, Pregel
from langgraph.types import Command, Durability, Overwrite
from langgraph.types import Command, Durability, Overwrite, interrupt
pytestmark = pytest.mark.anyio
@@ -43,10 +46,13 @@ def _build_graph(
*,
reducer: Any = _append_reducer,
write: Any = lambda: [AIMessage(content="reply", id="ai-1")],
channel: Any = None,
) -> Any:
if channel is None:
channel = DeltaChannel(reducer, snapshot_frequency=50)
State = TypedDict( # noqa: UP013
"State",
{"messages": Annotated[list, DeltaChannel(reducer, snapshot_frequency=50)]},
{"messages": Annotated[list, channel]},
) # type: ignore[call-overload]
def agent(state: dict) -> dict:
@@ -173,28 +179,38 @@ def test_delta_channel_message_in_an_overwrite_gets_stable_id(container: type) -
MESSAGE_SHAPES = [
pytest.param(lambda: [HumanMessage("hello")], id="message"),
pytest.param(lambda: HumanMessage("hello"), id="bare message"),
pytest.param(lambda: [HumanMessage("hello", id="")], id="message, empty id"),
pytest.param(lambda: [{"role": "user", "content": "hello"}], id="dict"),
pytest.param(lambda: {"type": "human", "content": "hello"}, id="bare dict"),
pytest.param(
lambda: [{"role": "user", "content": "hello", "id": ""}], id="dict, empty id"
),
pytest.param(lambda: [HumanMessage("hello", id="")], id="message, empty id"),
pytest.param(lambda: [("user", "hello")], id="tuple"),
pytest.param(lambda: ("user", "hello"), id="bare tuple"),
pytest.param(lambda: ["hello"], id="string"),
pytest.param(lambda: "hello", id="bare string"),
pytest.param(lambda: Overwrite(["hello"]), id="Overwrite"),
pytest.param(lambda: Overwrite(("hello",)), id="Overwrite of a tuple"),
pytest.param(lambda: Overwrite(HumanMessage("hello")), id="Overwrite of a message"),
pytest.param(lambda: Overwrite(("user", "hello")), id="Overwrite of a pair"),
pytest.param(lambda: {"__overwrite__": [("user", "hello")]}, id="Overwrite dict"),
]
def _id(m: Any) -> str | None:
return m.get("id") if isinstance(m, dict) else m.id
def _hello_ids(graph: Any, config: dict) -> list[str | None]:
def messages() -> list:
value = graph.get_state(config).values["messages"]
return value if isinstance(value, list) else [value]
return [
next(
m.id
for m in graph.get_state(config).values["messages"]
if m.content == "hello"
_id(m)
for m in messages()
if (m.get("content") if isinstance(m, dict) else m.content) == "hello"
)
for _ in range(2)
]
@@ -224,31 +240,6 @@ def test_node_message_of_any_shape_gets_stable_id(write: Any) -> None:
assert first == second, "its id must be the same on every read"
@pytest.mark.parametrize(
"write",
[
pytest.param(
lambda: [HumanMessage("a", id=""), HumanMessage("b", id="")],
id="messages",
),
pytest.param(
lambda: Overwrite([HumanMessage("a", id=""), HumanMessage("b", id="")]),
id="Overwrite",
),
],
)
def test_messages_with_empty_ids_in_one_write_get_distinct_ids(write: Any) -> None:
graph = _build_graph(InMemorySaver(), reducer=_messages_delta_reducer, write=write)
config = {"configurable": {"thread_id": "t"}}
graph.invoke({"messages": []}, config)
messages = graph.get_state(config).values["messages"]
assert [m.content for m in messages] == ["a", "b"]
assert all(m.id for m in messages), "each message should get a UUID"
assert messages[0].id != messages[1].id
def test_a_list_written_twice_adds_its_messages_twice() -> None:
turn = [("user", "hello")]
graph = _build_graph(InMemorySaver(), reducer=_messages_delta_reducer)
@@ -359,3 +350,435 @@ def test_other_delta_channels_keep_the_dicts_in_an_overwrite(value: dict) -> Non
graph.invoke({"messages": []}, config)
assert graph.get_state(config).values["messages"] == [value]
MESSAGES_CHANNELS = [
pytest.param(lambda: DeltaChannel(_messages_delta_reducer), id="delta"),
pytest.param(lambda: add_messages, id="add_messages"),
]
@pytest.mark.parametrize("channel", MESSAGES_CHANNELS)
@pytest.mark.parametrize(
"write",
[
pytest.param(lambda: [{"role": "user", "content": "hello"}], id="dict"),
pytest.param(lambda: [("user", "hello")], id="tuple"),
pytest.param(lambda: "hello", id="bare string"),
],
)
def test_updates_carry_the_saved_message_ids(channel: Any, write: Any) -> None:
graph = _build_graph(InMemorySaver(), channel=channel(), write=write)
config = {"configurable": {"thread_id": "t"}}
updates = list(graph.stream({"messages": []}, config, stream_mode="updates"))
streamed = updates[0]["agent"]["messages"]
streamed = streamed if isinstance(streamed, list) else [streamed]
first, second = _hello_ids(graph, config)
assert [_id(m) for m in streamed] == [first], "updates must show the saved id"
assert first == second
def test_add_messages_keeps_a_message_dict_a_dict() -> None:
written = {"role": "user", "content": "hello"}
graph = _build_graph(InMemorySaver(), channel=add_messages, write=lambda: [written])
config = {"configurable": {"thread_id": "t"}}
updates = list(graph.stream({"messages": []}, config, stream_mode="updates"))
(streamed,) = updates[0]["agent"]["messages"]
assert streamed == {**written, "id": streamed["id"]}
assert streamed["id"] == _hello_ids(graph, config)[0]
assert written == {"role": "user", "content": "hello"}, (
"the node's dict is left as is"
)
@pytest.mark.parametrize("channel", MESSAGES_CHANNELS)
@pytest.mark.parametrize(
"write",
[
pytest.param(lambda: Overwrite([HumanMessage("hello")]), id="message"),
pytest.param(
lambda: Overwrite([{"role": "user", "content": "hello"}]), id="dict"
),
pytest.param(lambda: Overwrite([("user", "hello")]), id="tuple"),
pytest.param(
lambda: {"__overwrite__": [{"role": "user", "content": "hello"}]},
id="__overwrite__ dict",
),
pytest.param(
lambda: {
"type": "__overwrite__",
"value": [{"role": "user", "content": "hello"}],
},
id="serialized Overwrite",
),
],
)
def test_an_overwrite_keeps_its_message_ids_in_a_fork(channel: Any, write: Any) -> None:
graph = _build_graph(InMemorySaver(), channel=channel(), write=write)
config = {"configurable": {"thread_id": "t"}}
graph.invoke({"messages": []}, config)
first, second = _hello_ids(graph, config)
forked = graph.update_state(
graph.get_state(config).config, {"messages": [AIMessage("x", id="x")]}
)
assert first, "the message should get a UUID"
assert first == second, "its id must be the same on every read"
assert _hello_ids(graph, forked) == [first, first], "a fork must keep it"
@pytest.mark.parametrize("channel", MESSAGES_CHANNELS)
@pytest.mark.parametrize(
"write",
[
pytest.param(lambda: Overwrite(HumanMessage("hello")), id="message"),
pytest.param(
lambda: Overwrite({"role": "user", "content": "hello"}), id="dict"
),
pytest.param(lambda: Overwrite("hello"), id="string"),
pytest.param(lambda: Overwrite(("user", "hello")), id="pair"),
],
)
def test_one_message_in_an_overwrite_stays_one_message(
channel: Any, write: Any
) -> None:
graph = _build_graph(InMemorySaver(), channel=channel(), write=write)
config = {"configurable": {"thread_id": "t"}}
graph.invoke({"messages": []}, config)
graph.invoke({"messages": [("user", "next")]}, config)
value = graph.get_state(config).values["messages"]
messages = value if isinstance(value, list) else [value]
assert [
m.get("content") if isinstance(m, dict) else m.content for m in messages
] == ["hello"]
first, second = _hello_ids(graph, config)
assert first, "the message should get a UUID"
assert first == second, "its id must be the same on every read"
@pytest.mark.parametrize("channel", MESSAGES_CHANNELS)
@pytest.mark.parametrize(
"input",
[
pytest.param(lambda: [HumanMessage("hello")], id="message"),
pytest.param(lambda: [{"role": "user", "content": "hello"}], id="dict"),
pytest.param(lambda: "hello", id="bare string"),
],
)
def test_a_replay_from_the_first_checkpoint_keeps_the_input_message_ids(
channel: Any, input: Any, durability: Durability
) -> None:
graph = _build_graph(InMemorySaver(), channel=channel())
config = {"configurable": {"thread_id": "t"}}
graph.invoke({"messages": input()}, config, durability=durability)
first, _ = _hello_ids(graph, config)
# `exit` saves no input checkpoint; a DeltaChannel anchor has no `source`.
oldest = [s for s in graph.get_state_history(config) if "source" in s.metadata][-1]
graph.invoke(None, oldest.config)
assert first, "the message should get a UUID"
assert _hello_ids(graph, config) == [first, first]
class _PydanticState(BaseModel):
messages: Annotated[list, add_messages] = []
@dataclass
class _DataclassState:
messages: Annotated[list, add_messages] = field(default_factory=list)
@dataclass
class _SystemPromptState:
messages: Annotated[list, add_messages] = field(default_factory=list)
def __post_init__(self) -> None:
self.messages = [SystemMessage("be brief"), *self.messages]
@dataclass(frozen=True)
class _FrozenDataclassState:
messages: Annotated[list, add_messages] = field(default_factory=list)
@pytest.mark.parametrize(
"schema",
[_PydanticState, _DataclassState, _FrozenDataclassState, _SystemPromptState],
)
@pytest.mark.parametrize(
"input",
[
pytest.param(lambda: [HumanMessage("hello")], id="message"),
pytest.param(lambda: [{"role": "user", "content": "hello"}], id="dict"),
pytest.param(lambda: [("user", "hello")], id="tuple"),
],
)
def test_a_state_object_input_saves_its_message_ids(schema: Any, input: Any) -> None:
graph = (
StateGraph(schema)
.add_node("agent", lambda state: {"messages": [AIMessage("reply")]})
.add_edge(START, "agent")
.compile(checkpointer=InMemorySaver())
)
config = {"configurable": {"thread_id": "t"}}
state = schema(messages=input())
input_types = [type(m) for m in state.messages]
graph.invoke(state, config)
saved = graph.get_state(config).values["messages"]
assert len(saved) == len(state.messages) + 1, "the input is saved as built"
first, _ = _hello_ids(graph, config)
oldest = list(graph.get_state_history(config))[-1]
graph.invoke(None, oldest.config)
assert first, "the message should get a UUID"
assert _hello_ids(graph, config) == [first, first]
assert [type(m) for m in state.messages] == input_types, "the input is left as is"
def test_a_dict_input_keeps_its_keys_and_their_order() -> None:
State = TypedDict( # noqa: UP013
"State", {"topic": str, "messages": Annotated[list, add_messages]}
) # type: ignore[call-overload]
graph = (
StateGraph(State)
.add_node("agent", lambda state: {})
.add_edge(START, "agent")
.compile(checkpointer=InMemorySaver())
)
config = {"configurable": {"thread_id": "t"}}
input = {
"topic": "x",
"messages": [{"role": "user", "content": "hello"}],
"other": 1,
}
graph.invoke(input, config)
saved = list(graph.checkpointer.list(config))[-1].checkpoint["channel_values"]
(message,) = saved["__start__"]["messages"]
assert list(saved["__start__"]) == ["topic", "messages", "other"]
assert saved["__start__"]["topic"] == "x" and saved["__start__"]["other"] == 1
assert message == {"role": "user", "content": "hello", "id": message["id"]}
assert message["id"]
@pytest.mark.parametrize(
"input",
[
pytest.param(lambda: [HumanMessage("hello")], id="message"),
pytest.param(lambda: {"role": "user", "content": "hello"}, id="dict"),
pytest.param(lambda: "hello", id="bare string"),
],
)
def test_a_root_channel_input_saves_its_message_ids(input: Any) -> None:
graph = (
StateGraph(Annotated[list, add_messages])
.add_node("agent", lambda state: [AIMessage("reply")])
.add_edge(START, "agent")
.compile(checkpointer=InMemorySaver())
)
config = {"configurable": {"thread_id": "t"}}
def hello_id() -> str | None:
return next(
_id(m)
for m in graph.get_state(config).values
if (m.get("content") if isinstance(m, dict) else m.content) == "hello"
)
graph.invoke(input(), config)
first = hello_id()
oldest = list(graph.get_state_history(config))[-1]
graph.invoke(None, oldest.config)
assert first, "the message should get a UUID"
assert hello_id() == first
def test_an_overwrite_on_a_formatting_add_messages_channel_gets_a_stable_id() -> None:
graph = _build_graph(
InMemorySaver(),
channel=add_messages(format="langchain-openai"),
write=lambda: Overwrite([HumanMessage("hello")]),
)
config = {"configurable": {"thread_id": "t"}}
graph.invoke({"messages": []}, config)
first, second = _hello_ids(graph, config)
assert first, "the message should get a UUID"
assert first == second, "its id must be the same on every read"
def test_add_messages_keeps_an_empty_id() -> None:
graph = _build_graph(
InMemorySaver(),
channel=add_messages,
write=lambda: [HumanMessage("hello", id="")],
)
config = {"configurable": {"thread_id": "t"}}
graph.invoke({"messages": []}, config)
assert _hello_ids(graph, config) == ["", ""]
def _hello_write_id(checkpointer: BaseCheckpointSaver, config: dict) -> str | None:
for saved in checkpointer.list(config):
for _, channel, value in saved.pending_writes or []:
if channel != "messages":
continue
for m in value if isinstance(value, list) else [value]:
content = m.get("content") if isinstance(m, dict) else m.content
if content == "hello":
return _id(m)
raise AssertionError("no saved write holds the message")
@pytest.mark.parametrize(
"write",
[
pytest.param(lambda: Overwrite(["hello"]), id="Overwrite"),
pytest.param(lambda: {"__overwrite__": ["hello"]}, id="__overwrite__ dict"),
pytest.param(
lambda: {"type": "__overwrite__", "value": ["hello"]},
id="serialized Overwrite",
),
],
)
def test_an_overwrite_streams_in_the_form_it_was_written(write: Any) -> None:
graph = _build_graph(InMemorySaver(), channel=add_messages, write=write)
config = {"configurable": {"thread_id": "t"}}
(update,) = graph.stream({"messages": []}, config, stream_mode="updates")
streamed, written = update["agent"]["messages"], write()
assert type(streamed) is type(written)
if isinstance(written, dict):
assert streamed.keys() == written.keys()
@pytest.mark.parametrize("channel", MESSAGES_CHANNELS)
def test_a_resumed_step_applies_the_message_id_it_saved(
channel: Any, sync_checkpointer: BaseCheckpointSaver
) -> None:
State = TypedDict("State", {"messages": Annotated[list, channel()]}) # noqa: UP013
def ask(state: dict) -> dict:
interrupt("continue?")
return {}
graph = (
StateGraph(State)
.add_node("write", lambda state: {"messages": [("user", "hello")]})
.add_node("ask", ask)
.add_edge(START, "write")
.add_edge(START, "ask")
.compile(checkpointer=sync_checkpointer)
)
config = {"configurable": {"thread_id": "t"}}
graph.invoke({"messages": []}, config)
saved = _hello_write_id(sync_checkpointer, config)
graph.invoke(Command(resume=True), config)
assert saved, "the write saved at the interrupt should carry an id"
assert _hello_ids(graph, config) == [saved, saved]
@pytest.mark.parametrize("channel", MESSAGES_CHANNELS)
def test_a_command_update_applies_the_message_id_it_saved(
channel: Any, sync_checkpointer: BaseCheckpointSaver
) -> None:
graph = _build_graph(sync_checkpointer, channel=channel(), write=lambda: [])
config = {"configurable": {"thread_id": "t"}}
graph.invoke({"messages": [HumanMessage("a", id="a")]}, config)
graph.invoke(
Command(update={"messages": [{"role": "user", "content": "hello"}]}), config
)
saved = _hello_write_id(sync_checkpointer, config)
assert saved, "the saved write should carry an id"
assert _hello_ids(graph, config) == [saved, saved]
@pytest.mark.parametrize("channel", MESSAGES_CHANNELS)
def test_update_state_applies_the_message_id_it_saved(
channel: Any, sync_checkpointer: BaseCheckpointSaver
) -> None:
graph = _build_graph(sync_checkpointer, channel=channel(), write=lambda: [])
config = {"configurable": {"thread_id": "t"}}
graph.invoke({"messages": [HumanMessage("a", id="a")]}, config)
updated = graph.update_state(
config, {"messages": [{"role": "user", "content": "hello"}]}
)
saved = _hello_write_id(sync_checkpointer, config)
assert saved, "the saved write should carry an id"
assert _hello_ids(graph, updated) == [saved, saved]
async def _ahello_ids(graph: Any, config: dict) -> list[str | None]:
return [
next(
_id(m)
for m in (await graph.aget_state(config)).values["messages"]
if (m.get("content") if isinstance(m, dict) else m.content) == "hello"
)
for _ in range(2)
]
@pytest.mark.parametrize("channel", MESSAGES_CHANNELS)
async def test_an_async_run_keeps_the_message_ids_it_saves(
channel: Any, async_checkpointer: BaseCheckpointSaver
) -> None:
graph = _build_graph(
async_checkpointer,
channel=channel(),
write=lambda: [{"role": "assistant", "content": "reply"}],
)
config = {"configurable": {"thread_id": "t"}}
updates = [
c
async for c in graph.astream(
{"messages": [{"role": "user", "content": "hello"}]},
config,
stream_mode="updates",
)
]
(streamed,) = updates[-1]["agent"]["messages"]
state = (await graph.aget_state(config)).values["messages"]
assert [_id(m) for m in state][-1] == _id(streamed), "updates show the saved id"
first, second = await _ahello_ids(graph, config)
assert first and first == second
oldest = [
s async for s in graph.aget_state_history(config) if "source" in s.metadata
][-1]
await graph.ainvoke(None, oldest.config)
assert await _ahello_ids(graph, config) == [first, first], "replay keeps it"
updated = await graph.aupdate_state(
config, {"messages": [{"role": "user", "content": "hello again"}]}
)
again = [
_id(m)
for m in (await graph.aget_state(updated)).values["messages"]
if (m.get("content") if isinstance(m, dict) else m.content) == "hello again"
]
assert again and again[0], "aupdate_state gives the message an id"
+7 -1
View File
@@ -6614,7 +6614,13 @@ def test_weather_subgraph(
(AnyStr("weather_graph:"),),
{
"weather_node": {
"messages": [{"role": "assistant", "content": "I'ts sunny in la!"}]
"messages": [
{
"role": "assistant",
"content": "I'ts sunny in la!",
"id": AnyStr(),
}
]
}
},
),
@@ -3727,7 +3727,13 @@ async def test_weather_subgraph(
(AnyStr("weather_graph:"),),
{
"weather_node": {
"messages": [{"role": "assistant", "content": "I'ts sunny in la!"}]
"messages": [
{
"role": "assistant",
"content": "I'ts sunny in la!",
"id": AnyStr(),
}
]
}
},
),
@@ -53,6 +53,8 @@ from langgraph.types import (
TaskPayload,
TaskResultPayload,
TasksStreamPart,
ToolsPayload,
ToolsStreamPart,
UpdatesStreamPart,
ValuesStreamPart,
interrupt,
@@ -1192,6 +1194,9 @@ def _check_type_narrowing(part: StreamPart[_StateT, _OutputT]) -> None:
elif part["type"] == "debug":
assert_type(part, DebugStreamPart[_StateT])
assert_type(part["data"], DebugPayload[_StateT])
elif part["type"] == "tools":
assert_type(part, ToolsStreamPart)
assert_type(part["data"], ToolsPayload)
assert_type(part["ns"], tuple[str, ...])
@@ -8,7 +8,10 @@ through `Pregel.stream(stream_mode=["tools", ...])` and inspect the raw
from __future__ import annotations
from typing import Annotated, Any
import asyncio
import contextlib
import threading
from typing import Annotated, Any, get_args, get_type_hints
import pytest
from langchain_core.messages import AIMessage
@@ -23,7 +26,14 @@ from langgraph.graph import StateGraph
from langgraph.graph.message import add_messages
from langgraph.pregel._tools import _tool_call_writer
from langgraph.runtime import RunControl
from langgraph.types import Command, interrupt
from langgraph.types import (
Command,
StreamMode,
StreamPart,
ToolsPayload,
ToolsStreamPart,
interrupt,
)
class _State(TypedDict):
@@ -150,6 +160,45 @@ class TestSyncGraphSyncTool:
assert kinds == ["tool-started", "tool-error"]
assert events[1][1]["message"] == "nope"
def test_v2_parts_have_the_declared_keys(self) -> None:
@tool
def flaky(text: str, runtime: ToolRuntime) -> str:
"""stream a chunk, then fail on "bad"."""
runtime.emit_output_delta(text)
if text == "bad":
raise ValueError("nope")
return text
parts: list[StreamPart] = []
for text in ("ok", "bad"):
graph = _build_graph(_caller_sync("flaky", {"text": text}), [flaky])
with contextlib.suppress(ValueError):
parts.extend(
graph.stream({"messages": []}, stream_mode="tools", version="v2")
)
assert [part["data"]["event"] for part in parts] == [
"tool-started",
"tool-output-delta",
"tool-finished",
"tool-started",
"tool-output-delta",
"tool-error",
]
assert "tools" in get_args(StreamMode)
assert ToolsStreamPart in get_args(StreamPart.__value__)
declared = {
get_args(get_type_hints(payload)["event"])[0]: payload
for payload in get_args(ToolsPayload)
}
for part in parts:
assert part["type"] == "tools"
assert part.keys() == ToolsStreamPart.__annotations__.keys()
payload = part["data"]
assert (
payload.keys() == declared[payload["event"]].__annotations__.keys()
), f"{payload['event']} payload keys differ from its declared type"
def test_interrupt_in_tool_is_not_a_tool_error(self) -> None:
@tool
def ask() -> str:
@@ -319,6 +368,54 @@ class TestAsyncGraphAsyncTool:
assert events == ["tool-started", "tool-started", "tool-finished"]
class TestToolsModeAloneStreamsLive:
def test_sync_delta_arrives_before_tool_returns(self) -> None:
delta_received = threading.Event()
order: list[str] = []
@tool
def slow(runtime: ToolRuntime) -> str:
"""emits, then waits for the consumer."""
runtime.emit_output_delta("partial")
delta_received.wait(timeout=5)
order.append("tool returned")
return "done"
graph = _build_graph(_caller_sync("slow", {}), [slow])
for payload in graph.stream({"messages": []}, stream_mode="tools"):
if payload["event"] == "tool-output-delta":
order.append("delta received")
delta_received.set()
assert order == ["delta received", "tool returned"], (
"the delta reached the consumer only after the tool returned"
)
@pytest.mark.anyio
async def test_async_delta_arrives_before_tool_returns(self) -> None:
delta_received = asyncio.Event()
order: list[str] = []
@tool
async def aslow(runtime: ToolRuntime) -> str:
"""emits, then waits for the consumer."""
runtime.emit_output_delta("partial")
with contextlib.suppress(asyncio.TimeoutError):
await asyncio.wait_for(delta_received.wait(), timeout=5)
order.append("tool returned")
return "done"
graph = _build_graph(_caller_async("aslow", {}), [aslow])
async for payload in graph.astream({"messages": []}, stream_mode="tools"):
if payload["event"] == "tool-output-delta":
order.append("delta received")
delta_received.set()
assert order == ["delta received", "tool returned"], (
"the delta reached the consumer only after the tool returned"
)
class TestConcurrentToolCalls:
def test_parallel_tool_calls_do_not_bleed(self) -> None:
@tool