mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-11-26 07:41:03 +01:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e3dbd42c5 | ||
|
|
ad48a3597d | ||
|
|
f96105368f | ||
|
|
732da52047 | ||
|
|
58d4a1c8d7 | ||
|
|
b4fe40f810 |
No files matched your search
@@ -1 +1 @@
|
||||
__version__ = "0.4.43"
|
||||
__version__ = "0.4.44"
|
||||
@@ -151,10 +151,7 @@ OPT_API_VERSION = click.option(
|
||||
type=str,
|
||||
help=(
|
||||
"Agent Server version to use for the base image. If unspecified, the "
|
||||
"latest stable version will be used. Exact versions like 0.18.3 are used "
|
||||
"as-is. A bare minor like 0.18 (or major like 0) resolves to the newest "
|
||||
"stable release in that line on PyPI, for example 0.18.4. Compatible "
|
||||
"ranges like "
|
||||
"latest stable version will be used. Compatible ranges like "
|
||||
"~=0.11.0.dev5 stay on 0.11.0.dev5 while only newer dev builds exist, "
|
||||
"then resolve to the newest matching rc or stable release, for example "
|
||||
"0.11.0rc1 or 0.11.0. Stable-floating ranges like >~=0.11.0.dev5 "
|
||||
|
||||
@@ -54,16 +54,6 @@ _API_VERSION_PART_PATTERN = re.compile(
|
||||
r"(?:\.(?P<patch>\d+))?"
|
||||
r"(?:(?:\.|)(?P<pre>dev|rc)(?P<pre_n>\d+))?$"
|
||||
)
|
||||
_DEFAULT_API_BASE_IMAGES = frozenset(
|
||||
{
|
||||
"langchain/langgraph-api",
|
||||
"langchain/langgraphjs-api",
|
||||
"langchain/langgraph-executor",
|
||||
}
|
||||
)
|
||||
_PIN_EXACT_API_VERSION_HINT = (
|
||||
'Pin an exact api_version instead, e.g.:\n "api_version": "0.18.3"'
|
||||
)
|
||||
|
||||
|
||||
class _ParsedApiVersion(NamedTuple):
|
||||
@@ -298,7 +288,7 @@ def _ensure_compatible_api_version_base_image(base_image: str) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _get_pypi_versions(package_name: str, *, exclude_yanked: bool = False) -> list[str]:
|
||||
def _get_pypi_versions(package_name: str) -> list[str]:
|
||||
try:
|
||||
response = httpx.get(
|
||||
f"https://pypi.org/pypi/{package_name}/json",
|
||||
@@ -315,65 +305,7 @@ def _get_pypi_versions(package_name: str, *, exclude_yanked: bool = False) -> li
|
||||
raise click.UsageError(
|
||||
f"Failed to fetch PyPI versions for {package_name}: invalid response."
|
||||
)
|
||||
return [
|
||||
version
|
||||
for version, files in releases.items()
|
||||
if isinstance(version, str)
|
||||
and (
|
||||
not exclude_yanked
|
||||
or (
|
||||
isinstance(files, list)
|
||||
and any(
|
||||
isinstance(file, dict) and not file.get("yanked") for file in files
|
||||
)
|
||||
)
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def _resolve_api_version_line(
|
||||
api_version: str,
|
||||
base_image: str,
|
||||
version_distro_tag: str,
|
||||
) -> str:
|
||||
"""Resolve a bare major or minor api_version to its newest final release."""
|
||||
if base_image not in _DEFAULT_API_BASE_IMAGES:
|
||||
return api_version
|
||||
try:
|
||||
line = _parse_api_version(api_version)
|
||||
except ValueError:
|
||||
return api_version
|
||||
if line.prerelease is not None or len(line.release) > 2:
|
||||
return api_version
|
||||
|
||||
try:
|
||||
pypi_versions = _get_pypi_versions("langgraph-api", exclude_yanked=True)
|
||||
except click.UsageError as exc:
|
||||
raise click.UsageError(
|
||||
f"Could not resolve api_version {api_version!r} to a release: "
|
||||
f"{exc.message}\n\n{_PIN_EXACT_API_VERSION_HINT}"
|
||||
) from None
|
||||
|
||||
candidates: list[tuple[_ParsedApiVersion, str]] = []
|
||||
for candidate_str in pypi_versions:
|
||||
try:
|
||||
candidate = _parse_api_version(candidate_str)
|
||||
except ValueError:
|
||||
continue
|
||||
if (
|
||||
candidate.prerelease is None
|
||||
and candidate.release[: len(line.release)] == line.release
|
||||
):
|
||||
candidates.append((candidate, candidate_str))
|
||||
|
||||
if not candidates:
|
||||
raise click.UsageError(
|
||||
f"No final PyPI releases match api_version {api_version!r} "
|
||||
f"for {base_image} with {version_distro_tag!r}.\n\n"
|
||||
f"{_PIN_EXACT_API_VERSION_HINT}"
|
||||
)
|
||||
|
||||
return max(candidates, key=lambda item: _api_version_sort_key(item[0]))[1]
|
||||
return [version for version in releases if isinstance(version, str)]
|
||||
|
||||
|
||||
def _resolve_compatible_api_version(
|
||||
@@ -383,7 +315,7 @@ def _resolve_compatible_api_version(
|
||||
) -> str:
|
||||
match = _API_VERSION_RANGE_PATTERN.fullmatch(api_version)
|
||||
if not match:
|
||||
return _resolve_api_version_line(api_version, base_image, version_distro_tag)
|
||||
return api_version
|
||||
|
||||
floor_str = match.group("version").strip()
|
||||
try:
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -649,9 +649,7 @@ class Config(TypedDict, total=False):
|
||||
api_version: str | None
|
||||
"""Optional. Which semantic version of the Agent Server to use.
|
||||
|
||||
Defaults to latest. Exact versions like `"0.18.3"` are used as-is. A bare
|
||||
minor like `"0.18"` (or major like `"0"`) resolves to the newest stable
|
||||
release in that line on PyPI when using the default base images. Check the
|
||||
Defaults to latest. Check the
|
||||
[changelog](https://docs.langchain.com/langgraph-platform/langgraph-server-changelog)
|
||||
for more information."""
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional. Which semantic version of the Agent Server to use.\n\nDefaults to latest. Exact versions like `\"0.18.3\"` are used as-is. A bare\nminor like `\"0.18\"` (or major like `\"0\"`) resolves to the newest stable\nrelease in that line on PyPI when using the default base images. Check the\nfor more information.\n"
|
||||
"description": "Optional. Which semantic version of the Agent Server to use.\n\nDefaults to latest. Check the\nfor more information.\n"
|
||||
},
|
||||
"auth": {
|
||||
"anyOf": [
|
||||
@@ -303,7 +303,7 @@
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional. Which semantic version of the Agent Server to use.\n\nDefaults to latest. Exact versions like `\"0.18.3\"` are used as-is. A bare\nminor like `\"0.18\"` (or major like `\"0\"`) resolves to the newest stable\nrelease in that line on PyPI when using the default base images. Check the\nfor more information.\n"
|
||||
"description": "Optional. Which semantic version of the Agent Server to use.\n\nDefaults to latest. Check the\nfor more information.\n"
|
||||
},
|
||||
"auth": {
|
||||
"anyOf": [
|
||||
@@ -542,7 +542,7 @@
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional. Which semantic version of the Agent Server to use.\n\nDefaults to latest. Exact versions like `\"0.18.3\"` are used as-is. A bare\nminor like `\"0.18\"` (or major like `\"0\"`) resolves to the newest stable\nrelease in that line on PyPI when using the default base images. Check the\nfor more information.\n"
|
||||
"description": "Optional. Which semantic version of the Agent Server to use.\n\nDefaults to latest. Check the\nfor more information.\n"
|
||||
},
|
||||
"auth": {
|
||||
"anyOf": [
|
||||
|
||||
@@ -50,7 +50,7 @@
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional. Which semantic version of the Agent Server to use.\n\nDefaults to latest. Exact versions like `\"0.18.3\"` are used as-is. A bare\nminor like `\"0.18\"` (or major like `\"0\"`) resolves to the newest stable\nrelease in that line on PyPI when using the default base images. Check the\nfor more information.\n"
|
||||
"description": "Optional. Which semantic version of the Agent Server to use.\n\nDefaults to latest. Check the\nfor more information.\n"
|
||||
},
|
||||
"auth": {
|
||||
"anyOf": [
|
||||
@@ -303,7 +303,7 @@
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional. Which semantic version of the Agent Server to use.\n\nDefaults to latest. Exact versions like `\"0.18.3\"` are used as-is. A bare\nminor like `\"0.18\"` (or major like `\"0\"`) resolves to the newest stable\nrelease in that line on PyPI when using the default base images. Check the\nfor more information.\n"
|
||||
"description": "Optional. Which semantic version of the Agent Server to use.\n\nDefaults to latest. Check the\nfor more information.\n"
|
||||
},
|
||||
"auth": {
|
||||
"anyOf": [
|
||||
@@ -542,7 +542,7 @@
|
||||
"type": "null"
|
||||
}
|
||||
],
|
||||
"description": "Optional. Which semantic version of the Agent Server to use.\n\nDefaults to latest. Exact versions like `\"0.18.3\"` are used as-is. A bare\nminor like `\"0.18\"` (or major like `\"0\"`) resolves to the newest stable\nrelease in that line on PyPI when using the default base images. Check the\nfor more information.\n"
|
||||
"description": "Optional. Which semantic version of the Agent Server to use.\n\nDefaults to latest. Check the\nfor more information.\n"
|
||||
},
|
||||
"auth": {
|
||||
"anyOf": [
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -7,13 +7,11 @@ import textwrap
|
||||
from unittest.mock import patch
|
||||
|
||||
import click
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from langgraph_cli.config import (
|
||||
_BUILD_TOOLS,
|
||||
_get_pip_cleanup_lines,
|
||||
_get_pypi_versions,
|
||||
config_to_compose,
|
||||
config_to_docker,
|
||||
default_base_image,
|
||||
@@ -3508,184 +3506,6 @@ def test_docker_tag_with_compatible_api_version_rejects_tagged_base_image():
|
||||
docker_tag(config, base_image="langchain/langgraph-api:0.11.0")
|
||||
|
||||
|
||||
_API_LINE_PYPI_VERSIONS = [
|
||||
"0.17.9",
|
||||
"0.18.0.dev1",
|
||||
"0.18.0rc1",
|
||||
"0.18.0",
|
||||
"0.18.2",
|
||||
"0.18.10",
|
||||
"0.18.11rc1",
|
||||
"0.19.0.dev1",
|
||||
"0.19.0rc2",
|
||||
"1.0.0rc1",
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("api_version", "expected"),
|
||||
[("0.18", "0.18.10"), ("0", "0.18.10"), ("0.17", "0.17.9")],
|
||||
)
|
||||
def test_docker_tag_resolves_api_version_line_to_latest_final_release(
|
||||
api_version: str, expected: str
|
||||
):
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"dependencies": ["."],
|
||||
"graphs": {"agent": "./agent.py:graph"},
|
||||
"api_version": api_version,
|
||||
}
|
||||
)
|
||||
|
||||
with patch(
|
||||
"langgraph_cli.config._get_pypi_versions",
|
||||
return_value=_API_LINE_PYPI_VERSIONS,
|
||||
) as get_versions:
|
||||
tag = docker_tag(config)
|
||||
|
||||
get_versions.assert_called_once_with("langgraph-api", exclude_yanked=True)
|
||||
assert tag == f"langchain/langgraph-api:{expected}-py3.11"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("config_extra", "base_image", "expected_prefix"),
|
||||
[
|
||||
(
|
||||
{"node_version": "20", "graphs": {"agent": "./agent.js:graph"}},
|
||||
None,
|
||||
"langchain/langgraphjs-api:0.18.10-node20",
|
||||
),
|
||||
(
|
||||
{"python_version": "3.12", "image_distro": "wolfi"},
|
||||
"langchain/langgraph-executor",
|
||||
"langchain/langgraph-executor:0.18.10-py3.12-wolfi",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_docker_tag_resolves_api_version_line_for_default_images(
|
||||
config_extra: dict, base_image: str | None, expected_prefix: str
|
||||
):
|
||||
config = validate_config(
|
||||
{
|
||||
"dependencies": ["."],
|
||||
"graphs": {"agent": "./agent.py:graph"},
|
||||
"api_version": "0.18",
|
||||
**config_extra,
|
||||
}
|
||||
)
|
||||
|
||||
with patch(
|
||||
"langgraph_cli.config._get_pypi_versions",
|
||||
return_value=_API_LINE_PYPI_VERSIONS,
|
||||
):
|
||||
tag = docker_tag(config, base_image=base_image)
|
||||
|
||||
assert tag == expected_prefix
|
||||
|
||||
|
||||
@pytest.mark.parametrize("api_version", ["0.18.3", "0.19.0rc2", "0.19.0.dev1"])
|
||||
def test_docker_tag_uses_exact_and_prerelease_api_version_verbatim(api_version: str):
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"dependencies": ["."],
|
||||
"graphs": {"agent": "./agent.py:graph"},
|
||||
"api_version": api_version,
|
||||
}
|
||||
)
|
||||
|
||||
with patch("langgraph_cli.config._get_pypi_versions") as get_versions:
|
||||
tag = docker_tag(config)
|
||||
|
||||
get_versions.assert_not_called()
|
||||
assert tag == f"langchain/langgraph-api:{api_version}-py3.11"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"base_image", ["my-registry/langgraph-api", "langchain/langgraph-server"]
|
||||
)
|
||||
def test_docker_tag_keeps_api_version_line_verbatim_for_custom_base_image(
|
||||
base_image: str,
|
||||
):
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"dependencies": ["."],
|
||||
"graphs": {"agent": "./agent.py:graph"},
|
||||
"api_version": "0.18",
|
||||
}
|
||||
)
|
||||
|
||||
with patch("langgraph_cli.config._get_pypi_versions") as get_versions:
|
||||
tag = docker_tag(config, base_image=base_image)
|
||||
|
||||
get_versions.assert_not_called()
|
||||
assert tag == f"{base_image}:0.18-py3.11"
|
||||
|
||||
|
||||
def test_docker_tag_api_version_line_without_final_release_asks_for_exact_pin():
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"dependencies": ["."],
|
||||
"graphs": {"agent": "./agent.py:graph"},
|
||||
"api_version": "0.19",
|
||||
}
|
||||
)
|
||||
|
||||
with patch(
|
||||
"langgraph_cli.config._get_pypi_versions",
|
||||
return_value=_API_LINE_PYPI_VERSIONS,
|
||||
):
|
||||
with pytest.raises(click.UsageError, match="No final PyPI releases") as exc:
|
||||
docker_tag(config)
|
||||
|
||||
assert '"api_version": "0.18.3"' in exc.value.message
|
||||
|
||||
|
||||
def test_docker_tag_api_version_line_when_pypi_unreachable_asks_for_exact_pin():
|
||||
config = validate_config(
|
||||
{
|
||||
"python_version": "3.11",
|
||||
"dependencies": ["."],
|
||||
"graphs": {"agent": "./agent.py:graph"},
|
||||
"api_version": "0.18",
|
||||
}
|
||||
)
|
||||
|
||||
with patch(
|
||||
"langgraph_cli.config.httpx.get",
|
||||
side_effect=httpx.ConnectError("network unreachable"),
|
||||
):
|
||||
with pytest.raises(click.UsageError, match="Could not resolve") as exc:
|
||||
docker_tag(config)
|
||||
|
||||
assert "network unreachable" in exc.value.message
|
||||
assert '"api_version": "0.18.3"' in exc.value.message
|
||||
|
||||
|
||||
def test_get_pypi_versions_excludes_yanked_and_empty_releases():
|
||||
releases = {
|
||||
"0.18.0": [{"yanked": False}],
|
||||
"0.18.1": [{"yanked": True}, {"yanked": True}],
|
||||
"0.18.2": [{"yanked": True}, {"yanked": False}],
|
||||
"0.18.3": [],
|
||||
}
|
||||
response = httpx.Response(
|
||||
200,
|
||||
json={"releases": releases},
|
||||
request=httpx.Request("GET", "https://pypi.org/pypi/langgraph-api/json"),
|
||||
)
|
||||
|
||||
with patch("langgraph_cli.config.httpx.get", return_value=response):
|
||||
assert _get_pypi_versions("langgraph-api") == list(releases)
|
||||
assert _get_pypi_versions("langgraph-api", exclude_yanked=True) == [
|
||||
"0.18.0",
|
||||
"0.18.2",
|
||||
]
|
||||
|
||||
|
||||
def test_config_to_docker_with_api_version():
|
||||
"""Test config_to_docker function with api_version parameter."""
|
||||
|
||||
|
||||
@@ -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(":")
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 item.id is None:
|
||||
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)
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
@@ -178,22 +184,33 @@ MESSAGE_SHAPES = [
|
||||
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)
|
||||
]
|
||||
@@ -333,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"
|
||||
@@ -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
|
||||
|
||||
Reference in new issue
Block a user