mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-12-03 11:03:07 +01:00
Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8bad677b0a | ||
|
|
83888ec170 | ||
|
|
6a3005b545 | ||
|
|
1ddf3cc19c | ||
|
|
c8a9bdda08 | ||
|
|
3e3dbd42c5 | ||
|
|
ad48a3597d | ||
|
|
f96105368f | ||
|
|
732da52047 | ||
|
|
58d4a1c8d7 | ||
|
|
b4fe40f810 | ||
|
|
c6335a4255 | ||
|
|
01d7b9e17b | ||
|
|
58a6e1cc5b | ||
|
|
8aea1fea7f | ||
|
|
37becf152a | ||
|
|
7830b91a24 | ||
|
|
a03c71268e | ||
|
|
292106d223 |
No files matched your search
@@ -1 +1 @@
|
||||
__version__ = "0.4.43"
|
||||
__version__ = "0.4.45"
|
||||
@@ -290,6 +290,17 @@ class RequestedPlacement:
|
||||
return self.k8s_namespace
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StoredPlacement:
|
||||
listener_id: str | None
|
||||
k8s_namespace: str | None
|
||||
|
||||
def allows(self, requested: RequestedPlacement) -> bool:
|
||||
return requested.listener_id in (None, self.listener_id) and (
|
||||
requested.k8s_namespace in (None, self.k8s_namespace)
|
||||
)
|
||||
|
||||
|
||||
def _describe_listeners(listeners: Sequence[Listener]) -> str:
|
||||
shown = listeners[:_LISTENERS_SHOWN]
|
||||
lines = [
|
||||
@@ -306,6 +317,21 @@ def _describe_listeners(listeners: Sequence[Listener]) -> str:
|
||||
class ExistingDeployment:
|
||||
id: str
|
||||
source: str | None
|
||||
placement: StoredPlacement | None = None
|
||||
image_pull_secrets: frozenset[str] | None = None
|
||||
|
||||
@classmethod
|
||||
def from_resource(
|
||||
cls, deployment_id: str, resource: Mapping[str, object]
|
||||
) -> "ExistingDeployment":
|
||||
source_config = resource.get("source_config")
|
||||
stored = source_config if isinstance(source_config, Mapping) else {}
|
||||
return cls(
|
||||
deployment_id,
|
||||
_source_of(resource),
|
||||
_stored_placement(stored),
|
||||
_stored_image_pull_secrets(stored),
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -517,12 +543,47 @@ def _source_of(resource: object) -> str | None:
|
||||
return source if isinstance(source, str) else None
|
||||
|
||||
|
||||
def _stored_placement(source_config: Mapping[str, object]) -> StoredPlacement | None:
|
||||
if "listener_id" not in source_config:
|
||||
return None
|
||||
listener_id = source_config["listener_id"]
|
||||
if listener_id is not None and not isinstance(listener_id, str):
|
||||
return None
|
||||
listener_config = source_config.get("listener_config")
|
||||
namespace = (
|
||||
listener_config.get("k8s_namespace")
|
||||
if isinstance(listener_config, Mapping)
|
||||
else None
|
||||
)
|
||||
return StoredPlacement(
|
||||
listener_id, namespace if isinstance(namespace, str) else None
|
||||
)
|
||||
|
||||
|
||||
def _stored_image_pull_secrets(
|
||||
source_config: Mapping[str, object],
|
||||
) -> frozenset[str] | None:
|
||||
if "resource_spec" not in source_config:
|
||||
return None
|
||||
resource_spec = source_config["resource_spec"] or {}
|
||||
if not isinstance(resource_spec, Mapping):
|
||||
return None
|
||||
entries = resource_spec.get("image_pull_secrets") or []
|
||||
if not isinstance(entries, list):
|
||||
return None
|
||||
return frozenset(
|
||||
entry["name"]
|
||||
for entry in entries
|
||||
if isinstance(entry, Mapping) and isinstance(entry.get("name"), str)
|
||||
)
|
||||
|
||||
|
||||
def find_deployment_by_name(
|
||||
client: HostBackendClient, name: str
|
||||
) -> ExistingDeployment | None:
|
||||
for resource in client.list_deployments(name=name, name_contains=name):
|
||||
if resource.get("name") == name and resource.get("id"):
|
||||
return ExistingDeployment(str(resource["id"]), _source_of(resource))
|
||||
return ExistingDeployment.from_resource(str(resource["id"]), resource)
|
||||
return None
|
||||
|
||||
|
||||
@@ -670,7 +731,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(
|
||||
@@ -829,7 +890,7 @@ def _fetch_deployment(
|
||||
resource = _call_host_backend_with_optional_tenant(
|
||||
client, lambda c: c.get_deployment(selector.deployment_id)
|
||||
)
|
||||
return ExistingDeployment(selector.deployment_id, _source_of(resource)), step + 1
|
||||
return ExistingDeployment.from_resource(selector.deployment_id, resource), step + 1
|
||||
|
||||
|
||||
def _find_deployment(
|
||||
@@ -858,7 +919,7 @@ def _find_deployment(
|
||||
)
|
||||
found = next(
|
||||
(
|
||||
ExistingDeployment(str(dep["id"]), _source_of(dep))
|
||||
ExistingDeployment.from_resource(str(dep["id"]), dep)
|
||||
for dep in existing
|
||||
if dep.get("id") and not dep.get("is_preview")
|
||||
),
|
||||
@@ -1773,11 +1834,39 @@ _K8S_SECRET_NAME_RE = re.compile(
|
||||
)
|
||||
|
||||
|
||||
def _placement_refusal(stored: StoredPlacement | None) -> str:
|
||||
if stored is None:
|
||||
return "already exists, so drop --listener-id and --k8s-namespace"
|
||||
if stored.listener_id is None:
|
||||
return (
|
||||
"was created without a listener, so drop --listener-id and --k8s-namespace"
|
||||
)
|
||||
if stored.k8s_namespace is None:
|
||||
return (
|
||||
f"runs on listener {stored.listener_id}, but its namespace was not "
|
||||
f"reported, so pass --listener-id {stored.listener_id} without "
|
||||
"--k8s-namespace, or drop both flags"
|
||||
)
|
||||
return (
|
||||
f"runs on listener {stored.listener_id} in namespace "
|
||||
f"{stored.k8s_namespace}, so pass those values or drop --listener-id "
|
||||
"and --k8s-namespace"
|
||||
)
|
||||
|
||||
|
||||
def _pull_secrets_refusal(stored: frozenset[str] | None) -> str:
|
||||
remedy = (
|
||||
"drop --image-pull-secret and update resource_spec through the API or "
|
||||
"the LangSmith UI instead"
|
||||
)
|
||||
if stored is None:
|
||||
return f"already exists, so {remedy}"
|
||||
held = ", ".join(sorted(stored)) or "no image pull secrets"
|
||||
return f"uses {held}, so pass the same secrets or {remedy}"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class CreateOnlySettings:
|
||||
"""Options for an external-image deployment that only apply when
|
||||
creating one, never when updating an existing deployment."""
|
||||
|
||||
placement: RequestedPlacement
|
||||
image_pull_secrets: tuple[str, ...] = ()
|
||||
|
||||
@@ -1801,21 +1890,26 @@ class CreateOnlySettings:
|
||||
"apply when creating an Agent Server with --push-to or --image-uri."
|
||||
)
|
||||
|
||||
def ensure_not_existing(self, deployment_id: str) -> None:
|
||||
if self.placement.requested:
|
||||
def ensure_unchanged(self, existing: ExistingDeployment) -> None:
|
||||
stored_placement = existing.placement
|
||||
if self.placement.requested and not (
|
||||
stored_placement is not None and stored_placement.allows(self.placement)
|
||||
):
|
||||
raise click.UsageError(
|
||||
"Listener and namespace are fixed when an Agent Server is "
|
||||
f"created. Agent Server {deployment_id} already exists, so "
|
||||
"drop --listener-id and --k8s-namespace, or create a new "
|
||||
"Agent Server with a different --name."
|
||||
f"created. Agent Server {existing.id} "
|
||||
f"{_placement_refusal(stored_placement)}, or create a new Agent "
|
||||
"Server with a different --name."
|
||||
)
|
||||
if self.image_pull_secrets:
|
||||
stored_secrets = existing.image_pull_secrets
|
||||
if self.image_pull_secrets and stored_secrets != frozenset(
|
||||
self.image_pull_secrets
|
||||
):
|
||||
raise click.UsageError(
|
||||
"langgraph deploy does not update image pull secrets on an "
|
||||
f"existing Agent Server. Agent Server {deployment_id} already "
|
||||
"exists, so drop --image-pull-secret and update resource_spec "
|
||||
"through the API or the LangSmith UI instead, or create a "
|
||||
"new Agent Server with a different --name."
|
||||
f"existing Agent Server. Agent Server {existing.id} "
|
||||
f"{_pull_secrets_refusal(stored_secrets)}, or create a new "
|
||||
"Agent Server with a different --name."
|
||||
)
|
||||
|
||||
|
||||
@@ -1844,7 +1938,7 @@ class CustomerRegistrySource:
|
||||
self, ctx: DeployContext, existing: ExistingDeployment, step: int
|
||||
) -> DeployOutcome:
|
||||
_ensure_customer_registry_source(existing)
|
||||
self.create_only.ensure_not_existing(existing.id)
|
||||
self.create_only.ensure_unchanged(existing)
|
||||
image_uri, step = self._publish(ctx, step)
|
||||
_log_deploy_step(step, f"Updating Agent Server {existing.id}")
|
||||
updated = ctx.client.update_deployment(
|
||||
@@ -1985,12 +2079,9 @@ def _select_source(
|
||||
remote_build_flag: bool | None,
|
||||
placement: RequestedPlacement,
|
||||
image_pull_secrets: tuple[str, ...],
|
||||
selector: DeploymentSelector,
|
||||
) -> DeploymentSource:
|
||||
create_only = CreateOnlySettings(placement, image_pull_secrets)
|
||||
create_only.ensure_creatable(push_to, image_uri)
|
||||
if create_only.requested and isinstance(selector, ById):
|
||||
create_only.ensure_not_existing(selector.deployment_id)
|
||||
if image_uri is not None:
|
||||
if push_to is not None:
|
||||
raise click.UsageError("--image-uri cannot be combined with --push-to.")
|
||||
@@ -2624,7 +2715,6 @@ def _deploy_cmd(
|
||||
remote_build_flag=remote_build_flag,
|
||||
placement=RequestedPlacement(listener_id, k8s_namespace),
|
||||
image_pull_secrets=image_pull_secrets,
|
||||
selector=selector,
|
||||
)
|
||||
|
||||
client = _create_host_backend_client(host_url, api_key, env_vars=env_vars)
|
||||
@@ -2728,7 +2818,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(
|
||||
|
||||
@@ -150,6 +150,10 @@ def _resources(payload: object) -> list[dict[str, Any]]:
|
||||
return [item for item in resources if isinstance(item, dict)]
|
||||
|
||||
|
||||
def _secrets_to_replace(secrets: list[dict[str, str]] | None) -> dict[str, Any]:
|
||||
return {"secrets": secrets} if secrets else {}
|
||||
|
||||
|
||||
class HostBackendError(click.ClickException):
|
||||
"""Raised when the host backend returns an error response."""
|
||||
|
||||
@@ -468,8 +472,7 @@ class HostBackendClient(_JsonClient):
|
||||
payload["revision_source"] = revision_source
|
||||
if tracked_packages:
|
||||
payload["tracked_packages"] = tracked_packages
|
||||
if secrets is not None:
|
||||
payload["secrets"] = secrets
|
||||
payload.update(_secrets_to_replace(secrets))
|
||||
return self._request("PATCH", f"/v2/deployments/{deployment_id}", payload)
|
||||
|
||||
def update_deployment_internal_source(
|
||||
@@ -501,8 +504,7 @@ class HostBackendClient(_JsonClient):
|
||||
if source_config:
|
||||
payload["source_config"] = source_config
|
||||
|
||||
if secrets is not None:
|
||||
payload["secrets"] = secrets
|
||||
payload.update(_secrets_to_replace(secrets))
|
||||
return self._request("PATCH", f"/v2/deployments/{deployment_id}", payload)
|
||||
|
||||
def list_revisions(
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -50,6 +50,11 @@ TWO_NAMESPACE_LISTENER = {
|
||||
"compute_id": "prod-cluster",
|
||||
"compute_config": {"k8s_namespaces": ["agents", "agents-staging"]},
|
||||
}
|
||||
STORED_SOURCE_CONFIG = {
|
||||
"listener_id": LISTENER_ID,
|
||||
"listener_config": {"k8s_namespace": "agents"},
|
||||
"resource_spec": {"image_pull_secrets": [{"name": "regcred"}]},
|
||||
}
|
||||
CREATED_ID = "dep-created"
|
||||
TRACKED_PACKAGES = ["langgraph:1.0.0"]
|
||||
SIGNED_UPLOAD_URL = "https://storage.example.com/signed"
|
||||
@@ -98,6 +103,15 @@ def _get(deployment_id: str) -> str:
|
||||
return f"GET /v2/deployments/{deployment_id}"
|
||||
|
||||
|
||||
def _external_deployment(source_config: dict) -> dict:
|
||||
return {
|
||||
"id": "dep-ext",
|
||||
"name": "my-app",
|
||||
"source": "external_docker",
|
||||
"source_config": source_config,
|
||||
}
|
||||
|
||||
|
||||
def _looks_like_a_uuid(value: str) -> bool:
|
||||
try:
|
||||
uuid.UUID(value)
|
||||
@@ -331,8 +345,14 @@ class DeployProject:
|
||||
timeline: list[str]
|
||||
uploads: list[tuple[str, str, int, dict[str, str] | None]]
|
||||
|
||||
def run(self, *args: str, host_url: str | None = CONTROL_PLANE_URL) -> Result:
|
||||
def run(
|
||||
self,
|
||||
*args: str,
|
||||
host_url: str | None = CONTROL_PLANE_URL,
|
||||
name: str | None = "my-app",
|
||||
) -> Result:
|
||||
host_args = ("--host-url", host_url) if host_url else ()
|
||||
name_args = ("--name", name) if name else ()
|
||||
return CliRunner().invoke(
|
||||
cli,
|
||||
[
|
||||
@@ -340,8 +360,7 @@ class DeployProject:
|
||||
"--api-key",
|
||||
"test-key",
|
||||
*host_args,
|
||||
"--name",
|
||||
"my-app",
|
||||
*name_args,
|
||||
"--no-input",
|
||||
"--no-wait",
|
||||
*args,
|
||||
@@ -731,7 +750,6 @@ def test_local_deploy_records_the_pushed_digest_and_tracked_packages(
|
||||
assert deploy_project.control_plane.bodies[_patch(CREATED_ID)] == {
|
||||
"revision_source": "internal_docker",
|
||||
"source_revision_config": {"image_uri": PUSHED_DIGEST},
|
||||
"secrets": [],
|
||||
"tracked_packages": TRACKED_PACKAGES,
|
||||
}
|
||||
|
||||
@@ -852,7 +870,6 @@ def test_remote_build_creates_an_internal_source_deployment_and_uploads_the_arch
|
||||
"langgraph_config_path": ARCHIVE[2],
|
||||
},
|
||||
"source_config": {"install_command": "yarn install"},
|
||||
"secrets": [],
|
||||
"tracked_packages": TRACKED_PACKAGES,
|
||||
}
|
||||
assert "Build triggered" in result.output
|
||||
@@ -962,7 +979,6 @@ def test_push_to_updates_an_existing_external_deployment_with_the_new_image(
|
||||
]
|
||||
assert deploy_project.control_plane.bodies[_patch("dep-ext")] == {
|
||||
"source_revision_config": {"image_uri": EXTERNAL_DIGEST},
|
||||
"secrets": [],
|
||||
"tracked_packages": TRACKED_PACKAGES,
|
||||
}
|
||||
|
||||
@@ -1030,7 +1046,6 @@ def test_image_uri_updates_an_existing_external_deployment_without_any_docker_wo
|
||||
assert deploy_project.timeline == [LIST_DEPLOYMENTS, _patch("dep-ext")]
|
||||
assert deploy_project.control_plane.bodies[_patch("dep-ext")] == {
|
||||
"source_revision_config": {"image_uri": EXTERNAL_DIGEST},
|
||||
"secrets": [],
|
||||
"tracked_packages": TRACKED_PACKAGES,
|
||||
}
|
||||
|
||||
@@ -1285,9 +1300,13 @@ def test_an_invalid_image_pull_secret_name_is_rejected_before_any_docker_work(
|
||||
assert deploy_project.timeline == []
|
||||
|
||||
|
||||
def test_image_pull_secret_cannot_update_an_existing_deployment(
|
||||
def test_image_pull_secret_is_refused_when_the_stored_secrets_are_unknown(
|
||||
deploy_project: DeployProject,
|
||||
) -> None:
|
||||
deploy_project.control_plane.existing_deployments = [
|
||||
{"id": "dep-1", "source": "external_docker"}
|
||||
]
|
||||
|
||||
result = deploy_project.run(
|
||||
"--deployment-id",
|
||||
"dep-1",
|
||||
@@ -1300,7 +1319,8 @@ def test_image_pull_secret_cannot_update_an_existing_deployment(
|
||||
assert result.exit_code != 0
|
||||
assert "--image-pull-secret" in result.output
|
||||
assert "dep-1" in result.output
|
||||
assert deploy_project.timeline == []
|
||||
assert deploy_project.docker.verbs() == []
|
||||
assert _patch("dep-1") not in deploy_project.timeline
|
||||
|
||||
|
||||
def test_image_pull_secret_cannot_update_a_deployment_found_by_name(
|
||||
@@ -1336,9 +1356,13 @@ def test_updating_a_deployment_never_looks_up_listeners(
|
||||
assert LIST_LISTENERS not in deploy_project.timeline
|
||||
|
||||
|
||||
def test_listener_flags_are_refused_for_a_deployment_id_without_any_call(
|
||||
def test_listener_flags_are_refused_for_a_deployment_id_with_an_unknown_placement(
|
||||
deploy_project: DeployProject,
|
||||
) -> None:
|
||||
deploy_project.control_plane.existing_deployments = [
|
||||
{"id": "dep-ext", "source": "external_docker"}
|
||||
]
|
||||
|
||||
result = deploy_project.run(
|
||||
"--push-to",
|
||||
PUSH_REPOSITORY,
|
||||
@@ -1351,7 +1375,8 @@ def test_listener_flags_are_refused_for_a_deployment_id_without_any_call(
|
||||
|
||||
assert result.exit_code != 0
|
||||
assert "fixed when an Agent Server is created" in result.output
|
||||
assert deploy_project.timeline == []
|
||||
assert deploy_project.docker.verbs() == []
|
||||
assert _patch("dep-ext") not in deploy_project.timeline
|
||||
|
||||
|
||||
def test_listener_flags_are_refused_on_an_existing_deployment(
|
||||
@@ -1375,6 +1400,198 @@ def test_listener_flags_are_refused_on_an_existing_deployment(
|
||||
assert deploy_project.docker.verbs() == []
|
||||
|
||||
|
||||
def test_create_only_flags_equal_to_the_stored_ones_update_the_agent_server(
|
||||
deploy_project: DeployProject,
|
||||
) -> None:
|
||||
deploy_project.control_plane.listeners = [LISTENER]
|
||||
deploy_project.control_plane.existing_deployments = [
|
||||
_external_deployment(STORED_SOURCE_CONFIG)
|
||||
]
|
||||
|
||||
result = deploy_project.run(
|
||||
"--push-to",
|
||||
PUSH_REPOSITORY,
|
||||
"--listener-id",
|
||||
LISTENER_ID,
|
||||
"--k8s-namespace",
|
||||
"agents",
|
||||
"--image-pull-secret",
|
||||
"regcred",
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert _patch("dep-ext") in deploy_project.timeline
|
||||
assert LIST_LISTENERS not in deploy_project.timeline
|
||||
assert f"GET /v2/listeners/{LISTENER_ID}" not in deploy_project.timeline
|
||||
|
||||
|
||||
def test_an_agent_bound_upgrade_accepts_the_stored_listener(
|
||||
deploy_project: DeployProject,
|
||||
) -> None:
|
||||
deploy_project.control_plane.existing_deployments = [
|
||||
_external_deployment(STORED_SOURCE_CONFIG)
|
||||
]
|
||||
|
||||
result = deploy_project.run(
|
||||
"--agent-id",
|
||||
"support-agent",
|
||||
"--agent-environment",
|
||||
"staging",
|
||||
"--image-uri",
|
||||
EXTERNAL_DIGEST,
|
||||
"--listener-id",
|
||||
LISTENER_ID,
|
||||
name=None,
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert _patch("dep-ext") in deploy_project.timeline
|
||||
|
||||
|
||||
def test_a_deployment_id_with_the_stored_flags_updates_the_agent_server(
|
||||
deploy_project: DeployProject,
|
||||
) -> None:
|
||||
deploy_project.control_plane.existing_deployments = [
|
||||
_external_deployment(STORED_SOURCE_CONFIG)
|
||||
]
|
||||
|
||||
result = deploy_project.run(
|
||||
"--deployment-id",
|
||||
"dep-ext",
|
||||
"--push-to",
|
||||
PUSH_REPOSITORY,
|
||||
"--listener-id",
|
||||
LISTENER_ID,
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert _patch("dep-ext") in deploy_project.timeline
|
||||
|
||||
|
||||
def test_a_namespace_alone_is_compared_only_with_the_stored_namespace(
|
||||
deploy_project: DeployProject,
|
||||
) -> None:
|
||||
deploy_project.control_plane.existing_deployments = [
|
||||
_external_deployment(STORED_SOURCE_CONFIG)
|
||||
]
|
||||
|
||||
result = deploy_project.run(
|
||||
"--push-to", PUSH_REPOSITORY, "--k8s-namespace", "agents"
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert _patch("dep-ext") in deploy_project.timeline
|
||||
|
||||
|
||||
def test_image_pull_secrets_match_the_stored_ones_in_any_order(
|
||||
deploy_project: DeployProject,
|
||||
) -> None:
|
||||
deploy_project.control_plane.existing_deployments = [
|
||||
_external_deployment(
|
||||
{
|
||||
"resource_spec": {
|
||||
"image_pull_secrets": [{"name": "b-cred"}, {"name": "a-cred"}]
|
||||
}
|
||||
}
|
||||
)
|
||||
]
|
||||
|
||||
result = deploy_project.run(
|
||||
"--push-to",
|
||||
PUSH_REPOSITORY,
|
||||
"--image-pull-secret",
|
||||
"a-cred",
|
||||
"--image-pull-secret",
|
||||
"b-cred",
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert _patch("dep-ext") in deploy_project.timeline
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("flag", "value", "stored"),
|
||||
[
|
||||
pytest.param(
|
||||
"--listener-id", OTHER_LISTENER_ID, LISTENER_ID, id="other_listener"
|
||||
),
|
||||
pytest.param(
|
||||
"--k8s-namespace", "agents-staging", "agents", id="other_namespace"
|
||||
),
|
||||
pytest.param(
|
||||
"--image-pull-secret", "other-cred", "regcred", id="other_pull_secret"
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_a_create_only_flag_that_differs_from_the_stored_value_is_refused(
|
||||
deploy_project: DeployProject, flag: str, value: str, stored: str
|
||||
) -> None:
|
||||
deploy_project.control_plane.existing_deployments = [
|
||||
_external_deployment(STORED_SOURCE_CONFIG)
|
||||
]
|
||||
|
||||
result = deploy_project.run("--push-to", PUSH_REPOSITORY, flag, value)
|
||||
|
||||
assert result.exit_code != 0
|
||||
assert stored in result.output
|
||||
assert deploy_project.docker.verbs() == []
|
||||
assert _patch("dep-ext") not in deploy_project.timeline
|
||||
|
||||
|
||||
def test_a_listener_for_an_agent_server_created_without_one_is_refused(
|
||||
deploy_project: DeployProject,
|
||||
) -> None:
|
||||
deploy_project.control_plane.existing_deployments = [
|
||||
_external_deployment({"listener_id": None, "listener_config": None})
|
||||
]
|
||||
|
||||
result = deploy_project.run(
|
||||
"--push-to", PUSH_REPOSITORY, "--listener-id", LISTENER_ID
|
||||
)
|
||||
|
||||
assert result.exit_code != 0
|
||||
assert "created without a listener" in result.output
|
||||
assert _patch("dep-ext") not in deploy_project.timeline
|
||||
|
||||
|
||||
def test_a_namespace_for_an_agent_server_without_a_reported_one_is_refused(
|
||||
deploy_project: DeployProject,
|
||||
) -> None:
|
||||
deploy_project.control_plane.existing_deployments = [
|
||||
_external_deployment({"listener_id": LISTENER_ID, "listener_config": {}})
|
||||
]
|
||||
|
||||
result = deploy_project.run(
|
||||
"--push-to",
|
||||
PUSH_REPOSITORY,
|
||||
"--listener-id",
|
||||
LISTENER_ID,
|
||||
"--k8s-namespace",
|
||||
"agents",
|
||||
)
|
||||
|
||||
assert result.exit_code != 0
|
||||
assert "namespace was not reported" in result.output
|
||||
assert "namespace None" not in result.output
|
||||
assert _patch("dep-ext") not in deploy_project.timeline
|
||||
|
||||
|
||||
def test_a_known_listener_alone_updates_an_agent_server_without_a_reported_namespace(
|
||||
deploy_project: DeployProject,
|
||||
) -> None:
|
||||
deploy_project.control_plane.listeners = [LISTENER]
|
||||
deploy_project.control_plane.existing_deployments = [
|
||||
_external_deployment({"listener_id": LISTENER_ID, "listener_config": {}})
|
||||
]
|
||||
|
||||
result = deploy_project.run(
|
||||
"--push-to", PUSH_REPOSITORY, "--listener-id", LISTENER_ID
|
||||
)
|
||||
|
||||
assert result.exit_code == 0, result.output
|
||||
assert _patch("dep-ext") in deploy_project.timeline
|
||||
|
||||
|
||||
def test_a_deployment_without_a_listener_announces_nothing(
|
||||
deploy_project: DeployProject,
|
||||
) -> None:
|
||||
|
||||
@@ -14,8 +14,6 @@ import pytest
|
||||
import langgraph_cli.deploy as deploy_mod
|
||||
from langgraph_cli.deploy import (
|
||||
BuildAndPush,
|
||||
ById,
|
||||
ByName,
|
||||
CreateOnlySettings,
|
||||
CustomerRegistrySource,
|
||||
DockerBuildCommand,
|
||||
@@ -27,6 +25,7 @@ from langgraph_cli.deploy import (
|
||||
PublishedImage,
|
||||
RemoteBuildSource,
|
||||
RequestedPlacement,
|
||||
StoredPlacement,
|
||||
Unplaced,
|
||||
_call_host_backend_with_optional_tenant,
|
||||
_create_host_backend_client,
|
||||
@@ -816,7 +815,6 @@ class TestSelectSource:
|
||||
"remote_build_flag": None,
|
||||
"placement": RequestedPlacement(),
|
||||
"image_pull_secrets": (),
|
||||
"selector": ByName("my-app"),
|
||||
}
|
||||
REPOSITORY = "registry.example.com/app"
|
||||
|
||||
@@ -1466,48 +1464,125 @@ def test_a_listener_without_an_id_is_refused(resource):
|
||||
Listener.from_resource(resource)
|
||||
|
||||
|
||||
def test_a_deployment_id_with_listener_flags_is_refused_without_probing_docker(
|
||||
monkeypatch,
|
||||
):
|
||||
def explode() -> tuple[bool, str | None]:
|
||||
raise AssertionError("docker must not be probed for an argv-only conflict")
|
||||
class TestExistingDeploymentFromResource:
|
||||
@pytest.mark.parametrize(
|
||||
("source_config", "placement", "image_pull_secrets"),
|
||||
[
|
||||
pytest.param(None, None, None, id="not_reported"),
|
||||
pytest.param({}, None, None, id="empty_source_config"),
|
||||
pytest.param(
|
||||
{
|
||||
"listener_id": "listener-1",
|
||||
"listener_config": {"k8s_namespace": "a"},
|
||||
},
|
||||
StoredPlacement("listener-1", "a"),
|
||||
None,
|
||||
id="listener_and_namespace",
|
||||
),
|
||||
pytest.param(
|
||||
{"listener_id": "listener-1", "listener_config": {}},
|
||||
StoredPlacement("listener-1", None),
|
||||
None,
|
||||
id="listener_without_a_reported_namespace",
|
||||
),
|
||||
pytest.param(
|
||||
{"listener_id": None, "listener_config": None},
|
||||
StoredPlacement(None, None),
|
||||
None,
|
||||
id="created_without_a_listener",
|
||||
),
|
||||
pytest.param({"listener_id": 1}, None, None, id="malformed_listener_id"),
|
||||
pytest.param(
|
||||
{"resource_spec": None}, None, frozenset(), id="no_resource_spec"
|
||||
),
|
||||
pytest.param(
|
||||
{"resource_spec": {"image_pull_secrets": None}},
|
||||
None,
|
||||
frozenset(),
|
||||
id="no_image_pull_secrets",
|
||||
),
|
||||
pytest.param(
|
||||
{
|
||||
"resource_spec": {
|
||||
"image_pull_secrets": [{"name": "b"}, {"name": "a"}]
|
||||
}
|
||||
},
|
||||
None,
|
||||
frozenset({"a", "b"}),
|
||||
id="image_pull_secrets",
|
||||
),
|
||||
pytest.param(
|
||||
{"resource_spec": "unexpected"},
|
||||
None,
|
||||
None,
|
||||
id="malformed_resource_spec",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_the_stored_create_only_values_are_read_or_left_unknown(
|
||||
self, source_config, placement, image_pull_secrets
|
||||
):
|
||||
resource = {"id": "dep-1", "source": "external_docker"}
|
||||
if source_config is not None:
|
||||
resource["source_config"] = source_config
|
||||
|
||||
monkeypatch.setattr(deploy_mod, "can_build_locally", explode)
|
||||
|
||||
with pytest.raises(click.UsageError, match="dep-1"):
|
||||
_select_source(
|
||||
push_to="registry.example.com/app",
|
||||
image=None,
|
||||
image_uri=None,
|
||||
image_name=None,
|
||||
tag=None,
|
||||
remote_build_flag=None,
|
||||
placement=RequestedPlacement(listener_id="listener-1"),
|
||||
image_pull_secrets=(),
|
||||
selector=ById("dep-1"),
|
||||
assert ExistingDeployment.from_resource(
|
||||
"dep-1", resource
|
||||
) == ExistingDeployment(
|
||||
"dep-1", "external_docker", placement, image_pull_secrets
|
||||
)
|
||||
|
||||
|
||||
def test_a_deployment_id_with_image_pull_secrets_is_refused_without_probing_docker(
|
||||
monkeypatch,
|
||||
):
|
||||
def explode() -> tuple[bool, str | None]:
|
||||
raise AssertionError("docker must not be probed for an argv-only conflict")
|
||||
|
||||
monkeypatch.setattr(deploy_mod, "can_build_locally", explode)
|
||||
|
||||
with pytest.raises(click.UsageError, match="dep-1"):
|
||||
_select_source(
|
||||
push_to="registry.example.com/app",
|
||||
image=None,
|
||||
image_uri=None,
|
||||
image_name=None,
|
||||
tag=None,
|
||||
remote_build_flag=None,
|
||||
placement=RequestedPlacement(),
|
||||
image_pull_secrets=("regcred",),
|
||||
selector=ById("dep-1"),
|
||||
)
|
||||
class TestStoredPlacement:
|
||||
@pytest.mark.parametrize(
|
||||
("stored", "requested", "allowed"),
|
||||
[
|
||||
pytest.param(
|
||||
StoredPlacement("listener-1", "a"),
|
||||
RequestedPlacement("listener-1", "a"),
|
||||
True,
|
||||
id="same_listener_and_namespace",
|
||||
),
|
||||
pytest.param(
|
||||
StoredPlacement("listener-1", "a"),
|
||||
RequestedPlacement(k8s_namespace="a"),
|
||||
True,
|
||||
id="same_namespace_alone",
|
||||
),
|
||||
pytest.param(
|
||||
StoredPlacement("listener-1", "a"),
|
||||
RequestedPlacement("listener-2"),
|
||||
False,
|
||||
id="other_listener",
|
||||
),
|
||||
pytest.param(
|
||||
StoredPlacement("listener-1", "a"),
|
||||
RequestedPlacement("listener-1", "b"),
|
||||
False,
|
||||
id="other_namespace",
|
||||
),
|
||||
pytest.param(
|
||||
StoredPlacement(None, None),
|
||||
RequestedPlacement("listener-1"),
|
||||
False,
|
||||
id="created_without_a_listener",
|
||||
),
|
||||
pytest.param(
|
||||
StoredPlacement("listener-1", None),
|
||||
RequestedPlacement("listener-1"),
|
||||
True,
|
||||
id="known_listener_with_an_unreported_namespace",
|
||||
),
|
||||
pytest.param(
|
||||
StoredPlacement("listener-1", None),
|
||||
RequestedPlacement("listener-1", "a"),
|
||||
False,
|
||||
id="namespace_that_was_not_reported",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_only_the_passed_values_must_match(self, stored, requested, allowed):
|
||||
assert stored.allows(requested) is allowed
|
||||
|
||||
|
||||
class TestResourceSpec:
|
||||
@@ -1540,18 +1615,55 @@ class TestCreateOnlySettings:
|
||||
def test_a_valid_secret_name_is_accepted(self):
|
||||
CreateOnlySettings(RequestedPlacement(), ("regcred-1.example",))
|
||||
|
||||
def test_ensure_not_existing_mentions_the_api_and_ui_for_pull_secrets(self):
|
||||
def test_unknown_pull_secrets_point_to_the_api_and_ui(self):
|
||||
settings = CreateOnlySettings(RequestedPlacement(), ("regcred",))
|
||||
with pytest.raises(click.UsageError, match="API or the LangSmith UI"):
|
||||
settings.ensure_not_existing("dep-1")
|
||||
settings.ensure_unchanged(ExistingDeployment("dep-1", "external_docker"))
|
||||
|
||||
def test_ensure_not_existing_keeps_the_placement_message_unchanged(self):
|
||||
def test_an_unknown_placement_keeps_the_original_message(self):
|
||||
settings = CreateOnlySettings(RequestedPlacement(listener_id="listener-1"))
|
||||
with pytest.raises(
|
||||
click.UsageError,
|
||||
match="Listener and namespace are fixed when an Agent Server is created",
|
||||
match=(
|
||||
"Listener and namespace are fixed when an Agent Server is created. "
|
||||
"Agent Server dep-1 already exists, so drop --listener-id and "
|
||||
"--k8s-namespace, or create a new Agent Server with a different --name."
|
||||
),
|
||||
):
|
||||
settings.ensure_not_existing("dep-1")
|
||||
settings.ensure_unchanged(ExistingDeployment("dep-1", "external_docker"))
|
||||
|
||||
def test_an_unreported_namespace_names_the_listener_and_asks_to_drop_the_namespace(
|
||||
self,
|
||||
):
|
||||
settings = CreateOnlySettings(RequestedPlacement("listener-1", "a"))
|
||||
with pytest.raises(
|
||||
click.UsageError,
|
||||
match=(
|
||||
"Agent Server dep-1 runs on listener listener-1, but its namespace "
|
||||
"was not reported, so pass --listener-id listener-1 without "
|
||||
"--k8s-namespace, or drop both flags, or create a new Agent Server "
|
||||
"with a different --name."
|
||||
),
|
||||
):
|
||||
settings.ensure_unchanged(
|
||||
ExistingDeployment(
|
||||
"dep-1", "external_docker", StoredPlacement("listener-1", None)
|
||||
)
|
||||
)
|
||||
|
||||
def test_equal_values_pass_without_a_refusal(self):
|
||||
settings = CreateOnlySettings(
|
||||
RequestedPlacement("listener-1", "a"), ("regcred",)
|
||||
)
|
||||
|
||||
settings.ensure_unchanged(
|
||||
ExistingDeployment(
|
||||
"dep-1",
|
||||
"external_docker",
|
||||
StoredPlacement("listener-1", "a"),
|
||||
frozenset({"regcred"}),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
class TestPlacementOnAKnownListener:
|
||||
|
||||
@@ -233,6 +233,21 @@ def _routing_client(seen: dict) -> HostBackendClient:
|
||||
},
|
||||
id="internal_docker_revision_names_its_source",
|
||||
),
|
||||
pytest.param(
|
||||
lambda c: c.update_deployment(
|
||||
"dep-123",
|
||||
"registry.example.com/app@sha256:abc",
|
||||
revision_source="internal_docker",
|
||||
secrets=[],
|
||||
),
|
||||
{
|
||||
"revision_source": "internal_docker",
|
||||
"source_revision_config": {
|
||||
"image_uri": "registry.example.com/app@sha256:abc"
|
||||
},
|
||||
},
|
||||
id="revision_omits_an_empty_secrets_list",
|
||||
),
|
||||
pytest.param(
|
||||
lambda c: c.update_deployment_internal_source(
|
||||
"dep-123",
|
||||
@@ -252,9 +267,25 @@ def _routing_client(seen: dict) -> HostBackendClient:
|
||||
"install_command": "yarn install",
|
||||
"build_command": "yarn build",
|
||||
},
|
||||
"secrets": [],
|
||||
},
|
||||
id="internal_source_revision_sends_js_build_commands",
|
||||
id="internal_source_revision_sends_build_commands_and_omits_empty_secrets",
|
||||
),
|
||||
pytest.param(
|
||||
lambda c: c.update_deployment_internal_source(
|
||||
"dep-123",
|
||||
source_tarball_path="tarballs/src.tgz",
|
||||
config_path="langgraph.json",
|
||||
secrets=[{"name": "KEY", "value": "val"}],
|
||||
),
|
||||
{
|
||||
"revision_source": "internal_source",
|
||||
"source_revision_config": {
|
||||
"source_tarball_path": "tarballs/src.tgz",
|
||||
"langgraph_config_path": "langgraph.json",
|
||||
},
|
||||
"secrets": [{"name": "KEY", "value": "val"}],
|
||||
},
|
||||
id="internal_source_revision_forwards_secrets",
|
||||
),
|
||||
pytest.param(
|
||||
lambda c: c.update_deployment_internal_source(
|
||||
|
||||
@@ -37,6 +37,10 @@ CONFIG_KEY_SEND = sys.intern("__pregel_send")
|
||||
# holds the `write` function that accepts writes to state/edges/reserved keys
|
||||
CONFIG_KEY_READ = sys.intern("__pregel_read")
|
||||
# holds the `read` function that returns a copy of the current state
|
||||
CONFIG_KEY_READ_STATE = sys.intern("__pregel_read_state")
|
||||
# holds a function that returns the state as the task's node gets it from an edge,
|
||||
# set on Send tasks, whose input is the Send arg instead. Other tasks set it to None
|
||||
# so a graph running inside a Send task never reads its parent's state
|
||||
CONFIG_KEY_CALL = sys.intern("__pregel_call")
|
||||
# holds the `call` function that accepts a node/func, args and returns a future
|
||||
CONFIG_KEY_CHECKPOINTER = sys.intern("__pregel_checkpointer")
|
||||
@@ -72,8 +76,6 @@ CONFIG_KEY_DURABILITY = sys.intern("__pregel_durability")
|
||||
# holds the durability mode, one of "sync", "async", or "exit"
|
||||
CONFIG_KEY_RUNTIME = sys.intern("__pregel_runtime")
|
||||
# holds a `Runtime` instance with context, store, stream writer, etc.
|
||||
CONFIG_KEY_STATE_KEYS = sys.intern("__pregel_state_keys")
|
||||
# holds the names of the graph's state channels
|
||||
CONFIG_KEY_RESUME_MAP = sys.intern("__pregel_resume_map")
|
||||
# holds a mapping of task ns -> resume value for resuming tasks
|
||||
CONFIG_KEY_STRICT_RESUME = sys.intern("__pregel_strict_resume")
|
||||
@@ -91,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(":")
|
||||
|
||||
@@ -119,7 +119,7 @@ class DeltaChannel(Generic[Value], BaseChannel[Any, Any, Any]):
|
||||
"""Initialize from a stored blob.
|
||||
|
||||
Blob types:
|
||||
* `MISSING`: start empty; caller replays writes.
|
||||
* `MISSING` or `None`: start empty; caller replays writes.
|
||||
* `_DeltaSnapshot(value)`: restore value directly from snapshot.
|
||||
* plain value (migration from old `BinaryOperatorAggregate` blobs):
|
||||
use directly.
|
||||
@@ -128,7 +128,7 @@ class DeltaChannel(Generic[Value], BaseChannel[Any, Any, Any]):
|
||||
self.reducer, self.typ, snapshot_frequency=self.snapshot_frequency
|
||||
)
|
||||
new.key = self.key
|
||||
if checkpoint is MISSING:
|
||||
if checkpoint is MISSING or checkpoint is None:
|
||||
new.value = self.typ()
|
||||
elif isinstance(checkpoint, _DeltaSnapshot):
|
||||
new.value = checkpoint.value
|
||||
|
||||
@@ -1,20 +1,12 @@
|
||||
import asyncio
|
||||
import sys
|
||||
from collections.abc import Mapping
|
||||
from typing import Any
|
||||
|
||||
from langchain_core.runnables import RunnableConfig
|
||||
from langchain_core.runnables.config import var_child_runnable_config
|
||||
from langgraph.store.base import BaseStore
|
||||
|
||||
from langgraph._internal._constants import (
|
||||
CONF,
|
||||
CONFIG_KEY_READ,
|
||||
CONFIG_KEY_RUNTIME,
|
||||
CONFIG_KEY_SEND,
|
||||
CONFIG_KEY_STATE_KEYS,
|
||||
)
|
||||
from langgraph.errors import InvalidUpdateError, NotInTaskError
|
||||
from langgraph._internal._constants import CONF, CONFIG_KEY_RUNTIME
|
||||
from langgraph.types import StreamWriter
|
||||
|
||||
|
||||
@@ -202,70 +194,3 @@ def get_stream_writer() -> StreamWriter:
|
||||
"""
|
||||
runtime = get_config()[CONF][CONFIG_KEY_RUNTIME]
|
||||
return runtime.stream_writer
|
||||
|
||||
|
||||
def _task_conf(caller: str) -> dict[str, Any]:
|
||||
conf = (var_child_runnable_config.get() or {}).get(CONF, {})
|
||||
if CONFIG_KEY_READ not in conf:
|
||||
msg = f"Called {caller} outside of a graph node or task"
|
||||
raise NotInTaskError(msg)
|
||||
return conf
|
||||
|
||||
|
||||
def read_state(*keys: str) -> dict[str, Any]:
|
||||
"""Read graph state from inside a node or tool, with its own updates applied.
|
||||
|
||||
A node receives state as it was when the step started. This also applies
|
||||
the updates the node has queued since, such as with
|
||||
[`write_state`][langgraph.config.write_state]. A key that holds its value
|
||||
for one step, such as an `EphemeralValue`, reads as unset unless the node
|
||||
wrote it. Like `get_store`, this does not work in async code on
|
||||
Python < 3.11.
|
||||
|
||||
!!! version-added "Added in version 1.2.23"
|
||||
|
||||
Args:
|
||||
*keys: The state keys to read. Reads every state key when omitted.
|
||||
|
||||
Returns:
|
||||
The values by key. A key with no value is left out.
|
||||
|
||||
Raises:
|
||||
KeyError: When a key is not a state key.
|
||||
NotInTaskError: When called outside of a graph node or task.
|
||||
"""
|
||||
conf = _task_conf("read_state")
|
||||
state_keys = conf.get(CONFIG_KEY_STATE_KEYS, ())
|
||||
for key in keys:
|
||||
if key not in state_keys:
|
||||
msg = f"'{key}' is not a state key"
|
||||
raise KeyError(msg)
|
||||
return conf[CONFIG_KEY_READ](list(keys or state_keys), True)
|
||||
|
||||
|
||||
def write_state(update: Mapping[str, Any]) -> None:
|
||||
"""Queue a state update from inside a node or tool.
|
||||
|
||||
The update is applied when the step ends, and
|
||||
[`read_state`][langgraph.config.read_state] sees it at once. Like
|
||||
`get_store`, this does not work in async code on Python < 3.11.
|
||||
|
||||
!!! version-added "Added in version 1.2.23"
|
||||
|
||||
Args:
|
||||
update: The values to write, by state key.
|
||||
|
||||
Raises:
|
||||
InvalidUpdateError: When a key is not a state key, or takes one value
|
||||
per step and the node already wrote it. Nothing is queued.
|
||||
NotInTaskError: When called outside of a graph node or task.
|
||||
"""
|
||||
conf = _task_conf("write_state")
|
||||
state_keys = conf.get(CONFIG_KEY_STATE_KEYS, ())
|
||||
for key in update:
|
||||
if key not in state_keys:
|
||||
msg = f"Cannot write to '{key}': it is not a state key"
|
||||
raise InvalidUpdateError(msg)
|
||||
writes = list(update.items())
|
||||
conf[CONFIG_KEY_READ](list(update), True, proposed=writes)
|
||||
conf[CONFIG_KEY_SEND](writes)
|
||||
@@ -25,7 +25,6 @@ __all__ = (
|
||||
"NodeError",
|
||||
"NodeInterrupt",
|
||||
"NodeTimeoutError",
|
||||
"NotInTaskError",
|
||||
"ParentCommand",
|
||||
"EmptyInputError",
|
||||
"TaskNotFound",
|
||||
@@ -102,10 +101,6 @@ class InvalidUpdateError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class NotInTaskError(RuntimeError):
|
||||
"""Raised when task state is read or written outside of a running graph task."""
|
||||
|
||||
|
||||
class GraphInterrupt(GraphBubbleUp):
|
||||
"""Raised when a subgraph is interrupted, suppressed by the root graph.
|
||||
Never raised directly, or surfaced to the user."""
|
||||
|
||||
@@ -24,6 +24,9 @@ from typing_extensions import TypedDict, deprecated
|
||||
|
||||
from langgraph._internal._constants import CONF, CONFIG_KEY_SEND
|
||||
from langgraph.graph.state import StateGraph
|
||||
from langgraph.pregel._messages import (
|
||||
REMOVE_ALL_MESSAGES as REMOVE_ALL_MESSAGES,
|
||||
)
|
||||
from langgraph.pregel._messages import (
|
||||
_messages_delta_reducer as _messages_delta_reducer,
|
||||
)
|
||||
@@ -38,8 +41,6 @@ __all__ = (
|
||||
|
||||
Messages = list[MessageLikeRepresentation] | MessageLikeRepresentation
|
||||
|
||||
REMOVE_ALL_MESSAGES = "__remove_all__"
|
||||
|
||||
|
||||
def _add_messages_wrapper(func: Callable) -> Callable[[Messages, Messages], Messages]:
|
||||
def _add_messages(
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -42,6 +42,7 @@ from langgraph._internal._constants import (
|
||||
CONFIG_KEY_CHECKPOINTER,
|
||||
CONFIG_KEY_NODE_ERROR,
|
||||
CONFIG_KEY_READ,
|
||||
CONFIG_KEY_READ_STATE,
|
||||
CONFIG_KEY_RESUME_MAP,
|
||||
CONFIG_KEY_RUNTIME,
|
||||
CONFIG_KEY_SCRATCHPAD,
|
||||
@@ -194,27 +195,20 @@ def local_read(
|
||||
task: WritesProtocol,
|
||||
select: list[str] | str,
|
||||
fresh: bool = False,
|
||||
*,
|
||||
proposed: Sequence[tuple[str, Any]] = (),
|
||||
) -> dict[str, Any] | Any:
|
||||
"""Function injected under CONFIG_KEY_READ in task config, to read current state.
|
||||
Used by conditional edges to read a copy of the state with reflecting the writes
|
||||
from that node only.
|
||||
|
||||
`proposed` writes are applied after the task's own without being queued, so a
|
||||
fresh read raises `InvalidUpdateError` for an update the step would reject."""
|
||||
# a snapshot, so another thread queuing a write cannot break the loops below
|
||||
writes = (*task.writes, *proposed)
|
||||
from that node only."""
|
||||
updated: dict[str, list[Any]] = defaultdict(list)
|
||||
if isinstance(select, str):
|
||||
managed_keys = []
|
||||
for c, v in writes:
|
||||
for c, v in task.writes:
|
||||
if c == select:
|
||||
updated[c].append(v)
|
||||
else:
|
||||
managed_keys = [k for k in select if k in managed]
|
||||
select = [k for k in select if k not in managed]
|
||||
for c, v in writes:
|
||||
for c, v in task.writes:
|
||||
if c in select:
|
||||
updated[c].append(v)
|
||||
if fresh:
|
||||
@@ -741,6 +735,7 @@ def prepare_single_task(
|
||||
triggers,
|
||||
),
|
||||
),
|
||||
CONFIG_KEY_READ_STATE: None,
|
||||
CONFIG_KEY_CHECKPOINTER: (
|
||||
checkpointer
|
||||
or configurable.get(CONFIG_KEY_CHECKPOINTER)
|
||||
@@ -918,6 +913,7 @@ def prepare_push_task_functional(
|
||||
managed,
|
||||
PregelTaskWrites(in_progress_task_path, name, writes, triggers),
|
||||
),
|
||||
CONFIG_KEY_READ_STATE: None,
|
||||
CONFIG_KEY_CHECKPOINTER: (
|
||||
checkpointer or configurable.get(CONFIG_KEY_CHECKPOINTER)
|
||||
),
|
||||
@@ -1088,6 +1084,15 @@ def prepare_push_task_send(
|
||||
translated_task_path, packet.node, writes, triggers
|
||||
),
|
||||
),
|
||||
CONFIG_KEY_READ_STATE: partial(
|
||||
_proc_input,
|
||||
proc,
|
||||
managed,
|
||||
channels,
|
||||
for_execution=True,
|
||||
scratchpad=scratchpad,
|
||||
input_cache=None,
|
||||
),
|
||||
CONFIG_KEY_CHECKPOINTER: (
|
||||
checkpointer or configurable.get(CONFIG_KEY_CHECKPOINTER)
|
||||
),
|
||||
@@ -1229,6 +1234,7 @@ def prepare_node_error_handler_task(
|
||||
PUSH_TRIGGER,
|
||||
),
|
||||
),
|
||||
CONFIG_KEY_READ_STATE: None,
|
||||
CONFIG_KEY_CHECKPOINTER: (
|
||||
checkpointer or configurable.get(CONFIG_KEY_CHECKPOINTER)
|
||||
),
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -4,7 +4,7 @@ import asyncio
|
||||
import binascii
|
||||
import concurrent.futures
|
||||
from collections import defaultdict, deque
|
||||
from collections.abc import Callable, Iterator, Mapping, Sequence
|
||||
from collections.abc import Awaitable, Callable, Iterator, Mapping, Sequence
|
||||
from contextlib import (
|
||||
AbstractAsyncContextManager,
|
||||
AbstractContextManager,
|
||||
@@ -47,7 +47,6 @@ from langgraph._internal._constants import (
|
||||
CONFIG_KEY_RESUMING,
|
||||
CONFIG_KEY_RUNTIME,
|
||||
CONFIG_KEY_SCRATCHPAD,
|
||||
CONFIG_KEY_STATE_KEYS,
|
||||
CONFIG_KEY_STREAM,
|
||||
CONFIG_KEY_STRICT_RESUME,
|
||||
CONFIG_KEY_TASK_ID,
|
||||
@@ -75,7 +74,7 @@ from langgraph.channels.base import BaseChannel
|
||||
from langgraph.channels.binop import _get_overwrite
|
||||
from langgraph.channels.delta import DeltaChannel
|
||||
from langgraph.channels.untracked_value import UntrackedValue
|
||||
from langgraph.constants import END, TAG_HIDDEN
|
||||
from langgraph.constants import TAG_HIDDEN
|
||||
from langgraph.errors import (
|
||||
EmptyInputError,
|
||||
GraphInterrupt,
|
||||
@@ -201,16 +200,28 @@ class PregelLoop:
|
||||
Callable[
|
||||
[
|
||||
concurrent.futures.Future | None,
|
||||
Sequence[Any],
|
||||
Sequence[concurrent.futures.Future],
|
||||
RunnableConfig,
|
||||
Checkpoint,
|
||||
str,
|
||||
CheckpointMetadata,
|
||||
ChannelVersions,
|
||||
],
|
||||
Any,
|
||||
RunnableConfig,
|
||||
]
|
||||
| Callable[
|
||||
[
|
||||
asyncio.Task | None,
|
||||
Sequence[asyncio.Future],
|
||||
RunnableConfig,
|
||||
Checkpoint,
|
||||
CheckpointMetadata,
|
||||
ChannelVersions,
|
||||
],
|
||||
Awaitable[RunnableConfig],
|
||||
]
|
||||
| None
|
||||
)
|
||||
|
||||
_migrate_checkpoint: Callable[[Checkpoint], None] | None
|
||||
submit: Submit
|
||||
channels: Mapping[str, BaseChannel]
|
||||
@@ -350,11 +361,6 @@ class PregelLoop:
|
||||
self.input_keys = input_keys
|
||||
self.output_keys = output_keys
|
||||
self.stream_keys = stream_keys
|
||||
keys = [stream_keys] if isinstance(stream_keys, str) else stream_keys
|
||||
# an entrypoint streams its return value through END, which is not state
|
||||
self.config = patch_configurable(
|
||||
self.config, {CONFIG_KEY_STATE_KEYS: [k for k in keys if k != END]}
|
||||
)
|
||||
self.interrupt_after = interrupt_after
|
||||
self.interrupt_before = interrupt_before
|
||||
self.manager = manager
|
||||
@@ -1740,6 +1746,7 @@ class SyncPregelLoop(PregelLoop, AbstractContextManager):
|
||||
)
|
||||
self.stack = ExitStack()
|
||||
if checkpointer:
|
||||
self._checkpointer_put_after_previous = self._put_checkpoint_after_previous
|
||||
self.checkpointer_get_next_version = checkpointer.get_next_version
|
||||
self.checkpointer_put_writes = checkpointer.put_writes
|
||||
self.checkpointer_put_writes_accepts_task_path = (
|
||||
@@ -1747,11 +1754,11 @@ class SyncPregelLoop(PregelLoop, AbstractContextManager):
|
||||
)
|
||||
else:
|
||||
self.checkpointer_get_next_version = increment
|
||||
self._checkpointer_put_after_previous = None # type: ignore[assignment]
|
||||
self._checkpointer_put_after_previous = None
|
||||
self.checkpointer_put_writes = None
|
||||
self.checkpointer_put_writes_accepts_task_path = False
|
||||
|
||||
def _checkpointer_put_after_previous(
|
||||
def _put_checkpoint_after_previous(
|
||||
self,
|
||||
prev: concurrent.futures.Future | None,
|
||||
delta_write_futs: Sequence[concurrent.futures.Future],
|
||||
@@ -1996,6 +2003,7 @@ class AsyncPregelLoop(PregelLoop, AbstractAsyncContextManager):
|
||||
)
|
||||
self.stack = AsyncExitStack()
|
||||
if checkpointer:
|
||||
self._checkpointer_put_after_previous = self._put_checkpoint_after_previous
|
||||
self.checkpointer_get_next_version = checkpointer.get_next_version
|
||||
self.checkpointer_put_writes = checkpointer.aput_writes
|
||||
self.checkpointer_put_writes_accepts_task_path = (
|
||||
@@ -2003,11 +2011,11 @@ class AsyncPregelLoop(PregelLoop, AbstractAsyncContextManager):
|
||||
)
|
||||
else:
|
||||
self.checkpointer_get_next_version = increment
|
||||
self._checkpointer_put_after_previous = None # type: ignore[assignment]
|
||||
self._checkpointer_put_after_previous = None
|
||||
self.checkpointer_put_writes = None
|
||||
self.checkpointer_put_writes_accepts_task_path = False
|
||||
|
||||
async def _checkpointer_put_after_previous(
|
||||
async def _put_checkpoint_after_previous(
|
||||
self,
|
||||
prev: asyncio.Task | None,
|
||||
delta_write_futs: Sequence[asyncio.Future],
|
||||
|
||||
@@ -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 ()
|
||||
|
||||
|
||||
@@ -433,21 +441,24 @@ class StreamMessagesHandlerV2(StreamMessagesHandler, _V2StreamingCallbackHandler
|
||||
# Defined here rather than in `langgraph.graph.message`, which re-exports it:
|
||||
# `ensure_message_ids` has to recognize it, and importing that module from the
|
||||
# loop would be an import cycle.
|
||||
REMOVE_ALL_MESSAGES = "__remove_all__"
|
||||
|
||||
|
||||
def _messages_delta_reducer(
|
||||
state: list[AnyMessage], writes: list[list[AnyMessage]]
|
||||
) -> list[AnyMessage]:
|
||||
"""**Experimental.** Batch reducer for use with `DeltaChannel`.
|
||||
|
||||
Processes all writes in one pass — dedup by ID, `RemoveMessage`
|
||||
tombstoning — without calling `add_messages`.
|
||||
tombstoning, `REMOVE_ALL_MESSAGES` reset — without calling `add_messages`.
|
||||
|
||||
This reducer is batching-invariant, as required by `DeltaChannel`:
|
||||
`reducer(reducer(state, xs), ys) == reducer(state, xs + ys)`.
|
||||
|
||||
Raw dict / string / tuple inputs are coerced to typed `BaseMessage`
|
||||
objects so that HTTP-driven graphs work without a separate coercion
|
||||
step. This is not full `add_messages` parity — `REMOVE_ALL_MESSAGES`,
|
||||
unknown-id `RemoveMessage` errors, missing-id UUID assignment, and
|
||||
step. This is not full `add_messages` parity — unknown-id
|
||||
`RemoveMessage` errors, missing-id UUID assignment, and
|
||||
`BaseMessageChunk` conversion are not handled here.
|
||||
|
||||
Example::
|
||||
@@ -478,6 +489,13 @@ def _messages_delta_reducer(
|
||||
state_msgs = cast("list[AnyMessage]", convert_to_messages(state))
|
||||
msgs = cast("list[AnyMessage]", convert_to_messages(flat))
|
||||
|
||||
for idx in range(len(msgs) - 1, -1, -1):
|
||||
m = msgs[idx]
|
||||
if isinstance(m, RemoveMessage) and m.id == REMOVE_ALL_MESSAGES:
|
||||
state_msgs = []
|
||||
msgs = msgs[idx + 1 :]
|
||||
break
|
||||
|
||||
index: dict[str, int] = {
|
||||
m.id: i for i, m in enumerate(state_msgs) if m.id is not None
|
||||
}
|
||||
@@ -514,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)
|
||||
@@ -76,7 +76,6 @@ from langgraph._internal._constants import (
|
||||
CONFIG_KEY_RUNNER_SUBMIT,
|
||||
CONFIG_KEY_RUNTIME,
|
||||
CONFIG_KEY_SEND,
|
||||
CONFIG_KEY_STATE_KEYS,
|
||||
CONFIG_KEY_STREAM,
|
||||
CONFIG_KEY_STREAM_MESSAGES_V2,
|
||||
CONFIG_KEY_TASK_ID,
|
||||
@@ -718,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]
|
||||
|
||||
@@ -757,7 +756,7 @@ class Pregel(
|
||||
|
||||
config: RunnableConfig | None = None
|
||||
|
||||
name: str = "LangGraph"
|
||||
name: str | None = "LangGraph"
|
||||
|
||||
trigger_to_nodes: Mapping[str, Sequence[str]]
|
||||
node_error_handler_map: Mapping[str, str]
|
||||
@@ -2048,7 +2047,6 @@ class Pregel(
|
||||
# deque.extend is thread-safe
|
||||
CONFIG_KEY_SEND: writes.extend,
|
||||
CONFIG_KEY_TASK_ID: task_id,
|
||||
CONFIG_KEY_STATE_KEYS: self.stream_channels_list,
|
||||
CONFIG_KEY_READ: partial(
|
||||
local_read,
|
||||
_scratchpad(
|
||||
@@ -2549,7 +2547,6 @@ class Pregel(
|
||||
# deque.extend is thread-safe
|
||||
CONFIG_KEY_SEND: writes.extend,
|
||||
CONFIG_KEY_TASK_ID: task_id,
|
||||
CONFIG_KEY_STATE_KEYS: self.stream_channels_list,
|
||||
CONFIG_KEY_READ: partial(
|
||||
local_read,
|
||||
_scratchpad(
|
||||
@@ -2806,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)`.
|
||||
@@ -3059,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
|
||||
@@ -3219,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)`.
|
||||
@@ -3513,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 []
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "langgraph"
|
||||
version = "1.2.22"
|
||||
version = "1.2.25"
|
||||
description = "Building stateful, multi-actor applications with LLMs"
|
||||
authors = []
|
||||
requires-python = ">=3.10"
|
||||
@@ -27,7 +27,7 @@ dependencies = [
|
||||
"langchain-core>=1.4.7,<2",
|
||||
"langgraph-checkpoint>=4.3.0,<5.0.0",
|
||||
"langgraph-sdk>=0.4.6,<0.5.0",
|
||||
"langgraph-prebuilt>=1.1.0,<1.2.0",
|
||||
"langgraph-prebuilt>=1.1.3,<1.2.0",
|
||||
"xxhash>=3.5.0",
|
||||
"pydantic>=2.7.4",
|
||||
]
|
||||
@@ -60,7 +60,7 @@ test = [
|
||||
"langgraph-checkpoint-postgres",
|
||||
"langgraph-sdk",
|
||||
"psycopg[binary]",
|
||||
"uvloop==0.22.1",
|
||||
"uvloop==0.23.0",
|
||||
"pyperf",
|
||||
"py-spy",
|
||||
"pycryptodome",
|
||||
|
||||
@@ -2,34 +2,12 @@ import re
|
||||
from collections.abc import Sequence
|
||||
from typing import Any
|
||||
|
||||
from typing_extensions import Self
|
||||
|
||||
|
||||
class AnyObject:
|
||||
def __eq__(self, value):
|
||||
return True
|
||||
|
||||
|
||||
class FloatBetween(float):
|
||||
def __new__(cls, min_value: float, max_value: float) -> Self:
|
||||
return super().__new__(cls, min_value)
|
||||
|
||||
def __init__(self, min_value: float, max_value: float) -> None:
|
||||
super().__init__()
|
||||
self.min_value = min_value
|
||||
self.max_value = max_value
|
||||
|
||||
def __eq__(self, other: object) -> bool:
|
||||
return (
|
||||
isinstance(other, float)
|
||||
and other >= self.min_value
|
||||
and other <= self.max_value
|
||||
)
|
||||
|
||||
def __hash__(self) -> int:
|
||||
return hash((float(self), self.min_value, self.max_value))
|
||||
|
||||
|
||||
class AnyStr(str):
|
||||
def __init__(self, prefix: str | re.Pattern = "") -> None:
|
||||
super().__init__()
|
||||
|
||||
@@ -18,7 +18,7 @@ from langgraph.channels.topic import Topic
|
||||
from langgraph.channels.untracked_value import UntrackedValue
|
||||
from langgraph.errors import EmptyChannelError, InvalidUpdateError
|
||||
from langgraph.graph import START, StateGraph
|
||||
from langgraph.graph.message import _messages_delta_reducer
|
||||
from langgraph.graph.message import REMOVE_ALL_MESSAGES, _messages_delta_reducer
|
||||
from langgraph.graph.state import _get_channel
|
||||
from langgraph.pregel._checkpoint import delta_channels_to_snapshot
|
||||
from langgraph.types import Overwrite
|
||||
@@ -153,6 +153,25 @@ def test_delta_channel_basic_two_steps() -> None:
|
||||
assert ch.get()[1].content == "hello"
|
||||
|
||||
|
||||
def test_delta_channel_from_none_checkpoint_replays_from_empty() -> None:
|
||||
ch = DeltaChannel(_messages_delta_reducer, list).from_checkpoint(None)
|
||||
msg = HumanMessage(content="hi", id="h1")
|
||||
ch.replay_writes([("t0", "messages", [msg])])
|
||||
assert ch.get() == [msg]
|
||||
|
||||
|
||||
def test_messages_delta_reducer_remove_all() -> None:
|
||||
old = HumanMessage(content="old", id="h0")
|
||||
dropped = HumanMessage(content="dropped", id="h1")
|
||||
kept = AIMessage(content="kept", id="a1")
|
||||
writes = [[dropped], [RemoveMessage(id=REMOVE_ALL_MESSAGES), kept]]
|
||||
assert _messages_delta_reducer([old], writes) == [kept]
|
||||
state = [old]
|
||||
for w in writes:
|
||||
state = _messages_delta_reducer(state, [w])
|
||||
assert state == [kept]
|
||||
|
||||
|
||||
def test_delta_channel_from_checkpoint_writes_list() -> None:
|
||||
"""replay_writes on a fresh channel replays through the operator."""
|
||||
spec = DeltaChannel(_messages_delta_reducer, list)
|
||||
|
||||
@@ -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(),
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
),
|
||||
|
||||
@@ -88,7 +88,7 @@ from langgraph.types import (
|
||||
interrupt,
|
||||
)
|
||||
from tests.agents import AgentAction, AgentFinish
|
||||
from tests.any_str import AnyStr, AnyVersion, FloatBetween, UnsortedSequence
|
||||
from tests.any_str import AnyStr, AnyVersion, UnsortedSequence
|
||||
from tests.messages import (
|
||||
_AnyIdAIMessage,
|
||||
_AnyIdAIMessageChunk,
|
||||
@@ -3385,6 +3385,12 @@ def test_subgraph_checkpoint_true_interrupt(
|
||||
def test_stream_subgraphs_during_execution(
|
||||
sync_checkpointer: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
streamed = {"inner_1": threading.Event(), "outer_1": threading.Event()}
|
||||
|
||||
def wait_until_streamed(node: str) -> None:
|
||||
if not streamed[node].wait(timeout=10):
|
||||
raise TimeoutError(f"{node} was not streamed while the graph was running")
|
||||
|
||||
class InnerState(TypedDict):
|
||||
my_key: Annotated[str, operator.add]
|
||||
my_other_key: str
|
||||
@@ -3393,7 +3399,7 @@ def test_stream_subgraphs_during_execution(
|
||||
return {"my_key": "got here", "my_other_key": state["my_key"]}
|
||||
|
||||
def inner_2(state: InnerState):
|
||||
time.sleep(0.5)
|
||||
wait_until_streamed("outer_1")
|
||||
return {
|
||||
"my_key": " and there",
|
||||
"my_other_key": state["my_key"],
|
||||
@@ -3410,7 +3416,7 @@ def test_stream_subgraphs_during_execution(
|
||||
my_key: Annotated[str, operator.add]
|
||||
|
||||
def outer_1(state: State):
|
||||
time.sleep(0.2)
|
||||
wait_until_streamed("inner_1")
|
||||
return {"my_key": " and parallel"}
|
||||
|
||||
def outer_2(state: State):
|
||||
@@ -3428,34 +3434,22 @@ def test_stream_subgraphs_during_execution(
|
||||
|
||||
app = graph.compile(checkpointer=sync_checkpointer)
|
||||
|
||||
start = time.perf_counter()
|
||||
chunks: list[tuple[float, Any]] = []
|
||||
chunks: list[tuple[tuple[str, ...], dict[str, dict[str, str]]]] = []
|
||||
config = {"configurable": {"thread_id": "2"}}
|
||||
for c in app.stream({"my_key": ""}, config, subgraphs=True):
|
||||
chunks.append((round(time.perf_counter() - start, 1), c))
|
||||
for idx in range(len(chunks)):
|
||||
elapsed, c = chunks[idx]
|
||||
chunks[idx] = (round(elapsed - chunks[0][0], 1), c)
|
||||
for namespace, update in app.stream({"my_key": ""}, config, subgraphs=True):
|
||||
chunks.append((namespace, update))
|
||||
for node in update.keys() & streamed.keys():
|
||||
streamed[node].set()
|
||||
|
||||
assert chunks == [
|
||||
# arrives before "inner" finishes
|
||||
((AnyStr("inner:"),), {"inner_1": {"my_key": "got here", "my_other_key": ""}}),
|
||||
((), {"outer_1": {"my_key": " and parallel"}}),
|
||||
(
|
||||
FloatBetween(0.0, 0.1),
|
||||
(
|
||||
(AnyStr("inner:"),),
|
||||
{"inner_1": {"my_key": "got here", "my_other_key": ""}},
|
||||
),
|
||||
(AnyStr("inner:"),),
|
||||
{"inner_2": {"my_key": " and there", "my_other_key": "got here"}},
|
||||
),
|
||||
(FloatBetween(0.2, 0.3), ((), {"outer_1": {"my_key": " and parallel"}})),
|
||||
(
|
||||
FloatBetween(0.5, 0.8),
|
||||
(
|
||||
(AnyStr("inner:"),),
|
||||
{"inner_2": {"my_key": " and there", "my_other_key": "got here"}},
|
||||
),
|
||||
),
|
||||
(FloatBetween(0.5, 0.8), ((), {"inner": {"my_key": "got here and there"}})),
|
||||
(FloatBetween(0.5, 0.8), ((), {"outer_2": {"my_key": " and back again"}})),
|
||||
((), {"inner": {"my_key": "got here and there"}}),
|
||||
((), {"outer_2": {"my_key": " and back again"}}),
|
||||
]
|
||||
|
||||
|
||||
@@ -3463,10 +3457,13 @@ def test_stream_buffering_single_node(sync_checkpointer: BaseCheckpointSaver) ->
|
||||
class State(TypedDict):
|
||||
my_key: Annotated[str, operator.add]
|
||||
|
||||
received = threading.Event()
|
||||
|
||||
def node(state: State, writer: StreamWriter):
|
||||
writer("Before sleep")
|
||||
time.sleep(0.2)
|
||||
writer("After sleep")
|
||||
writer("Before wait")
|
||||
if not received.wait(timeout=10):
|
||||
raise TimeoutError("Custom event was not streamed before node completion")
|
||||
writer("After wait")
|
||||
return {"my_key": "got here"}
|
||||
|
||||
builder = StateGraph(State)
|
||||
@@ -3475,16 +3472,15 @@ def test_stream_buffering_single_node(sync_checkpointer: BaseCheckpointSaver) ->
|
||||
builder.add_edge("node", END)
|
||||
graph = builder.compile(checkpointer=sync_checkpointer)
|
||||
|
||||
start = time.perf_counter()
|
||||
chunks: list[tuple[float, Any]] = []
|
||||
config = {"configurable": {"thread_id": "2"}}
|
||||
for c in graph.stream({"my_key": ""}, config, stream_mode="custom"):
|
||||
chunks.append((round(time.perf_counter() - start, 1), c))
|
||||
|
||||
assert chunks == [
|
||||
(FloatBetween(0.0, 0.1), "Before sleep"),
|
||||
(FloatBetween(0.2, 0.3), "After sleep"),
|
||||
]
|
||||
stream = graph.stream({"my_key": ""}, config, stream_mode="custom")
|
||||
try:
|
||||
assert next(stream) == "Before wait"
|
||||
received.set()
|
||||
assert list(stream) == ["After wait"]
|
||||
finally:
|
||||
received.set()
|
||||
stream.close()
|
||||
|
||||
|
||||
def test_nested_graph_interrupts_parallel(
|
||||
|
||||
@@ -86,7 +86,7 @@ from langgraph.types import (
|
||||
StreamWriter,
|
||||
interrupt,
|
||||
)
|
||||
from tests.any_str import AnyStr, AnyVersion, FloatBetween, UnsortedSequence
|
||||
from tests.any_str import AnyStr, AnyVersion, UnsortedSequence
|
||||
from tests.fake_tracer import FakeTracer
|
||||
from tests.memory_assert import MemorySaverNoPending
|
||||
from tests.messages import (
|
||||
@@ -5141,6 +5141,11 @@ async def test_subgraph_checkpoint_true_interrupt(
|
||||
async def test_stream_subgraphs_during_execution(
|
||||
async_checkpointer: BaseCheckpointSaver,
|
||||
) -> None:
|
||||
streamed = {"inner_1": asyncio.Event(), "outer_1": asyncio.Event()}
|
||||
|
||||
async def wait_until_streamed(node: str) -> None:
|
||||
await asyncio.wait_for(streamed[node].wait(), timeout=10)
|
||||
|
||||
class InnerState(TypedDict):
|
||||
my_key: Annotated[str, operator.add]
|
||||
my_other_key: str
|
||||
@@ -5149,7 +5154,7 @@ async def test_stream_subgraphs_during_execution(
|
||||
return {"my_key": "got here", "my_other_key": state["my_key"]}
|
||||
|
||||
async def inner_2(state: InnerState):
|
||||
await asyncio.sleep(0.5)
|
||||
await wait_until_streamed("outer_1")
|
||||
return {
|
||||
"my_key": " and there",
|
||||
"my_other_key": state["my_key"],
|
||||
@@ -5166,7 +5171,7 @@ async def test_stream_subgraphs_during_execution(
|
||||
my_key: Annotated[str, operator.add]
|
||||
|
||||
async def outer_1(state: State):
|
||||
await asyncio.sleep(0.2)
|
||||
await wait_until_streamed("inner_1")
|
||||
return {"my_key": " and parallel"}
|
||||
|
||||
async def outer_2(state: State):
|
||||
@@ -5184,34 +5189,22 @@ async def test_stream_subgraphs_during_execution(
|
||||
|
||||
app = graph.compile(checkpointer=async_checkpointer)
|
||||
|
||||
start = perf_counter()
|
||||
chunks: list[tuple[float, Any]] = []
|
||||
chunks: list[tuple[tuple[str, ...], dict[str, dict[str, str]]]] = []
|
||||
config = {"configurable": {"thread_id": "2"}}
|
||||
async for c in app.astream({"my_key": ""}, config, subgraphs=True):
|
||||
chunks.append((round(perf_counter() - start, 1), c))
|
||||
for idx in range(len(chunks)):
|
||||
elapsed, c = chunks[idx]
|
||||
chunks[idx] = (round(elapsed - chunks[0][0], 1), c)
|
||||
async for namespace, update in app.astream({"my_key": ""}, config, subgraphs=True):
|
||||
chunks.append((namespace, update))
|
||||
for node in update.keys() & streamed.keys():
|
||||
streamed[node].set()
|
||||
|
||||
assert chunks == [
|
||||
# arrives before "inner" finishes
|
||||
((AnyStr("inner:"),), {"inner_1": {"my_key": "got here", "my_other_key": ""}}),
|
||||
((), {"outer_1": {"my_key": " and parallel"}}),
|
||||
(
|
||||
FloatBetween(0.0, 0.1),
|
||||
(
|
||||
(AnyStr("inner:"),),
|
||||
{"inner_1": {"my_key": "got here", "my_other_key": ""}},
|
||||
),
|
||||
(AnyStr("inner:"),),
|
||||
{"inner_2": {"my_key": " and there", "my_other_key": "got here"}},
|
||||
),
|
||||
(FloatBetween(0.2, 0.4), ((), {"outer_1": {"my_key": " and parallel"}})),
|
||||
(
|
||||
FloatBetween(0.5, 0.8),
|
||||
(
|
||||
(AnyStr("inner:"),),
|
||||
{"inner_2": {"my_key": " and there", "my_other_key": "got here"}},
|
||||
),
|
||||
),
|
||||
(FloatBetween(0.5, 0.8), ((), {"inner": {"my_key": "got here and there"}})),
|
||||
(FloatBetween(0.5, 0.8), ((), {"outer_2": {"my_key": " and back again"}})),
|
||||
((), {"inner": {"my_key": "got here and there"}}),
|
||||
((), {"outer_2": {"my_key": " and back again"}}),
|
||||
]
|
||||
|
||||
|
||||
@@ -5222,10 +5215,12 @@ async def test_stream_buffering_single_node(
|
||||
class State(TypedDict):
|
||||
my_key: Annotated[str, operator.add]
|
||||
|
||||
received = asyncio.Event()
|
||||
|
||||
async def node(state: State, writer: StreamWriter):
|
||||
writer("Before sleep")
|
||||
await asyncio.sleep(0.2)
|
||||
writer("After sleep")
|
||||
writer("Before wait")
|
||||
await asyncio.wait_for(received.wait(), timeout=10)
|
||||
writer("After wait")
|
||||
return {"my_key": "got here"}
|
||||
|
||||
builder = StateGraph(State)
|
||||
@@ -5235,16 +5230,13 @@ async def test_stream_buffering_single_node(
|
||||
|
||||
graph = builder.compile(checkpointer=async_checkpointer)
|
||||
|
||||
start = perf_counter()
|
||||
chunks: list[tuple[float, Any]] = []
|
||||
config = {"configurable": {"thread_id": "2"}}
|
||||
async for c in graph.astream({"my_key": ""}, config, stream_mode="custom"):
|
||||
chunks.append((round(perf_counter() - start, 1), c))
|
||||
chunks: list[str] = []
|
||||
async for chunk in graph.astream({"my_key": ""}, config, stream_mode="custom"):
|
||||
chunks.append(chunk)
|
||||
received.set()
|
||||
|
||||
assert chunks == [
|
||||
(FloatBetween(0.0, 0.1), "Before sleep"),
|
||||
(FloatBetween(0.2, 0.3), "After sleep"),
|
||||
]
|
||||
assert chunks == ["Before wait", "After wait"]
|
||||
|
||||
|
||||
async def test_nested_graph_interrupts_parallel(
|
||||
|
||||
@@ -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, ...])
|
||||
|
||||
|
||||
|
||||
@@ -1,246 +0,0 @@
|
||||
import operator
|
||||
import sys
|
||||
from collections.abc import Callable
|
||||
from typing import Annotated, Any
|
||||
|
||||
import pytest
|
||||
from langchain_core.runnables import RunnableConfig, RunnableLambda
|
||||
from langgraph.checkpoint.memory import InMemorySaver
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from langgraph.channels.ephemeral_value import EphemeralValue
|
||||
from langgraph.channels.untracked_value import UntrackedValue
|
||||
from langgraph.config import read_state, write_state
|
||||
from langgraph.errors import InvalidUpdateError, NotInTaskError
|
||||
from langgraph.func import entrypoint
|
||||
from langgraph.graph import END, START, StateGraph
|
||||
from langgraph.types import Command, Overwrite, interrupt
|
||||
|
||||
pytestmark = pytest.mark.anyio
|
||||
|
||||
NEEDS_CONTEXTVARS = pytest.mark.skipif(
|
||||
sys.version_info < (3, 11),
|
||||
reason="Python 3.11+ is required for async contextvars support",
|
||||
)
|
||||
|
||||
|
||||
class State(TypedDict, total=False):
|
||||
one: str
|
||||
many: Annotated[list[int], operator.add]
|
||||
ephemeral: Annotated[str, EphemeralValue(str)]
|
||||
untracked: Annotated[str, UntrackedValue(str)]
|
||||
|
||||
|
||||
def run(node: Callable[..., Any], input: State | None = None) -> dict[str, Any]:
|
||||
graph = StateGraph(State).add_node("node", node).add_edge(START, "node").compile()
|
||||
return graph.invoke(input or {"many": [0]})
|
||||
|
||||
|
||||
def test_read_state_applies_the_nodes_own_updates() -> None:
|
||||
seen: dict[str, Any] = {}
|
||||
|
||||
def node(state: State) -> None:
|
||||
seen["start"] = read_state()
|
||||
write_state({"one": "a", "many": [1]})
|
||||
seen["all"] = read_state()
|
||||
seen["one"] = read_state("one")
|
||||
seen["both"] = read_state("one", "many")
|
||||
seen["input"] = dict(state)
|
||||
|
||||
assert run(node) == {"one": "a", "many": [0, 1]}
|
||||
assert seen == {
|
||||
"start": {"many": [0]},
|
||||
"all": {"one": "a", "many": [0, 1]},
|
||||
"one": {"one": "a"},
|
||||
"both": {"one": "a", "many": [0, 1]},
|
||||
"input": {"many": [0]},
|
||||
}
|
||||
|
||||
|
||||
def test_write_state_adds_to_the_update_the_node_returns() -> None:
|
||||
def node(state: State) -> State:
|
||||
write_state({"many": [1]})
|
||||
write_state({"many": [2]})
|
||||
return {"many": [3]}
|
||||
|
||||
assert run(node) == {"many": [0, 1, 2, 3]}
|
||||
|
||||
|
||||
@NEEDS_CONTEXTVARS
|
||||
async def test_an_async_node_finds_its_task_from_context() -> None:
|
||||
async def node(state: State) -> None:
|
||||
write_state({"one": "a"})
|
||||
assert read_state("one") == {"one": "a"}
|
||||
|
||||
graph = StateGraph(State).add_node("node", node).add_edge(START, "node").compile()
|
||||
assert await graph.ainvoke({"many": [0]}) == {"one": "a", "many": [0]}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("first", "second"),
|
||||
[
|
||||
({"one": "a"}, {"one": "b"}),
|
||||
({"many": Overwrite([1])}, {"many": Overwrite([2])}),
|
||||
({"ephemeral": "a"}, {"ephemeral": "b"}),
|
||||
({"untracked": "a"}, {"untracked": "b"}),
|
||||
],
|
||||
ids=["last-value", "overwrite", "ephemeral", "untracked"],
|
||||
)
|
||||
def test_write_state_rejects_a_second_value_for_a_one_value_key(
|
||||
first: dict[str, Any], second: dict[str, Any]
|
||||
) -> None:
|
||||
after: dict[str, Any] = {}
|
||||
|
||||
def node(state: State) -> None:
|
||||
write_state(first)
|
||||
before = read_state()
|
||||
with pytest.raises(InvalidUpdateError):
|
||||
write_state(second)
|
||||
after.update(unchanged=read_state() == before)
|
||||
|
||||
assert run(node) == run(lambda state: first)
|
||||
assert after == {"unchanged": True}
|
||||
|
||||
|
||||
def test_a_rejected_update_queues_none_of_its_keys() -> None:
|
||||
def node(state: State) -> None:
|
||||
write_state({"one": "a"})
|
||||
with pytest.raises(InvalidUpdateError):
|
||||
write_state({"many": [1], "one": "b"})
|
||||
|
||||
assert run(node) == {"one": "a", "many": [0]}
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"key", ["missing", "__pregel_tasks", "__start__", "branch:to:other"]
|
||||
)
|
||||
def test_write_state_rejects_a_key_that_is_not_state(key: str) -> None:
|
||||
ran: list[str] = []
|
||||
|
||||
def node(state: State) -> None:
|
||||
with pytest.raises(InvalidUpdateError, match="not a state key"):
|
||||
write_state({"many": [1], key: None})
|
||||
|
||||
graph = (
|
||||
StateGraph(State)
|
||||
.add_node("node", node)
|
||||
.add_node("other", lambda state: ran.append("other"))
|
||||
.add_edge(START, "node")
|
||||
.add_edge("other", END)
|
||||
.compile()
|
||||
)
|
||||
assert graph.invoke({"many": [0]}) == {"many": [0]}
|
||||
assert ran == []
|
||||
|
||||
|
||||
def test_read_state_returns_state_keys_only() -> None:
|
||||
seen: list[dict[str, Any]] = []
|
||||
|
||||
graph = (
|
||||
StateGraph(State)
|
||||
.add_node("a", lambda state: {"many": [1]})
|
||||
.add_node("b", lambda state: {"many": [2]})
|
||||
.add_node("joined", lambda state: seen.append(read_state()))
|
||||
.add_edge(START, "a")
|
||||
.add_edge(START, "b")
|
||||
.add_edge(["a", "b"], "joined")
|
||||
.compile()
|
||||
)
|
||||
graph.invoke({"many": [0]})
|
||||
assert [sorted(state) for state in seen] == [["many"]]
|
||||
|
||||
|
||||
def test_read_state_rejects_a_key_that_is_not_state() -> None:
|
||||
def node(state: State) -> None:
|
||||
for key in ("missing", "__start__", "branch:to:node"):
|
||||
with pytest.raises(KeyError, match="not a state key"):
|
||||
read_state(key)
|
||||
|
||||
assert run(node) == {"many": [0]}
|
||||
|
||||
|
||||
def test_a_state_key_may_contain_a_colon() -> None:
|
||||
Colon = TypedDict("Colon", {"user:name": str})
|
||||
|
||||
def node(state: Any) -> None:
|
||||
write_state({"user:name": "a"})
|
||||
assert read_state() == {"user:name": "a"}
|
||||
|
||||
graph = StateGraph(Colon).add_node("node", node).add_edge(START, "node").compile()
|
||||
assert graph.invoke({}) == {"user:name": "a"}
|
||||
|
||||
|
||||
def test_a_one_step_key_reads_as_unset_until_the_node_writes_it() -> None:
|
||||
seen: list[dict[str, Any]] = []
|
||||
|
||||
def node(state: State) -> None:
|
||||
seen.append(read_state("ephemeral"))
|
||||
write_state({"ephemeral": "b"})
|
||||
seen.append(read_state("ephemeral"))
|
||||
|
||||
run(node, {"ephemeral": "a"})
|
||||
assert seen == [{}, {"ephemeral": "b"}]
|
||||
|
||||
|
||||
def test_read_and_write_state_need_a_running_graph() -> None:
|
||||
with pytest.raises(NotInTaskError, match="read_state outside"):
|
||||
read_state()
|
||||
with pytest.raises(NotInTaskError, match="write_state outside"):
|
||||
write_state({"one": "a"})
|
||||
with pytest.raises(NotInTaskError):
|
||||
RunnableLambda(lambda _: read_state()).invoke(None)
|
||||
with pytest.raises(NotInTaskError):
|
||||
RunnableLambda(lambda _: write_state({"one": "a"})).invoke(None)
|
||||
|
||||
|
||||
def test_an_entrypoint_has_no_state_keys() -> None:
|
||||
@entrypoint()
|
||||
def workflow(value: int) -> dict[str, Any]:
|
||||
for key in (END, "__previous__"):
|
||||
with pytest.raises(InvalidUpdateError, match="not a state key"):
|
||||
write_state({key: value})
|
||||
return read_state()
|
||||
|
||||
assert workflow.invoke(1) == {}
|
||||
|
||||
|
||||
def test_updates_written_before_an_interrupt_apply_once_after_resume() -> None:
|
||||
def node(state: State) -> State:
|
||||
write_state({"many": [1]})
|
||||
answer = interrupt("ok?")
|
||||
write_state({"one": answer})
|
||||
return {"many": [2]}
|
||||
|
||||
graph = (
|
||||
StateGraph(State)
|
||||
.add_node("node", node)
|
||||
.add_edge(START, "node")
|
||||
.compile(checkpointer=InMemorySaver())
|
||||
)
|
||||
config: RunnableConfig = {"configurable": {"thread_id": "1"}}
|
||||
graph.invoke({"many": [0]}, config)
|
||||
assert graph.get_state(config).values == {"many": [0]}
|
||||
assert graph.invoke(Command(resume="yes"), config) == {
|
||||
"one": "yes",
|
||||
"many": [0, 1, 2],
|
||||
}
|
||||
|
||||
|
||||
def test_read_state_in_a_conditional_edge_during_update_state() -> None:
|
||||
seen: list[dict[str, Any]] = []
|
||||
|
||||
def route(state: State) -> str:
|
||||
seen.append(read_state("one"))
|
||||
return "end"
|
||||
|
||||
graph = (
|
||||
StateGraph(State)
|
||||
.add_node("node", lambda state: None)
|
||||
.add_edge(START, "node")
|
||||
.add_conditional_edges("node", route, {"end": "__end__"})
|
||||
.compile(checkpointer=InMemorySaver())
|
||||
)
|
||||
config: RunnableConfig = {"configurable": {"thread_id": "1"}}
|
||||
graph.invoke({"one": "a"}, config)
|
||||
graph.update_state(config, {"one": "b"}, as_node="node")
|
||||
assert seen == [{"one": "a"}, {"one": "b"}]
|
||||
@@ -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
|
||||
|
||||
Generated
+578
-409
File diff suppressed because it is too large.
Load diff
@@ -82,9 +82,9 @@ from langchain_core.tools.base import (
|
||||
_is_injected_arg_type,
|
||||
get_all_basemodel_annotations,
|
||||
)
|
||||
from langgraph._internal._constants import CONF, CONFIG_KEY_READ
|
||||
from langgraph._internal._runnable import RunnableCallable
|
||||
from langgraph.config import read_state
|
||||
from langgraph.errors import GraphBubbleUp, NotInTaskError
|
||||
from langgraph.errors import GraphBubbleUp
|
||||
from langgraph.graph.message import REMOVE_ALL_MESSAGES
|
||||
from langgraph.pregel._tools import _tool_call_writer
|
||||
from langgraph.runtime import ExecutionInfo, ServerInfo
|
||||
@@ -107,6 +107,12 @@ except ImportError: # `langgraph` before `is_invalid_resume` never marks resume
|
||||
return False
|
||||
|
||||
|
||||
try:
|
||||
from langgraph._internal._constants import CONFIG_KEY_READ_STATE
|
||||
except ImportError: # `langgraph` before `CONFIG_KEY_READ_STATE` never sets the key
|
||||
CONFIG_KEY_READ_STATE = "__pregel_read_state"
|
||||
|
||||
|
||||
# right now we use a dict as the default, can change this to AgentState, but depends
|
||||
# on if this lives in LangChain or LangGraph... ideally would have some typed
|
||||
# messages key
|
||||
@@ -1332,7 +1338,8 @@ class ToolNode(RunnableCallable):
|
||||
- `ToolCallWithContext` dict — legacy Send payload carrying an inlined
|
||||
state snapshot; return `input["state"]`.
|
||||
- list of `ToolCall` dicts — new Send payload with no inlined state;
|
||||
hydrate state from channels with `read_state`.
|
||||
read the state this node would get from an edge, coerced to its
|
||||
input schema (raw channel values on older `langgraph`).
|
||||
- regular graph state (dict/list/BaseModel) — return `input` as-is.
|
||||
"""
|
||||
if isinstance(input, dict) and input.get("__type") == "tool_call_with_context":
|
||||
@@ -1343,11 +1350,18 @@ class ToolNode(RunnableCallable):
|
||||
and isinstance(input[-1], dict)
|
||||
and input[-1].get("type") == "tool_call"
|
||||
):
|
||||
try:
|
||||
conf = config.get(CONF, {})
|
||||
if (read_state := conf.get(CONFIG_KEY_READ_STATE)) is not None:
|
||||
return read_state()
|
||||
except NotInTaskError:
|
||||
# not running in a graph, so there is no state to read
|
||||
read = conf.get(CONFIG_KEY_READ)
|
||||
if read is None:
|
||||
return {}
|
||||
# Pregel installs CONFIG_KEY_READ as
|
||||
# `functools.partial(local_read, scratchpad, channels, managed, task)`.
|
||||
# Match the previous inlined-state contract by reading channels only;
|
||||
# managed values have their own injection path (`ToolRuntime.context`).
|
||||
channels = read.args[1]
|
||||
return cast("dict[str, Any]", read(list(channels), True))
|
||||
return input
|
||||
|
||||
def _inject_tool_args(
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "langgraph-prebuilt"
|
||||
version = "1.1.2"
|
||||
version = "1.1.3"
|
||||
description = "Library with high-level APIs for creating and executing LangGraph agents and tools."
|
||||
authors = []
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"""Unit tests for tool call interceptor in ToolNode."""
|
||||
|
||||
import functools
|
||||
from collections.abc import Awaitable, Callable
|
||||
from dataclasses import replace
|
||||
from typing import Annotated
|
||||
@@ -9,10 +10,8 @@ import pytest
|
||||
from langchain_core.messages import AIMessage, ToolCall, ToolMessage
|
||||
from langchain_core.runnables import RunnableConfig
|
||||
from langchain_core.tools import tool
|
||||
from langgraph.graph import START, MessagesState, StateGraph
|
||||
from langgraph.graph.state import CompiledStateGraph
|
||||
from langgraph.store.base import BaseStore
|
||||
from langgraph.types import Command, Send
|
||||
from langgraph.types import Command
|
||||
|
||||
from langgraph.prebuilt.tool_node import (
|
||||
InjectedState,
|
||||
@@ -1326,59 +1325,53 @@ async def test_state_extraction_with_tool_call_with_context_async() -> None:
|
||||
assert "tool_call" not in state_seen[0]
|
||||
|
||||
|
||||
class _FilesState(MessagesState):
|
||||
files: dict[str, str]
|
||||
def _config_with_channel_read(
|
||||
channel_values: dict[str, object],
|
||||
store: BaseStore | None = None,
|
||||
) -> RunnableConfig:
|
||||
"""Build a config that mimics `CONFIG_KEY_READ` as Pregel installs it.
|
||||
|
||||
Pregel always installs a `functools.partial(local_read, scratchpad,
|
||||
channels, managed, task)`, and `ToolNode` introspects that partial to
|
||||
learn channel names. The stub matches the shape: partial whose second and
|
||||
third positional args are `channels` and `managed` mappings.
|
||||
"""
|
||||
|
||||
channels_stub = {k: None for k in channel_values}
|
||||
managed_stub: dict[str, object] = {}
|
||||
|
||||
# Shape matches pregel's real partial:
|
||||
# functools.partial(local_read, scratchpad, channels, managed, task)
|
||||
def _read(scratchpad, channels, managed, task, select, fresh):
|
||||
if isinstance(select, str):
|
||||
return channel_values[select]
|
||||
return {k: channel_values[k] for k in select if k in channel_values}
|
||||
|
||||
read = functools.partial(_read, None, channels_stub, managed_stub, None)
|
||||
cfg = _create_config_with_runtime(store)
|
||||
cfg["configurable"]["__pregel_read"] = read
|
||||
return cfg
|
||||
|
||||
|
||||
def _send_tool_call_graph(tool_node: ToolNode) -> CompiledStateGraph:
|
||||
"""A graph that reaches `tool_node` with `Send("tools", [tool_call])`."""
|
||||
tool_call: ToolCall = {
|
||||
"name": "add",
|
||||
"args": {"a": 1, "b": 2},
|
||||
"id": "call_1",
|
||||
"type": "tool_call",
|
||||
}
|
||||
return (
|
||||
StateGraph(_FilesState)
|
||||
.add_node("tools", tool_node)
|
||||
.add_conditional_edges(START, lambda _: [Send("tools", [tool_call])], ["tools"])
|
||||
.compile()
|
||||
)
|
||||
def test_list_form_send_hydrates_state_from_channel_read() -> None:
|
||||
"""Send('tools', [tool_call]) with no inlined state should hydrate
|
||||
ToolRuntime.state from CONFIG_KEY_READ (full state read)."""
|
||||
state_seen = []
|
||||
|
||||
|
||||
def _state_seen_by(tool_node_state: list[object]) -> ToolNode:
|
||||
def state_inspector_handler(
|
||||
request: ToolCallRequest,
|
||||
execute: Callable[[ToolCallRequest], ToolMessage | Command],
|
||||
) -> ToolMessage | Command:
|
||||
tool_node_state.append(request.state)
|
||||
state_seen.append(request.state)
|
||||
return execute(request)
|
||||
|
||||
return ToolNode([add], wrap_tool_call=state_inspector_handler)
|
||||
channel_values = {
|
||||
"messages": [AIMessage("from channels")],
|
||||
"files": {"/a.md": "body"},
|
||||
}
|
||||
|
||||
tool_node = ToolNode([add], wrap_tool_call=state_inspector_handler)
|
||||
|
||||
def test_list_form_send_hydrates_state_from_graph_state() -> None:
|
||||
"""Send('tools', [tool_call]) with no inlined state hydrates
|
||||
ToolRuntime.state with the full graph state."""
|
||||
state_seen: list[object] = []
|
||||
state = {"messages": [AIMessage("from channels", id="1")], "files": {"/a.md": "b"}}
|
||||
|
||||
_send_tool_call_graph(_state_seen_by(state_seen)).invoke(state)
|
||||
|
||||
assert state_seen == [state]
|
||||
|
||||
|
||||
async def test_list_form_send_hydrates_state_async() -> None:
|
||||
state_seen: list[object] = []
|
||||
state = {"messages": [AIMessage("from channels", id="1")], "files": {}}
|
||||
|
||||
await _send_tool_call_graph(_state_seen_by(state_seen)).ainvoke(state)
|
||||
|
||||
assert state_seen == [state]
|
||||
|
||||
|
||||
def test_list_form_send_outside_a_graph_has_empty_state() -> None:
|
||||
state_seen: list[object] = []
|
||||
tool_call: ToolCall = {
|
||||
"name": "add",
|
||||
"args": {"a": 1, "b": 2},
|
||||
@@ -1386,9 +1379,41 @@ def test_list_form_send_outside_a_graph_has_empty_state() -> None:
|
||||
"type": "tool_call",
|
||||
}
|
||||
|
||||
_state_seen_by(state_seen).invoke([tool_call], config=_create_config_with_runtime())
|
||||
tool_node.invoke([tool_call], config=_config_with_channel_read(channel_values))
|
||||
|
||||
assert state_seen == [{}]
|
||||
assert len(state_seen) == 1
|
||||
got = state_seen[0]
|
||||
assert got == channel_values
|
||||
assert "messages" in got and "files" in got
|
||||
|
||||
|
||||
async def test_list_form_send_hydrates_state_async() -> None:
|
||||
state_seen = []
|
||||
|
||||
def state_inspector_handler(
|
||||
request: ToolCallRequest,
|
||||
execute: Callable[[ToolCallRequest], ToolMessage | Command],
|
||||
) -> ToolMessage | Command:
|
||||
state_seen.append(request.state)
|
||||
return execute(request)
|
||||
|
||||
channel_values = {"messages": [AIMessage("from channels")], "files": {}}
|
||||
|
||||
tool_node = ToolNode([add], wrap_tool_call=state_inspector_handler)
|
||||
|
||||
tool_call: ToolCall = {
|
||||
"name": "add",
|
||||
"args": {"a": 1, "b": 2},
|
||||
"id": "call_1",
|
||||
"type": "tool_call",
|
||||
}
|
||||
|
||||
await tool_node.ainvoke(
|
||||
[tool_call], config=_config_with_channel_read(channel_values)
|
||||
)
|
||||
|
||||
assert len(state_seen) == 1
|
||||
assert state_seen[0] == channel_values
|
||||
|
||||
|
||||
def test_tool_call_request_is_frozen() -> None:
|
||||
|
||||
@@ -3,6 +3,7 @@ import dataclasses
|
||||
import json
|
||||
import sys
|
||||
import warnings
|
||||
from collections.abc import Callable
|
||||
from functools import partial
|
||||
from typing import (
|
||||
Annotated,
|
||||
@@ -1573,6 +1574,66 @@ def test_tool_node_inject_state(schema_: type[T]) -> None:
|
||||
assert tool_message.content == "hi?"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("schema_", _INJECTED_STATE_SCHEMAS)
|
||||
def test_tool_node_send_tool_call_gets_same_state_as_edge(schema_: type[T]) -> None:
|
||||
call = ToolCall(name="record", args={}, id="call_1", type="tool_call")
|
||||
seen: list[tuple[type, type]] = []
|
||||
|
||||
def record(runtime: ToolRuntime, state: Annotated[T, InjectedState]) -> str:
|
||||
"""Record the state types the tool gets."""
|
||||
seen.append((type(runtime.state), type(state)))
|
||||
return "ok"
|
||||
|
||||
def agent(state: Any) -> dict:
|
||||
return {"messages": [AIMessage("", tool_calls=[call])]}
|
||||
|
||||
def state_types(route: Callable[[Any], str | list[Send]]) -> tuple[type, type]:
|
||||
seen.clear()
|
||||
graph = (
|
||||
StateGraph(schema_)
|
||||
.add_node("agent", agent)
|
||||
.add_node("tools", ToolNode([record]))
|
||||
.add_edge(START, "agent")
|
||||
.add_conditional_edges("agent", route, ["tools"])
|
||||
.compile()
|
||||
)
|
||||
graph.invoke({"messages": [], "foo": "bar"})
|
||||
return seen[0]
|
||||
|
||||
by_send = state_types(lambda _: [Send("tools", [call])])
|
||||
by_edge = state_types(lambda _: "tools")
|
||||
assert by_send == by_edge
|
||||
|
||||
|
||||
def test_tool_node_in_graph_run_by_send_gets_that_graphs_state() -> None:
|
||||
call = ToolCall(name="record", args={}, id="call_1", type="tool_call")
|
||||
seen: list[Any] = []
|
||||
|
||||
def record(runtime: ToolRuntime) -> str:
|
||||
"""Record the state the tool gets."""
|
||||
seen.append(runtime.state)
|
||||
return "ok"
|
||||
|
||||
class State(TypedDict):
|
||||
value: str
|
||||
|
||||
def call_tools(state: State) -> dict:
|
||||
ToolNode([record]).invoke([call])
|
||||
return {}
|
||||
|
||||
inner = StateGraph(State).add_node(call_tools).add_edge(START, "call_tools")
|
||||
outer = (
|
||||
StateGraph(State)
|
||||
.add_node("inner", inner.compile())
|
||||
.add_conditional_edges(
|
||||
START, lambda _: [Send("inner", {"value": "inner"})], ["inner"]
|
||||
)
|
||||
.compile()
|
||||
)
|
||||
outer.invoke({"value": "outer"})
|
||||
assert seen == [{"value": "inner"}]
|
||||
|
||||
|
||||
def test_tool_node_inject_store() -> None:
|
||||
store = InMemoryStore()
|
||||
namespace = ("test",)
|
||||
|
||||
Generated
+4
-4
@@ -381,7 +381,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "langgraph"
|
||||
version = "1.2.22"
|
||||
version = "1.2.25"
|
||||
source = { editable = "../langgraph" }
|
||||
dependencies = [
|
||||
{ name = "langchain-core" },
|
||||
@@ -430,7 +430,7 @@ dev = [
|
||||
{ name = "syrupy" },
|
||||
{ name = "ty" },
|
||||
{ name = "types-requests" },
|
||||
{ name = "uvloop", specifier = "==0.22.1" },
|
||||
{ name = "uvloop", specifier = "==0.23.0" },
|
||||
]
|
||||
lint = [
|
||||
{ name = "ruff" },
|
||||
@@ -460,7 +460,7 @@ test = [
|
||||
{ name = "pytest-xdist", extras = ["psutil"] },
|
||||
{ name = "redis" },
|
||||
{ name = "syrupy" },
|
||||
{ name = "uvloop", specifier = "==0.22.1" },
|
||||
{ name = "uvloop", specifier = "==0.23.0" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -607,7 +607,7 @@ test = [
|
||||
|
||||
[[package]]
|
||||
name = "langgraph-prebuilt"
|
||||
version = "1.1.2"
|
||||
version = "1.1.3"
|
||||
source = { editable = "." }
|
||||
dependencies = [
|
||||
{ name = "langchain-core" },
|
||||
|
||||
@@ -13,8 +13,10 @@ Each node is designed to surface a specific v3 channel:
|
||||
- `subgraph` is a nested `StateGraph` invoked once so `thread.subgraphs` has
|
||||
exactly one direct child (`tasks` + `messages` under a namespace).
|
||||
|
||||
Extensions: every node calls `get_stream_writer()("progress", {...})` so
|
||||
`thread.extensions["progress"]` produces deterministic events.
|
||||
Extensions: every node writes `{"name": "progress", ...}` with
|
||||
`get_stream_writer()`, and `ProgressTransformer` relays the root-level ones
|
||||
onto a named `progress` channel, so `thread.extensions["progress"]` produces
|
||||
deterministic events.
|
||||
|
||||
No real LLM is used — message streaming is simulated by yielding a list of
|
||||
`AIMessageChunk`s from the node. This keeps the integration suite
|
||||
@@ -38,6 +40,7 @@ from langchain_core.tools import tool
|
||||
from langgraph.config import get_stream_writer
|
||||
from langgraph.graph import StateGraph
|
||||
from langgraph.graph.message import add_messages
|
||||
from langgraph.stream import ProtocolEvent, StreamChannel, StreamTransformer
|
||||
from langgraph.stream.transformers import CustomTransformer, UpdatesTransformer
|
||||
from langgraph.types import interrupt
|
||||
|
||||
@@ -272,6 +275,33 @@ def run_subgraph(state: AgentState) -> dict[str, Any]:
|
||||
}
|
||||
|
||||
|
||||
class ProgressTransformer(StreamTransformer):
|
||||
"""The server only routes named channels to `thread.extensions[name]`."""
|
||||
|
||||
required_stream_modes = ("custom",)
|
||||
|
||||
def __init__(self, scope: tuple[str, ...] = ()) -> None:
|
||||
super().__init__(scope)
|
||||
self._channel: StreamChannel[dict[str, Any]] = StreamChannel("progress")
|
||||
self._scope_list = list(scope)
|
||||
|
||||
def init(self) -> dict[str, Any]:
|
||||
return {"progress": self._channel}
|
||||
|
||||
def process(self, event: ProtocolEvent) -> bool:
|
||||
if event["method"] != "custom":
|
||||
return True
|
||||
params = event["params"]
|
||||
data = params["data"]
|
||||
if (
|
||||
params["namespace"] == self._scope_list
|
||||
and isinstance(data, dict)
|
||||
and data.get("name") == "progress"
|
||||
):
|
||||
self._channel.push(data)
|
||||
return True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Top-level graph
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -296,5 +326,5 @@ graph = _builder.compile(
|
||||
# auto-registered by the v3 mux for any graph that streams a chat
|
||||
# model. ``ValuesTransformer`` / ``LifecycleTransformer`` are also
|
||||
# always-on natives.
|
||||
transformers=[CustomTransformer, UpdatesTransformer],
|
||||
transformers=[CustomTransformer, UpdatesTransformer, ProgressTransformer],
|
||||
)
|
||||
@@ -1,7 +1,7 @@
|
||||
"""Exercise `thread.extensions[name]` against the integration API.
|
||||
|
||||
Every node in the example graph writes `("progress", {...})` via
|
||||
`get_stream_writer`. This script verifies the `extensions["progress"]`
|
||||
Every node in the example graph writes `{"name": "progress", ...}` via
|
||||
`get_stream_writer`, relayed onto the named `progress` channel. This script verifies the `extensions["progress"]`
|
||||
projection yields each progress event in order.
|
||||
"""
|
||||
|
||||
@@ -32,7 +32,7 @@ async def run_async() -> None:
|
||||
print(f" total progress events: {len(events)}")
|
||||
assert events, "expected at least one progress event"
|
||||
# Verify ordering covers the node sequence.
|
||||
steps = [e.get("step") for e in events]
|
||||
steps = [e["payload"]["step"] for e in events]
|
||||
print(f" step sequence: {steps}")
|
||||
finally:
|
||||
await raw.aclose()
|
||||
@@ -51,7 +51,7 @@ def run_sync() -> None:
|
||||
events.append(event)
|
||||
print(f" total progress events: {len(events)}")
|
||||
assert events, "expected at least one progress event"
|
||||
steps = [e.get("step") for e in events]
|
||||
steps = [e["payload"]["step"] for e in events]
|
||||
print(f" step sequence: {steps}")
|
||||
finally:
|
||||
raw.close()
|
||||
|
||||
@@ -28,7 +28,7 @@ async def test_extensions_async(async_threads) -> None:
|
||||
|
||||
# Iterator exits at the `ask_human` interrupt via `_signal_paused`,
|
||||
# so we capture exactly the pre-interrupt progress sequence.
|
||||
steps = [e.get("step") for e in events]
|
||||
steps = [e["payload"]["step"] for e in events]
|
||||
assert steps == _EXPECTED_PRE_INTERRUPT_STEPS, (
|
||||
f"unexpected step sequence: {steps}"
|
||||
)
|
||||
@@ -43,7 +43,7 @@ def test_extensions_sync(sync_threads) -> None:
|
||||
for event in thread.extensions["progress"]:
|
||||
events.append(event)
|
||||
|
||||
steps = [e.get("step") for e in events]
|
||||
steps = [e["payload"]["step"] for e in events]
|
||||
assert steps == _EXPECTED_PRE_INTERRUPT_STEPS, (
|
||||
f"unexpected step sequence: {steps}"
|
||||
)
|
||||
Generated
+4
-4
@@ -394,7 +394,7 @@ wheels = [
|
||||
|
||||
[[package]]
|
||||
name = "langgraph"
|
||||
version = "1.2.22"
|
||||
version = "1.2.25"
|
||||
source = { editable = "../langgraph" }
|
||||
dependencies = [
|
||||
{ name = "langchain-core" },
|
||||
@@ -443,7 +443,7 @@ dev = [
|
||||
{ name = "syrupy" },
|
||||
{ name = "ty" },
|
||||
{ name = "types-requests" },
|
||||
{ name = "uvloop", specifier = "==0.22.1" },
|
||||
{ name = "uvloop", specifier = "==0.23.0" },
|
||||
]
|
||||
lint = [
|
||||
{ name = "ruff" },
|
||||
@@ -473,7 +473,7 @@ test = [
|
||||
{ name = "pytest-xdist", extras = ["psutil"] },
|
||||
{ name = "redis" },
|
||||
{ name = "syrupy" },
|
||||
{ name = "uvloop", specifier = "==0.22.1" },
|
||||
{ name = "uvloop", specifier = "==0.23.0" },
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -526,7 +526,7 @@ test = [
|
||||
|
||||
[[package]]
|
||||
name = "langgraph-prebuilt"
|
||||
version = "1.1.2"
|
||||
version = "1.1.3"
|
||||
source = { editable = "../prebuilt" }
|
||||
dependencies = [
|
||||
{ name = "langchain-core" },
|
||||
|
||||
Reference in new issue
Block a user