Skip to content

The agent engineering platform.

feat(langchain): add opt-in per-call interrupts to HITL middleware (#41062)

Baihao Wangac2f5e355e74
diff --git a/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py b/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py
index 9584b645b2..a8955d6302 100644
--- a/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py
+++ b/libs/langchain_v1/langchain/agents/middleware/human_in_the_loop.py
@@ -4,12 +4,30 @@ from __future__ import annotations
import json
from dataclasses import replace
-from typing import TYPE_CHECKING, Annotated, Any, Literal, Protocol, cast
+from typing import (
+ TYPE_CHECKING,
+ Annotated,
+ Any,
+ Literal,
+ Protocol,
+ Union,
+ cast,
+ get_args,
+)
from langchain_core.messages import AIMessage, ToolCall, ToolMessage
from langgraph.config import get_config
from langgraph.prebuilt.tool_node import ToolRuntime
+from langgraph.runtime import get_runtime
from langgraph.types import Command, interrupt
+from pydantic import (
+ BaseModel,
+ Discriminator,
+ ValidatorFunctionWrapHandler,
+ WithJsonSchema,
+ WrapValidator,
+ create_model,
+)
from typing_extensions import NotRequired, TypedDict
from langchain.agents.middleware.types import (
@@ -23,8 +41,10 @@ from langchain.agents.middleware.types import (
)
if TYPE_CHECKING:
- from collections.abc import Awaitable, Callable
+ from collections.abc import Awaitable, Callable, Sequence
+ from langchain_core.runnables import RunnableConfig
+ from langchain_core.tools import BaseTool
from langgraph.runtime import Runtime
@@ -75,7 +95,11 @@ class ReviewConfig(TypedDict):
"""The decisions that are allowed for this request."""
args_schema: NotRequired[dict[str, Any]]
- """JSON schema for the args associated with the action, if edits are allowed."""
+ """Unused: the middleware doesn't set it.
+
+ In `per_call` mode the interrupt's `response_schema` shows the tool's own argument
+ schema instead.
+ """
class HITLRequest(TypedDict):
@@ -141,6 +165,125 @@ class RespondDecision(TypedDict):
Decision = ApproveDecision | EditDecision | RejectDecision | RespondDecision
+InterruptMode = Literal["batched", "per_call"]
+"""How HITL pauses: one interrupt per model turn (`batched`) or per gated tool call."""
+
+
+class ToolApprovalRequest(TypedDict):
+ """Interrupt value raised once per gated tool call in `per_call` mode.
+
+ Takes the place of `HITLRequest`. Answer it with a single `Decision`, keyed by the
+ interrupt's ID, not a `HITLResponse`. The interrupt's `response_schema` lists the
+ decisions allowed for the tool and, for edits, the tool's argument schema.
+ """
+
+ type: Literal["tool_approval"]
+ """Always `"tool_approval"`; tells clients how to read this interrupt."""
+
+ tool_call_id: str
+ """ID of the model's tool call this approval is about."""
+
+ name: str
+ """Tool name, as the model requested it."""
+
+ args: dict[str, Any]
+ """Tool arguments, as the model requested them."""
+
+ description: str
+ """Text shown to the reviewer."""
+
+
+def _edit_args(tool: BaseTool | None) -> object:
+ """What an edit's `args` must look like: the tool's Pydantic schema, if it has one.
+
+ That's the schema the model sees (`tool_call_schema`): it checks arg types and
+ required args. Args it doesn't declare pass through, and the tool ignores them as
+ it would from the model.
+ Validator methods on the tool's `args_schema` aren't part of it; they run when the
+ tool does.
+ A JSON-schema tool's schema is shown but not enforced, and with no tool any object
+ is accepted.
+ """
+ schema = tool.tool_call_schema if tool else None
+ if not (isinstance(schema, type) and issubclass(schema, BaseModel)):
+ shown = schema if isinstance(schema, dict) else {"type": "object"}
+ return Annotated[dict[str, Any], WithJsonSchema(shown)]
+ return schema
+
+
+def _as_sent(answer: object, check: ValidatorFunctionWrapHandler) -> object:
+ """Check `answer`, then pass it on as sent, so the tool validates its args once."""
+ check(answer)
+ return answer
+
+
+def _edit_decision(name: str, tool: BaseTool | None) -> object:
+ """`EditDecision` for one tool: `name` pinned to it, `args` from `_edit_args`."""
+ edited_action = create_model(
+ "EditedAction",
+ name=(Literal[name], ...),
+ args=(_edit_args(tool), ...),
+ )
+ decision = create_model(
+ "EditDecision",
+ type=(Literal["edit"], ...),
+ edited_action=(edited_action, ...),
+ )
+ return Annotated[decision, WrapValidator(_as_sent)]
+
+
+def _decision_schema(
+ allowed: Sequence[DecisionType], name: str, tool: BaseTool | None = None
+) -> type[Decision]:
+ """The per-call `response_schema`: today's decision types, limited to `allowed`.
+
+ The edit branch is built for this tool: its name is pinned, so an edit can't switch
+ tools, and its args follow the tool's own schema. An answer is checked only against
+ the branch its `type` names, so a bad one gets a single error about what's wrong.
+ A one-decision tool gets that decision's plain object schema.
+
+ Returns a type rather than a JSON schema because LangGraph checks answers only
+ against Python types; it publishes the type's JSON schema to clients.
+ """
+ by_type: dict[DecisionType, object] = {
+ "approve": ApproveDecision,
+ "reject": RejectDecision,
+ "respond": RespondDecision,
+ }
+ if "edit" in allowed:
+ by_type["edit"] = _edit_decision(name, tool)
+ # Drop duplicates, keeping order: a union of one type can't take a `Discriminator`.
+ members = tuple(by_type[d] for d in dict.fromkeys(allowed))
+ # Type checkers can't follow a type built at runtime. At runtime, `interrupt()` checks
+ # every answer against it, so what it returns is one of these decisions.
+ if len(members) == 1:
+ return cast("type[Decision]", members[0])
+ # Check only the branch the answer's `type` names, so a bad answer gets one precise
+ # error rather than one per branch.
+ return cast("type[Decision]", Annotated[Union[members], Discriminator("type")]) # noqa: UP007
+
+
+def _answer_message(tool_call: ToolCall, decision: RejectDecision | RespondDecision) -> ToolMessage:
+ """The message the model gets in place of the tool's result."""
+ if decision["type"] == "respond":
+ # Skip tool execution; the human answers on behalf of the tool.
+ content = decision["message"]
+ elif reason := decision.get("message"):
+ content = f"User rejected the tool call for `{tool_call['name']}` with reason: {reason}"
+ else:
+ content = (
+ f"User rejected the tool call for `{tool_call['name']}` with id "
+ f"{tool_call['id']}. The tool was not executed. Do not retry this tool "
+ "call unless the user explicitly requests it."
+ )
+ return ToolMessage(
+ content=content,
+ name=tool_call["name"],
+ tool_call_id=tool_call["id"],
+ status="success" if decision["type"] == "respond" else "error",
+ )
+
+
class HITLResponse(TypedDict):
"""Response payload for a HITLRequest."""
@@ -204,7 +347,11 @@ class InterruptOnConfig(TypedDict):
```
"""
args_schema: NotRequired[dict[str, Any]]
- """JSON schema for the args associated with the action, if edits are allowed."""
+ """Unused: the middleware doesn't send it to the reviewer in either mode.
+
+ In `per_call` mode the interrupt's `response_schema` shows the tool's own argument
+ schema instead.
+ """
when: NotRequired[Callable[[ToolCallRequest], bool]]
"""Optional predicate controlling whether to interrupt for a given tool call.
@@ -219,6 +366,15 @@ class InterruptOnConfig(TypedDict):
populated from the current tool call. The `tools` argument is not supplied,
so it uses its default empty list.
+ In `per_call` mode the predicate runs in `wrap_tool_call` and receives the real
+ `ToolCallRequest`, with `tool` and the tool's `ToolRuntime` set.
+
+ In both modes the predicate runs again when the run resumes, so it must return the
+ same answer for the same call. If it returns `False` on resume, the reviewer's
+ answer is skipped and the tool runs, even if they rejected it. In `batched` mode,
+ if it flips for only some of the reviewed calls, the decisions no longer line up
+ with the calls and resuming raises a `ValueError`.
+
Example:
```python
# Only interrupt delete_file calls targeting /etc
@@ -238,7 +394,95 @@ class _HumanInTheLoopState(AgentState[ResponseT]):
class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):
- """Human in the loop middleware."""
+ """Pause the agent so a person can review tool calls before they run.
+
+ Each tool in `interrupt_on` needs a decision before it runs: approve, edit, reject,
+ or respond. The pause is a LangGraph `interrupt`, so the agent needs a checkpointer,
+ and the run continues with `Command(resume=...)`.
+
+ `interrupt_mode` sets how the agent pauses:
+
+ - `"batched"` (default): one interrupt per model turn. Its value is a `HITLRequest`
+ listing every gated call, answered with a `HITLResponse` whose decisions match
+ the calls by position.
+ - `"per_call"`: one interrupt per gated tool call, as the call starts. Its value is
+ a `ToolApprovalRequest` and its `response_schema` lists the decisions that tool
+ allows. Each is answered with a single `Decision` keyed by interrupt ID, and
+ LangGraph checks the answer against the schema before saving it. `"per_call"`
+ is planned to become the default in the next major release.
+
+ Examples:
+ !!! example "Batched: one interrupt per model turn"
+
+ ```python
+ from langchain.agents import create_agent
+ from langchain.agents.middleware import HumanInTheLoopMiddleware
+ from langgraph.checkpoint.memory import InMemorySaver
+ from langgraph.types import Command
+
+ agent = create_agent(
+ model,
+ tools=[send_email, delete_file],
+ middleware=[
+ HumanInTheLoopMiddleware(interrupt_on={"send_email": True, "delete_file": True})
+ ],
+ checkpointer=InMemorySaver(),
+ )
+ config = {"configurable": {"thread_id": "1"}}
+ result = agent.invoke(
+ {"messages": [{"role": "user", "content": "Email Alice, then delete the report."}]},
+ config,
+ version="v2",
+ )
+ # One interrupt; `value["action_requests"]` lists send_email, then delete_file.
+ agent.invoke(
+ Command(
+ resume={
+ "decisions": [
+ {"type": "approve"},
+ {"type": "reject", "message": "Keep the report."},
+ ]
+ }
+ ),
+ config,
+ version="v2",
+ )
+ ```
+
+ !!! example "Per-call: one interrupt per gated tool call"
+
+ ```python
+ agent = create_agent(
+ model,
+ tools=[send_email, delete_file],
+ middleware=[
+ HumanInTheLoopMiddleware(
+ interrupt_on={
+ "send_email": True,
+ "delete_file": {"allowed_decisions": ["approve", "reject"]},
+ },
+ interrupt_mode="per_call",
+ )
+ ],
+ checkpointer=InMemorySaver(),
+ )
+ config = {"configurable": {"thread_id": "2"}}
+ result = agent.invoke(
+ {"messages": [{"role": "user", "content": "Email Alice, then delete the report."}]},
+ config,
+ version="v2",
+ )
+ # Two interrupts, each with `value["type"] == "tool_approval"` and its own
+ # `response_schema`. Answer each by its ID.
+ answers = {}
+ for interrupt in result.interrupts:
+ if interrupt.value["name"] == "delete_file":
+ answers[interrupt.id] = {"type": "reject", "message": "Keep the report."}
+ else:
+ answers[interrupt.id] = {"type": "approve"}
+ agent.invoke(Command(resume=answers), config, version="v2")
+ ```
+ """
state_schema = _HumanInTheLoopState # type: ignore[assignment]
@@ -248,6 +492,7 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):
*,
description_prefix: str = "Tool execution requires approval",
edit_notice: str | None = _EDIT_NOTICE,
+ interrupt_mode: InterruptMode = "batched",
) -> None:
"""Initialize the human in the loop middleware.
@@ -275,14 +520,61 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):
Not used if a tool has a `description` in its `InterruptOnConfig`.
edit_notice: Text prepended to the result of a tool call a reviewer replaced
via an `edit` decision. Pass `None` to add nothing.
+ interrupt_mode: How the agent pauses for review.
+
+ - `"batched"` (default): one interrupt per model turn for all gated
+ tool calls, answered with a `HITLResponse`.
+ - `"per_call"`: one `ToolApprovalRequest` interrupt per gated tool
+ call, with a typed `response_schema`, answered with a single
+ `Decision` keyed by interrupt ID.
+
+ In `per_call` mode, LangGraph checks each answer before saving it:
+
+ - An edit can't switch tools, and its args must match the tool's
+ argument types. Args the tool doesn't declare are ignored, as
+ they are when the model sends them.
+ Validator methods on the tool's `args_schema` run when the tool
+ does. For a tool whose arguments are a JSON schema rather than a
+ Pydantic model, edits are shown in `response_schema` but not
+ checked.
+ - An invalid answer raises `pydantic.ValidationError` and isn't
+ saved, so the same interrupt can be answered again.
+
+ !!! warning "Answering several calls at once"
+
+ If one of several answers sent together is invalid, the others'
+ tools may already have run even if they still show as pending,
+ and answering them again would run them twice. Check answers
+ against `response_schema` before sending them together, or send
+ one at a time.
+
+ !!! warning "Middleware order in `per_call` mode"
+
+ The review happens as the tool call starts, inside the tool-call
+ middleware chain. List this middleware before tool retry or
+ error-handling middleware so it wraps them, and don't enable it
+ on subclasses that raise their own interrupts in `after_model`.
+ On resume, each paused tool call runs the middleware listed
+ before this one again up to the pause, so that middleware must
+ not have side effects before calling `handler`. The tool itself
+ runs only after the answer.
+
+ As in `batched` mode, running the agent asynchronously (`ainvoke`,
+ `astream`) needs Python 3.11 or later.
Raises:
ValueError: If a tool's `InterruptOnConfig` does not have a non-empty
`allowed_decisions` list (e.g. a misspelled key or an empty list).
An interrupt config without decisions would otherwise be silently
dropped, disabling the approval gate for that tool.
+ Also if `interrupt_mode` is invalid.
"""
super().__init__()
+ if interrupt_mode not in (modes := get_args(InterruptMode)):
+ allowed = " or ".join(repr(mode) for mode in modes)
+ msg = f"`interrupt_mode` must be {allowed}, got {interrupt_mode!r}."
+ raise ValueError(msg)
+ self.interrupt_mode = interrupt_mode
self.edit_notice = edit_notice
resolved_configs: dict[str, InterruptOnConfig] = {}
for tool_name, tool_config in interrupt_on.items():
@@ -333,7 +625,6 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):
)
# Create ReviewConfig
- # eventually can get tool information and populate args_schema from there
review_config = ReviewConfig(
action_name=tool_name,
allowed_decisions=config["allowed_decisions"],
@@ -356,33 +647,10 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):
# Keep the model's own call in the message; `wrap_tool_call` substitutes the
# reviewer's at execution time.
return tool_call, None
- if decision["type"] == "reject" and "reject" in allowed_decisions:
- reason = decision.get("message")
- content = (
- f"User rejected the tool call for `{tool_call['name']}` with reason: {reason}"
- if reason
- else (
- f"User rejected the tool call for `{tool_call['name']}` with id "
- f"{tool_call['id']}. The tool was not executed. Do not retry this tool "
- "call unless the user explicitly requests it."
- )
- )
- tool_message = ToolMessage(
- content=content,
- name=tool_call["name"],
- tool_call_id=tool_call["id"],
- status="error",
- )
- return tool_call, tool_message
- if decision["type"] == "respond" and "respond" in allowed_decisions:
- # Skip tool execution; the human answers on behalf of the tool.
- tool_message = ToolMessage(
- content=decision["message"],
- name=tool_call["name"],
- tool_call_id=tool_call["id"],
- status="success",
- )
- return tool_call, tool_message
+ if decision["type"] in allowed_decisions and (
+ decision["type"] == "reject" or decision["type"] == "respond"
+ ):
+ return tool_call, _answer_message(tool_call, decision)
msg = (
f"Unexpected human decision: {decision}. "
f"Decision type '{decision.get('type')}' "
@@ -402,6 +670,7 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):
when = config.get("when")
if when is None:
return True
+ runnable_config: RunnableConfig
try:
runnable_config = get_config()
except RuntimeError:
@@ -424,6 +693,68 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):
)
return when(req)
+ def _tool_approval_request(
+ self, request: ToolCallRequest, config: InterruptOnConfig
+ ) -> ToolApprovalRequest:
+ """Build the per-call interrupt value for one gated tool call.
+
+ Raises:
+ ValueError: If the tool call has no ID. It can't run without one, so the
+ reviewer isn't asked to approve it.
+ """
+ tool_call = request.tool_call
+ tool_call_id = tool_call["id"]
+ # Only `None`: an empty ID still runs, so per-call keeps working where batched does.
+ if tool_call_id is None:
+ msg = (
+ f"Tool call `{tool_call['name']}` has no ID, so its result can't be matched "
+ "to it. Make sure the chat model returns tool call IDs."
+ )
+ raise ValueError(msg)
+ # A description factory gets the graph `Runtime`, as in batched mode.
+ runtime: Runtime[ContextT] = get_runtime()
+ action_request, _ = self._create_action_and_config(
+ tool_call, config, request.state, runtime
+ )
+ return ToolApprovalRequest(
+ type="tool_approval",
+ tool_call_id=tool_call_id,
+ name=tool_call["name"],
+ args=tool_call["args"],
+ description=action_request.get("description", ""),
+ )
+
+ def _resolve_per_call(
+ self, request: ToolCallRequest
+ ) -> tuple[ToolCallRequest, Action | None] | ToolMessage:
+ """Ask the reviewer about one tool call, if it's gated.
+
+ Returns the request to run, with the reviewer's call if they edited it, or the
+ message to return instead of running the tool.
+ """
+ tool_call = request.tool_call
+ config = self.interrupt_on.get(tool_call["name"])
+ if config is None:
+ return request, None
+ when = config.get("when")
+ if when is not None and not when(request):
+ return request, None
+
+ value = self._tool_approval_request(request, config)
+ response_schema = _decision_schema(
+ config["allowed_decisions"], tool_call["name"], request.tool
+ )
+ # LangGraph parses the answer against `response_schema` before saving it, so it
+ # comes back as one of this tool's allowed decisions.
+ decision = interrupt(value, response_schema=response_schema)
+ if decision["type"] == "approve":
+ return request, None
+ if decision["type"] == "edit":
+ # The schema pinned the tool name, so this is always the same tool.
+ executed = decision["edited_action"]
+ return self._apply_edit(request, executed), executed
+ return _answer_message(tool_call, decision)
+
def after_model(
self, state: AgentState[Any], runtime: Runtime[ContextT]
) -> dict[str, Any] | None:
@@ -440,6 +771,9 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):
ValueError: If the number of human decisions does not match the number of
interrupted tool calls.
"""
+ if self.interrupt_mode == "per_call":
+ # Interrupts are raised per tool call, in `wrap_tool_call`.
+ return None
messages = state["messages"]
if not messages:
return None
@@ -545,7 +879,8 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):
return None
edited = request.state.get(_EDITED_TOOL_CALLS_KEY) or {}
if tool_call_id in edited:
- return cast("Action", edited[tool_call_id])
+ executed: Action = edited[tool_call_id]
+ return executed
return None
def _apply_edit(self, request: ToolCallRequest, executed: Action) -> ToolCallRequest:
@@ -648,13 +983,27 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):
) -> ToolMessage | Command[Any]:
"""Prepend reviewer-edit guidance to the result of an edited tool call.
+ In `per_call` mode this is also where the interrupt is raised.
+
Args:
request: The tool call request being executed.
handler: Callable that executes the tool.
Returns:
The tool result, with a note prepended when a reviewer edited the call.
+
+ Raises:
+ ValidationError: In `per_call` mode, if the reviewer's answer doesn't match
+ the tool call's `response_schema`. Nothing is saved, so the call can be
+ answered again.
+ ValueError: In `per_call` mode, if a gated tool call has no ID.
"""
+ if self.interrupt_mode == "per_call":
+ resolved = self._resolve_per_call(request)
+ if isinstance(resolved, ToolMessage):
+ return resolved
+ to_run, executed = resolved
+ return self._annotate_edited_result(handler(to_run), to_run, executed)
executed = self._reviewer_edit(request)
if executed is not None:
request = self._apply_edit(request, executed)
@@ -667,13 +1016,27 @@ class HumanInTheLoopMiddleware(AgentMiddleware[StateT, ContextT, ResponseT]):
) -> ToolMessage | Command[Any]:
"""Async variant of `wrap_tool_call`.
+ In `per_call` mode this is also where the interrupt is raised.
+
Args:
request: The tool call request being executed.
handler: Awaitable callable that executes the tool.
Returns:
The tool result, with a note prepended when a reviewer edited the call.
+
+ Raises:
+ ValidationError: In `per_call` mode, if the reviewer's answer doesn't match
+ the tool call's `response_schema`. Nothing is saved, so the call can be
+ answered again.
+ ValueError: In `per_call` mode, if a gated tool call has no ID.
"""
+ if self.interrupt_mode == "per_call":
+ resolved = self._resolve_per_call(request)
+ if isinstance(resolved, ToolMessage):
+ return resolved
+ to_run, executed = resolved
+ return self._annotate_edited_result(await handler(to_run), to_run, executed)
executed = self._reviewer_edit(request)
if executed is not None:
request = self._apply_edit(request, executed)
diff --git a/libs/langchain_v1/pyproject.toml b/libs/langchain_v1/pyproject.toml
index 4980927c02..dd45403fa5 100644
--- a/libs/langchain_v1/pyproject.toml
+++ b/libs/langchain_v1/pyproject.toml
@@ -25,7 +25,7 @@ version = "1.4.5"
requires-python = ">=3.10.0,<4.0.0"
dependencies = [
"langchain-core>=1.6.10,<2.0.0",
- "langgraph>=1.2.11,<1.3.0",
+ "langgraph>=1.2.12,<1.3.0",
"pydantic>=2.7.4,<3.0.0",
]
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_internal_call_transformer.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_internal_call_transformer.py
index 7f6c8a5170..042cb7f323 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_internal_call_transformer.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_internal_call_transformer.py
@@ -103,7 +103,7 @@ def test_internal_call_transformer_not_registered_without_offending_middleware()
assert not any(isinstance(t, InternalCallTransformer) for t in transformers)
# Drain to close cleanly.
- list(run.tool_calls) # type: ignore[attr-defined]
+ list(run.tool_calls)
def test_internal_call_transformer_registered_before_messages_transformer() -> None:
@@ -131,7 +131,7 @@ def test_internal_call_transformer_registered_before_messages_transformer() -> N
)
# Drain to close cleanly.
- list(run.tool_calls) # type: ignore[attr-defined]
+ list(run.tool_calls)
def test_internal_call_transformer_deduped_across_middleware() -> None:
@@ -153,7 +153,7 @@ def test_internal_call_transformer_deduped_across_middleware() -> None:
assert sum(isinstance(t, InternalCallTransformer) for t in transformers) == 1
# Drain to close cleanly.
- list(run.tool_calls) # type: ignore[attr-defined]
+ list(run.tool_calls)
def test_internal_call_transformer_deduped_alongside_builtins() -> None:
@@ -176,7 +176,7 @@ def test_internal_call_transformer_deduped_alongside_builtins() -> None:
assert sum(isinstance(t, InternalCallTransformer) for t in transformers) == 1
# Drain to close cleanly.
- list(run.tool_calls) # type: ignore[attr-defined]
+ list(run.tool_calls)
def test_internal_call_transformer_dedup_accepts_unhashable_factories() -> None:
@@ -199,7 +199,7 @@ def test_internal_call_transformer_dedup_accepts_unhashable_factories() -> None:
)
run = agent.stream_events({"messages": [HumanMessage("hi")]}, version="v3")
- list(run.tool_calls) # type: ignore[attr-defined]
+ list(run.tool_calls)
def test_internal_model_calls_excluded_from_messages_projection_sync() -> None:
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_transformers.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_transformers.py
index 92c4c82713..adfd06ce01 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_transformers.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_transformers.py
@@ -68,7 +68,7 @@ def test_middleware_transformer_registered_on_compiled_graph() -> None:
assert "middleware_marker" in run._mux.extensions
# Drain to close the run cleanly.
- list(run.tool_calls) # type: ignore[attr-defined]
+ list(run.tool_calls)
def test_middleware_and_user_transformers_compose_in_order() -> None:
@@ -97,7 +97,7 @@ def test_middleware_and_user_transformers_compose_in_order() -> None:
"transformers must register as: built-in, then middleware, then user-supplied"
)
- list(run.tool_calls) # type: ignore[attr-defined]
+ list(run.tool_calls)
def test_transformers_from_multiple_middleware_preserve_middleware_order() -> None:
@@ -130,7 +130,7 @@ def test_transformers_from_multiple_middleware_preserve_middleware_order() -> No
idx_b = next(i for i, t in enumerate(transformers) if isinstance(t, _MarkerB))
assert idx_a < idx_b
- list(run.tool_calls) # type: ignore[attr-defined]
+ list(run.tool_calls)
def test_middleware_without_transformers_does_not_affect_registry() -> None:
@@ -146,4 +146,4 @@ def test_middleware_without_transformers_does_not_affect_registry() -> None:
assert any(isinstance(t, ToolCallTransformer) for t in transformers)
assert not any(isinstance(t, _MiddlewareMarker) for t in transformers)
- list(run.tool_calls) # type: ignore[attr-defined]
+ list(run.tool_calls)
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_human_in_the_loop.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_human_in_the_loop.py
index 9dd94fdb6f..13f8968f3f 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_human_in_the_loop.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_human_in_the_loop.py
@@ -1,26 +1,40 @@
import re
+import sys
from types import SimpleNamespace
-from typing import TYPE_CHECKING, Any
+from typing import TYPE_CHECKING, Annotated, Any, cast
from unittest.mock import patch
import pytest
from langchain_core.messages import AIMessage, HumanMessage, ToolCall, ToolMessage
-from langchain_core.tools import tool
+from langchain_core.tools import BaseTool, StructuredTool, tool
from langgraph.checkpoint.memory import InMemorySaver
+from langgraph.graph.state import CompiledStateGraph
from langgraph.prebuilt.tool_node import ToolNode, ToolRuntime
from langgraph.runtime import Runtime
from langgraph.types import Command
+from pydantic import AfterValidator, TypeAdapter, ValidationError
from langchain.agents.factory import _make_tools_to_model_edge, create_agent
-from langchain.agents.middleware import InterruptOnConfig
+from langchain.agents.middleware import InterruptOnConfig, ToolErrorMiddleware, ToolRetryMiddleware
from langchain.agents.middleware.human_in_the_loop import (
_EDIT_NOTICE,
_EDITED_TOOL_CALLS_KEY,
Action,
+ Decision,
+ DecisionType,
HumanInTheLoopMiddleware,
+ InterruptMode,
+ _decision_schema,
_HumanInTheLoopState,
)
-from langchain.agents.middleware.types import AgentState, ToolCallRequest
+from langchain.agents.middleware.types import (
+ AgentMiddleware,
+ AgentState,
+ ContextT,
+ InputAgentState,
+ OutputAgentState,
+ ToolCallRequest,
+)
from tests.unit_tests.agents.model import FakeToolCallingModel
if TYPE_CHECKING:
@@ -1067,10 +1081,8 @@ def test_when_predicate_batch_skips_interrupt_when_false() -> None:
)
state = AgentState[Any](messages=[HumanMessage(content="Hi"), ai_message])
- with (
- patch("langchain.agents.middleware.human_in_the_loop.get_config", return_value={}),
- patch("langchain.agents.middleware.human_in_the_loop.interrupt") as mock_interrupt,
- ):
+ # Called directly, outside a graph: there's no run config, and `when` still runs.
+ with patch("langchain.agents.middleware.human_in_the_loop.interrupt") as mock_interrupt:
result = middleware.after_model(state, Runtime())
mock_interrupt.assert_not_called()
@@ -1791,3 +1803,468 @@ def test_return_direct_routing_keeps_calls_with_unnamed_results() -> None:
]
assert edge({"messages": messages}) == "MODEL"
+
+
+# --- Per-call mode (interrupt_mode="per_call") ---
+
+
[email protected]("allowed", [["respond"], ["respond", "respond"]])
+def test_decision_schema_with_one_decision_is_a_plain_object(allowed: list[DecisionType]) -> None:
+ schema = TypeAdapter(_decision_schema(allowed, "send_email")).json_schema()
+ assert schema["properties"]["type"]["const"] == "respond"
+ assert schema["required"] == ["type", "message"]
+
+
+ ("answer", "loc", "error_type"),
+ [
+ ({"type": "edit"}, ("edit", "edited_action"), "missing"),
+ ({"type": "nope"}, (), "union_tag_invalid"),
+ (
+ {"type": "edit", "edited_action": {"name": "send_email", "args": {}}},
+ ("edit", "edited_action", "args", "to"),
+ "missing",
+ ),
+ (
+ {"type": "edit", "edited_action": {"name": "delete_file", "args": {"to": "b"}}},
+ ("edit", "edited_action", "name"),
+ "literal_error",
+ ),
+ ],
+)
+def test_decision_schema_rejects_a_bad_answer_with_one_error_at_the_problem(
+ answer: object, loc: tuple[str, ...], error_type: str
+) -> None:
+ @tool
+ def send_email(to: str, cc: str | None = None) -> str:
+ """Send an email."""
+ return f"sent to {to}, cc {cc}"
+
+ schema = _decision_schema(["approve", "edit", "reject", "respond"], "send_email", send_email)
+ with pytest.raises(ValidationError) as exc_info:
+ TypeAdapter(schema).validate_python(answer)
+ assert [(e["loc"], e["type"]) for e in exc_info.value.errors()] == [(loc, error_type)]
+
+
+ "tool",
+ [
+ None,
+ StructuredTool(
+ name="send_email",
+ description="d",
+ func=lambda **_: "sent",
+ args_schema={"type": "object", "properties": {"to": {"type": "string"}}},
+ ),
+ ],
+ ids=["no_tool", "json_schema_tool"],
+)
+def test_edit_args_without_a_pydantic_schema_are_shown_but_not_enforced(
+ tool: BaseTool | None,
+) -> None:
+ adapter = TypeAdapter(_decision_schema(["edit"], "send_email", tool))
+ assert adapter.json_schema()["$defs"]["EditedAction"]["properties"]["args"]["type"] == "object"
+ answer = {"type": "edit", "edited_action": {"name": "send_email", "args": {"to": 5}}}
+ assert adapter.validate_python(answer) == answer
+
+
+def test_middleware_checks_interrupt_mode() -> None:
+ assert HumanInTheLoopMiddleware(interrupt_on={"t": True}).interrupt_mode == "batched"
+ with pytest.raises(ValueError, match="must be 'batched' or 'per_call', got 'sometimes'"):
+ HumanInTheLoopMiddleware(
+ interrupt_on={"t": True}, interrupt_mode=cast("InterruptMode", "sometimes")
+ )
+
+
+def _agent(
+ tools: list[BaseTool],
+ tool_calls: list[ToolCall],
+ interrupt_on: dict[str, bool | InterruptOnConfig],
+ *after: AgentMiddleware,
+) -> CompiledStateGraph[AgentState[Any], None, InputAgentState, OutputAgentState[Any]]:
+ """An agent with per-call HITL whose model makes `tool_calls`, then finishes."""
+ return create_agent(
+ model=FakeToolCallingModel(tool_calls=[tool_calls, []]),
+ tools=tools,
+ middleware=[HumanInTheLoopMiddleware(interrupt_on, interrupt_mode="per_call"), *after],
+ checkpointer=InMemorySaver(),
+ )
+
+
+def test_per_call_interrupt_shows_the_call_and_the_answers_it_accepts() -> None:
+ @tool
+ def send_email(to: str) -> str:
+ """Send an email."""
+ return f"sent to {to}"
+
+ agent = _agent(
+ [send_email],
+ [ToolCall(name="send_email", args={"to": "alice"}, id="call_email")],
+ {
+ "send_email": {
+ "allowed_decisions": ["approve", "edit", "reject", "respond"],
+ "description": "Email",
+ # Not used in per-call mode: the edit's args come from the tool itself.
+ "args_schema": {"type": "object", "properties": {"recipient": {"type": "string"}}},
+ }
+ },
+ )
+ result = agent.invoke({"messages": [HumanMessage("go")]}, {"configurable": {"thread_id": "t"}})
+ [intr] = result["__interrupt__"]
+
+ # `value`: the tool call waiting for review.
+ assert intr.value == {
+ "type": "tool_approval",
+ "tool_call_id": "call_email",
+ "name": "send_email",
+ "args": {"to": "alice"},
+ "description": "Email",
+ }
+ # `response_schema`: one branch per allowed decision, matched on `type`.
+ schema = intr.response_schema
+ defs = schema["$defs"]
+ assert schema["oneOf"] == [
+ {"$ref": "#/$defs/ApproveDecision"},
+ {"$ref": "#/$defs/EditDecision"},
+ {"$ref": "#/$defs/RejectDecision"},
+ {"$ref": "#/$defs/RespondDecision"},
+ ]
+ assert defs["ApproveDecision"]["required"] == ["type"]
+ assert defs["EditDecision"]["required"] == ["type", "edited_action"]
+ assert defs["RejectDecision"]["required"] == ["type"] # `message` is optional
+ assert defs["RespondDecision"]["required"] == ["type", "message"]
+ # An edit names the same tool, and its args follow the tool's own schema.
+ edit, edited_action, args = defs["EditDecision"], defs["EditedAction"], defs["send_email"]
+ assert edit["properties"]["edited_action"] == {"$ref": "#/$defs/EditedAction"}
+ assert edited_action["properties"]["name"]["const"] == "send_email"
+ assert edited_action["properties"]["args"] == {"$ref": "#/$defs/send_email"}
+ assert (list(args["properties"]), args["required"]) == (["to"], ["to"])
+ assert args["description"] == "Send an email."
+
+
+ ("answer", "ran_with", "status", "content"),
+ [
+ ({"type": "approve"}, ["alice"], "success", "sent to alice"),
+ (
+ {"type": "edit", "edited_action": {"name": "send_email", "args": {"to": "bob"}}},
+ ["bob"],
+ "success",
+ "sent to bob",
+ ),
+ # The tool ignores an arg it doesn't declare, as it would from the model.
+ (
+ {
+ "type": "edit",
+ "edited_action": {"name": "send_email", "args": {"to": "bob", "subject": "hi"}},
+ },
+ ["bob"],
+ "success",
+ "sent to bob",
+ ),
+ (
+ {"type": "reject", "message": "not now"},
+ [],
+ "error",
+ "User rejected the tool call for `send_email` with reason: not now",
+ ),
+ ({"type": "respond", "message": "already sent"}, [], "success", "already sent"),
+ ],
+ ids=["approve", "edit", "edit-with-an-undeclared-arg", "reject", "respond"],
+)
+def test_per_call_resume_with_each_decision(
+ answer: Decision, ran_with: list[str], status: str, content: str
+) -> None:
+ ran: list[str] = []
+
+ @tool
+ def send_email(to: str) -> str:
+ """Send an email."""
+ ran.append(to)
+ return f"sent to {to}"
+
+ agent = _agent(
+ [send_email],
+ [ToolCall(name="send_email", args={"to": "alice"}, id="call_email")],
+ {"send_email": True},
+ )
+ config: RunnableConfig = {"configurable": {"thread_id": "t"}}
+ [intr] = agent.invoke({"messages": [HumanMessage("go")]}, config)["__interrupt__"]
+
+ final = agent.invoke(Command(resume={intr.id: answer}), config)
+
+ [message] = [m for m in final["messages"] if isinstance(m, ToolMessage)]
+ assert (ran, message.status) == (ran_with, status)
+ assert str(message.content).endswith(content)
+ # Only an edit tells the model that a reviewer replaced the call.
+ assert ("Executed instead: send_email" in str(message.content)) == (answer["type"] == "edit")
+
+
+def test_per_call_edit_leaves_validation_and_injected_args_to_the_tool() -> None:
+ @tool
+ def send_email(
+ to: Annotated[str, AfterValidator(lambda v: f"<{v}>")], runtime: ToolRuntime
+ ) -> str:
+ """Send an email."""
+ return f"sent to {to} for {runtime.tool_call_id}"
+
+ agent = _agent(
+ [send_email],
+ [ToolCall(name="send_email", args={"to": "alice"}, id="call_email")],
+ {"send_email": True},
+ )
+ config: RunnableConfig = {"configurable": {"thread_id": "t"}}
+ [intr] = agent.invoke({"messages": [HumanMessage("go")]}, config)["__interrupt__"]
+ # The reviewer edits only what the model sees; the tool validates the edit once and
+ # gets `runtime` injected.
+ assert list(intr.response_schema["$defs"]["send_email"]["properties"]) == ["to"]
+ edit = {"type": "edit", "edited_action": {"name": "send_email", "args": {"to": "bob"}}}
+ final = agent.invoke(Command(resume={intr.id: edit}), config)
+ [message] = [m for m in final["messages"] if isinstance(m, ToolMessage)]
+ assert str(message.content).endswith("sent to <bob> for call_email")
+
+
+def test_per_call_pauses_once_per_gated_call_and_applies_answers_by_id() -> None:
+ ran: list[str] = []
+
+ @tool
+ def send_email(to: str, cc: str | None = None) -> str:
+ """Send an email."""
+ ran.append(f"send_email(to={to}, cc={cc})")
+ return f"sent to {to}"
+
+ @tool
+ def delete_file(path: str) -> str:
+ """Delete a file."""
+ ran.append(f"delete_file({path})")
+ return f"deleted {path}"
+
+ @tool
+ def read_file(path: str) -> str:
+ """Read a file."""
+ ran.append(f"read_file({path})")
+ return f"contents of {path}"
+
+ calls = [
+ ToolCall(name="send_email", args={"to": "alice", "cc": "carol"}, id="call_email"),
+ ToolCall(name="delete_file", args={"path": "x.txt"}, id="call_delete"),
+ ToolCall(name="delete_file", args={"path": "tmp.txt"}, id="call_delete_tmp"),
+ ToolCall(name="read_file", args={"path": "y.txt"}, id="call_read"),
+ ]
+ agent = _agent(
+ [send_email, delete_file, read_file],
+ calls,
+ {
+ "send_email": True,
+ "delete_file": {
+ "allowed_decisions": ["approve", "reject"],
+ "when": lambda req: req.tool_call["args"]["path"] != "tmp.txt",
+ },
+ },
+ )
+ config: RunnableConfig = {"configurable": {"thread_id": "t"}}
+ paused = agent.invoke({"messages": [HumanMessage("go")]}, config)["__interrupt__"]
+ by_tool = {i.value["name"]: i for i in paused}
+ email, delete = by_tool["send_email"], by_tool["delete_file"]
+ assert (len(paused), delete.value["args"]) == (2, {"path": "x.txt"})
+ assert email.id != delete.id
+ # A call that isn't gated, or that `when` lets through, runs without waiting.
+ assert sorted(ran) == ["delete_file(tmp.txt)", "read_file(y.txt)"]
+
+ # Each interrupt accepts only its own tool's decisions.
+ assert delete.response_schema["oneOf"] == [
+ {"$ref": "#/$defs/ApproveDecision"},
+ {"$ref": "#/$defs/RejectDecision"},
+ ]
+ with pytest.raises(ValidationError, match="expected tags: 'approve', 'reject'"):
+ agent.invoke(Command(resume={delete.id: {"type": "respond", "message": "x"}}), config)
+
+ # The edit replaces the args: `cc` isn't carried over from the model's call.
+ edit = {"type": "edit", "edited_action": {"name": "send_email", "args": {"to": "bob"}}}
+ [pending] = agent.invoke(Command(resume={email.id: edit}), config)["__interrupt__"]
+ assert pending.id == delete.id
+
+ final = agent.invoke(
+ Command(resume={delete.id: {"type": "reject", "message": "keep it"}}), config
+ )
+ assert sorted(ran) == [ # nothing ran twice
+ "delete_file(tmp.txt)",
+ "read_file(y.txt)",
+ "send_email(to=bob, cc=None)",
+ ]
+ messages = {m.tool_call_id: m for m in final["messages"] if isinstance(m, ToolMessage)}
+ assert 'Executed instead: send_email with arguments {"to": "bob"}' in str(
+ messages["call_email"].content
+ )
+ assert messages["call_delete"].status == "error"
+ assert "keep it" in str(messages["call_delete"].content)
+ assert "__interrupt__" not in final
+
+
+ ("error", "after"),
+ [
+ (r"1 validation error for .*\nedit\.edited_action\n", []),
+ # Listed before error-handling middleware, HITL's error still reaches the caller.
+ (r"edit\.edited_action", [ToolRetryMiddleware(initial_delay=0)]),
+ (r"edit\.edited_action", [ToolErrorMiddleware(on_error=lambda *_: "x")]),
+ ],
+ ids=["hitl_alone", "hitl_wraps_retry", "hitl_wraps_tool_error"],
+)
+def test_per_call_rejects_a_bad_answer_without_saving_it(
+ error: str, after: list[AgentMiddleware]
+) -> None:
+ ran: list[str] = []
+
+ @tool
+ def send_email(to: str) -> str:
+ """Send an email."""
+ ran.append(to)
+ return f"sent to {to}"
+
+ agent = _agent(
+ [send_email],
+ [ToolCall(name="send_email", args={"to": "alice"}, id="call_email")],
+ {"send_email": True},
+ *after,
+ )
+ config: RunnableConfig = {"configurable": {"thread_id": "t"}}
+ [intr] = agent.invoke({"messages": [HumanMessage("go")]}, config)["__interrupt__"]
+
+ with pytest.raises(ValidationError, match=error):
+ agent.invoke(Command(resume={intr.id: {"type": "edit"}}), config)
+ assert ran == []
+
+ edit = {"type": "edit", "edited_action": {"name": "send_email", "args": {"to": "bob"}}}
+ final = agent.invoke(Command(resume={intr.id: edit}), config)
+ assert ran == ["bob"]
+ assert "__interrupt__" not in final
+
+
+def test_per_call_needs_a_tool_call_id() -> None:
+ @tool
+ def send_email(to: str) -> str:
+ """Send an email."""
+ return f"sent to {to}"
+
+ agent = _agent(
+ [send_email],
+ [ToolCall(name="send_email", args={"to": "alice"}, id=None)],
+ {"send_email": True},
+ )
+ with pytest.raises(ValueError, match="`send_email` has no ID"):
+ agent.invoke({"messages": [HumanMessage("go")]}, {"configurable": {"thread_id": "t"}})
+
+
+def test_per_call_description_factory_gets_the_graph_runtime() -> None:
+ seen: list[object] = []
+
+ @tool
+ def send_email(to: str) -> str:
+ """Send an email."""
+ return f"sent to {to}"
+
+ def describe(tool_call: ToolCall, state: AgentState[Any], runtime: Runtime[ContextT]) -> str:
+ seen.append(runtime)
+ return f"Email {tool_call['args']['to']}? ({len(state['messages'])} messages)"
+
+ config: InterruptOnConfig = {"allowed_decisions": ["approve"], "description": describe}
+ agent = _agent(
+ [send_email],
+ [ToolCall(name="send_email", args={"to": "alice"}, id="call_email")],
+ {"send_email": config},
+ )
+ result = agent.invoke({"messages": [HumanMessage("go")]}, {"configurable": {"thread_id": "t"}})
+ [intr] = result["__interrupt__"]
+
+ assert intr.value["description"] == "Email alice? (2 messages)"
+ assert seen
+ assert all(isinstance(runtime, Runtime) for runtime in seen) # as in batched mode
+
+
+def test_per_call_same_tool_twice_routes_each_answer_to_its_own_call() -> None:
+ ran: list[str] = []
+
+ @tool
+ def send_email(to: str) -> str:
+ """Send an email."""
+ ran.append(to)
+ return f"sent to {to}"
+
+ # An empty ID works too, as in batched mode.
+ calls = [ToolCall(name="send_email", args={"to": "alice"}, id=i) for i in ("e1", "")]
+ agent = _agent([send_email], calls, {"send_email": True})
+ config: RunnableConfig = {"configurable": {"thread_id": "t"}}
+ paused = agent.invoke({"messages": [HumanMessage("go")]}, config)["__interrupt__"]
+ by_call = {i.value["tool_call_id"]: i.id for i in paused}
+ assert set(by_call) == {"e1", ""}
+
+ answers = {by_call["e1"]: {"type": "approve"}, by_call[""]: {"type": "reject"}}
+ final = agent.invoke(Command(resume=answers), config)
+ assert ran == ["alice"]
+ messages = {m.tool_call_id: m for m in final["messages"] if isinstance(m, ToolMessage)}
+ assert messages[""].status == "error"
+
+
[email protected](sys.version_info < (3, 11), reason="Asyncio context vars require Python 3.11+")
+ ("answer", "status", "content"),
+ [
+ (
+ {"type": "edit", "edited_action": {"name": "send_email", "args": {"to": "bob"}}},
+ "success",
+ "sent to bob",
+ ),
+ ({"type": "reject"}, "error", "The tool was not executed."),
+ ],
+ ids=["edit", "reject"],
+)
+async def test_per_call_works_with_ainvoke(answer: Decision, status: str, content: str) -> None:
+ @tool
+ def send_email(to: str) -> str:
+ """Send an email."""
+ return f"sent to {to}"
+
+ agent = _agent(
+ [send_email],
+ [ToolCall(name="send_email", args={"to": "alice"}, id="call_email")],
+ {"send_email": True},
+ )
+ config: RunnableConfig = {"configurable": {"thread_id": "t"}}
+ [intr] = (await agent.ainvoke({"messages": [HumanMessage("go")]}, config))["__interrupt__"]
+
+ with pytest.raises(ValidationError, match=r"edit\.edited_action"):
+ await agent.ainvoke(Command(resume={intr.id: {"type": "edit"}}), config)
+ final = await agent.ainvoke(Command(resume={intr.id: answer}), config)
+
+ [message] = [m for m in final["messages"] if isinstance(m, ToolMessage)]
+ assert message.status == status
+ assert content in str(message.content)
+
+
+def test_per_call_retried_tool_is_not_reviewed_again_when_hitl_wraps_retry() -> None:
+ attempts: list[str] = []
+
+ @tool
+ def send_email(to: str) -> str:
+ """Send an email."""
+ attempts.append(to)
+ if len(attempts) == 1:
+ msg = "mail server unavailable"
+ raise RuntimeError(msg)
+ return f"sent to {to}"
+
+ agent = _agent(
+ [send_email],
+ [ToolCall(name="send_email", args={"to": "alice"}, id="call_email")],
+ {"send_email": True},
+ ToolRetryMiddleware(initial_delay=0),
+ )
+ config: RunnableConfig = {"configurable": {"thread_id": "t"}}
+ [intr] = agent.invoke({"messages": [HumanMessage("go")]}, config)["__interrupt__"]
+ final = agent.invoke(Command(resume={intr.id: {"type": "approve"}}), config)
+
+ assert "__interrupt__" not in final # the retry didn't ask the reviewer again
+ assert attempts == ["alice", "alice"]
+ [message] = [m for m in final["messages"] if isinstance(m, ToolMessage)]
+ assert message.content == "sent to alice"
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_pii.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_pii.py
index a86ed93164..dee46efc40 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_pii.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_pii.py
@@ -2062,7 +2062,7 @@ class TestPIIStreamTransformer:
)
# Drain to close cleanly.
- list(run.tool_calls) # type: ignore[attr-defined]
+ list(run.tool_calls)
class TestPIIStreamingEndToEnd:
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_agent_streaming.py b/libs/langchain_v1/tests/unit_tests/agents/test_agent_streaming.py
index 8ec53edcbe..a0b927ef3e 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_agent_streaming.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_agent_streaming.py
@@ -71,7 +71,7 @@ class TestAgentStreamV3Sync:
run = agent.stream_events({"messages": [HumanMessage("hi")]}, version="v3")
# Drain so the run closes cleanly.
- list(run.tool_calls) # type: ignore[attr-defined]
+ list(run.tool_calls)
def test_tool_calls_populated_without_opt_in(self) -> None:
"""`ToolCallTransformer` is registered by default on the agent streamer."""
@@ -80,7 +80,7 @@ class TestAgentStreamV3Sync:
run = agent.stream_events({"messages": [HumanMessage("hi")]}, version="v3")
- collected: list[ToolCallStream] = list(run.tool_calls) # type: ignore[attr-defined]
+ collected: list[ToolCallStream] = list(run.tool_calls)
assert len(collected) == 1
tc = collected[0]
assert tc.tool_name == "echo"
@@ -95,7 +95,7 @@ class TestAgentStreamV3Sync:
run = agent.stream_events({"messages": [HumanMessage("hi")]}, version="v3")
tool_calls: list[ToolCallStream] = []
- for tc in run.tool_calls: # type: ignore[attr-defined]
+ for tc in run.tool_calls:
tool_calls.append(tc)
assert list(tc.output_deltas) == ["one", "two"]
assert len(tool_calls) == 1
@@ -106,7 +106,7 @@ class TestAgentStreamV3Sync:
agent = create_agent(model, [])
run = agent.stream_events({"messages": [HumanMessage("hi")]}, version="v3")
- assert list(run.tool_calls) == [] # type: ignore[attr-defined]
+ assert list(run.tool_calls) == []
assert run.output is not None
def test_messages_projection_present(self) -> None:
@@ -122,7 +122,7 @@ class TestAgentStreamV3Sync:
assert "messages" in run._mux.extensions
assert hasattr(run, "messages")
# Drain so the run closes cleanly.
- for tc in run.tool_calls: # type: ignore[attr-defined]
+ for tc in run.tool_calls:
list(tc.output_deltas)
def test_caller_transformers_appended_not_replaced(self) -> None:
@@ -167,7 +167,7 @@ class TestAgentStreamV3Sync:
"ToolCallTransformer must be registered before user-supplied transformers"
)
- list(run.tool_calls) # type: ignore[attr-defined]
+ list(run.tool_calls)
def test_tool_error_sets_error_field(self) -> None:
"""Tool errors are surfaced on the `ToolCallStream.error` field.
@@ -184,7 +184,7 @@ class TestAgentStreamV3Sync:
collected: list[ToolCallStream] = []
def _drive() -> None:
- for tc in run.tool_calls: # type: ignore[attr-defined]
+ for tc in run.tool_calls:
collected.append(tc)
list(tc.output_deltas)
@@ -271,7 +271,7 @@ class TestAgentStreamV3Async:
agent = create_agent(model, [echo])
run = await agent.astream_events({"messages": [HumanMessage("hi")]}, version="v3")
- async for tc in run.tool_calls: # type: ignore[attr-defined]
+ async for tc in run.tool_calls:
async for _ in tc.output_deltas:
pass
@@ -283,7 +283,7 @@ class TestAgentStreamV3Async:
run = await agent.astream_events({"messages": [HumanMessage("hi")]}, version="v3")
collected: list[ToolCallStream] = []
- async for tc in run.tool_calls: # type: ignore[attr-defined]
+ async for tc in run.tool_calls:
collected.append(tc)
deltas = [d async for d in tc.output_deltas]
assert deltas == ["hi", "hi!"]
diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_subagent_transformer.py b/libs/langchain_v1/tests/unit_tests/agents/test_subagent_transformer.py
index e78f1c392d..bacc2a87dc 100644
--- a/libs/langchain_v1/tests/unit_tests/agents/test_subagent_transformer.py
+++ b/libs/langchain_v1/tests/unit_tests/agents/test_subagent_transformer.py
@@ -58,7 +58,7 @@ def test_subagents_surfaces_named_subagent() -> None:
run = supervisor.stream_events({"messages": [HumanMessage("weather?")]}, version="v3")
handles = []
- for handle in run.subagents: # type: ignore[attr-defined]
+ for handle in run.subagents:
handles.append(handle)
# Drain the nested run so it completes.
for _ in handle:
@@ -107,7 +107,7 @@ async def test_subagents_surfaces_named_subagent_async() -> None:
run = await supervisor.astream_events({"messages": [HumanMessage("weather?")]}, version="v3")
handles = []
- async for handle in run.subagents: # type: ignore[attr-defined]
+ async for handle in run.subagents:
handles.append(handle)
# Drain the nested run so it completes.
async for _ in handle:
@@ -136,7 +136,7 @@ def test_plain_tool_not_surfaced() -> None:
run = supervisor.stream_events({"messages": [HumanMessage("weather?")]}, version="v3")
- handles = list(run.subagents) # type: ignore[attr-defined]
+ handles = list(run.subagents)
# Drain the main run to completion.
for _ in run:
pass
@@ -172,7 +172,7 @@ def test_unnamed_inner_agent_surfaces_with_inherited_name() -> None:
run = supervisor.stream_events({"messages": [HumanMessage("weather?")]}, version="v3")
handles = []
- for handle in run.subagents: # type: ignore[attr-defined]
+ for handle in run.subagents:
handles.append(handle)
for _ in handle:
pass
@@ -210,7 +210,7 @@ def test_same_name_nested_agent_surfaced() -> None:
run = supervisor.stream_events({"messages": [HumanMessage("weather?")]}, version="v3")
handles = []
- for handle in run.subagents: # type: ignore[attr-defined]
+ for handle in run.subagents:
handles.append(handle)
for _ in handle:
pass
diff --git a/libs/langchain_v1/uv.lock b/libs/langchain_v1/uv.lock
index ba27e4f080..0f69de227c 100644
--- a/libs/langchain_v1/uv.lock
+++ b/libs/langchain_v1/uv.lock
@@ -2404,7 +2404,7 @@ requires-dist = [
{ name = "langchain-perplexity", marker = "extra == 'perplexity'" },
{ name = "langchain-together", marker = "extra == 'together'" },
{ name = "langchain-xai", marker = "extra == 'xai'" },
- { name = "langgraph", specifier = ">=1.2.11,<1.3.0" },
+ { name = "langgraph", specifier = ">=1.2.12,<1.3.0" },
{ name = "pydantic", specifier = ">=2.7.4,<3.0.0" },
]
provides-extras = ["community", "anthropic", "openai", "azure-ai", "google-vertexai", "google-genai", "fireworks", "ollama", "together", "mistralai", "huggingface", "groq", "aws", "baseten", "deepseek", "xai", "perplexity", "meta", "mcp"]
@@ -2996,7 +2996,7 @@ wheels = [
[[package]]
name = "langgraph"
-version = "1.2.11"
+version = "1.2.13"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "langchain-core" },
@@ -3006,9 +3006,9 @@ dependencies = [
{ name = "pydantic" },
{ name = "xxhash" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/56/0d/c8e7ee98896659e1b6555db0ab115a9ca899844744645d5d894032bab1d7/langgraph-1.2.11.tar.gz", hash = "sha256:9ecfe11e50d338b34b15cf4d8a442642de103e8ae6971320efba84e4542eb363", size = 725753, upload-time = "2026-08-11T14:00:36.945Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/c3/22/75ab5e7d13c842d8dc68f115cf6cc5a651a8d5a993e72a621c98bfb2b1cd/langgraph-1.2.13.tar.gz", hash = "sha256:a3cae71d4cb88455d7a8887109665525aefe4ab13fe941d653cd4b6de2af45c6", size = 752793, upload-time = "2026-10-05T17:51:21.566Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/0a/7f/c5c30e4be99ff821029c7ac872a480676bb179c9f3df85ea3f38d13f86d4/langgraph-1.2.11-py3-none-any.whl", hash = "sha256:8bab70de7b2d00b5300fb289bcf38d8b241400f3184c1e95e8ce706fb0e8686b", size = 248854, upload-time = "2026-08-11T14:00:35.494Z" },
+ { url = "https://files.pythonhosted.org/packages/da/8e/b7471af7fc72c218e545c74454c386a4b0867a8a15c9893db1d28464f492/langgraph-1.2.13-py3-none-any.whl", hash = "sha256:5d45a021e043aaf39f32122e620eacfd1245aa84dfaa84b0814cef0f4ac78eb4", size = 255979, upload-time = "2026-10-05T17:51:20.221Z" },
]
[[package]]