The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
feat(langchain): use decorators for jumps instead (#33179)
Sydney Runklea336afaecd61
diff --git a/libs/langchain_v1/langchain/agents/middleware/__init__.py b/libs/langchain_v1/langchain/agents/middleware/__init__.pyindex 5dd4eea993..89923b47f0 100644--- a/libs/langchain_v1/langchain/agents/middleware/__init__.py+++ b/libs/langchain_v1/langchain/agents/middleware/__init__.py@@ -10,6 +10,7 @@ from .types import (ModelRequest,after_model,before_model,+ hook_config,modify_model_request,)@@ -24,5 +25,6 @@ __all__ = ["SummarizationMiddleware","after_model","before_model",+ "hook_config","modify_model_request",]diff --git a/libs/langchain_v1/langchain/agents/middleware/types.py b/libs/langchain_v1/langchain/agents/middleware/types.pyindex 35ca31342c..48b38c6d2b 100644--- a/libs/langchain_v1/langchain/agents/middleware/types.py+++ b/libs/langchain_v1/langchain/agents/middleware/types.py@@ -2,13 +2,13 @@from __future__ import annotations+from collections.abc import Callablefrom dataclasses import dataclass, fieldfrom inspect import iscoroutinefunctionfrom typing import (TYPE_CHECKING,Annotated,Any,- ClassVar,Generic,Literal,Protocol,@@ -30,8 +30,6 @@ from langgraph.typing import ContextTfrom typing_extensions import NotRequired, Required, TypedDict, TypeVarif TYPE_CHECKING:- from collections.abc import Callable-from langchain_core.language_models.chat_models import BaseChatModelfrom langchain_core.tools import BaseToolfrom langgraph.runtime import Runtime@@ -46,6 +44,7 @@ __all__ = ["ModelRequest","OmitFromSchema","PublicAgentState",+ "hook_config",]JumpTo = Literal["tools", "model", "end"]@@ -123,12 +122,6 @@ class AgentMiddleware(Generic[StateT, ContextT]):tools: list[BaseTool]"""Additional tools registered by the middleware."""- before_model_jump_to: ClassVar[list[JumpTo]] = []- """Valid jump destinations for before_model hook. Used to establish conditional edges."""-- after_model_jump_to: ClassVar[list[JumpTo]] = []- """Valid jump destinations for after_model hook. Used to establish conditional edges."""-def before_model(self, state: StateT, runtime: Runtime[ContextT]) -> dict[str, Any] | None:"""Logic to run before the model is called."""@@ -184,6 +177,57 @@ class _CallableWithModelRequestAndStateAndRuntime(Protocol[StateT_contra, Contex...+CallableT = TypeVar("CallableT", bound=Callable[..., Any])+++def hook_config(+ *,+ can_jump_to: list[JumpTo] | None = None,+) -> Callable[[CallableT], CallableT]:+ """Decorator to configure hook behavior in middleware methods.++ Use this decorator on `before_model` or `after_model` methods in middleware classes+ to configure their behavior. Currently supports specifying which destinations they+ can jump to, which establishes conditional edges in the agent graph.++ Args:+ can_jump_to: Optional list of valid jump destinations. Can be:+ - "tools": Jump to the tools node+ - "model": Jump back to the model node+ - "end": Jump to the end of the graph++ Returns:+ Decorator function that marks the method with configuration metadata.++ Examples:+ Using decorator on a class method:+ ```python+ class MyMiddleware(AgentMiddleware):+ @hook_config(can_jump_to=["end", "model"])+ def before_model(self, state: AgentState) -> dict[str, Any] | None:+ if some_condition(state):+ return {"jump_to": "end"}+ return None+ ```++ Alternative: Use the `can_jump_to` parameter in `before_model`/`after_model` decorators:+ ```python+ @before_model(can_jump_to=["end"])+ def conditional_middleware(state: AgentState) -> dict[str, Any] | None:+ if should_exit(state):+ return {"jump_to": "end"}+ return None+ ```+ """++ def decorator(func: CallableT) -> CallableT:+ if can_jump_to is not None:+ func.__can_jump_to__ = can_jump_to # type: ignore[attr-defined]+ return func++ return decorator++@overloaddef before_model(func: _CallableWithStateAndRuntime[StateT, ContextT],@@ -196,7 +240,7 @@ def before_model(*,state_schema: type[StateT] | None = None,tools: list[BaseTool] | None = None,- jump_to: list[JumpTo] | None = None,+ can_jump_to: list[JumpTo] | None = None,name: str | None = None,) -> Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]@@ -208,7 +252,7 @@ def before_model(*,state_schema: type[StateT] | None = None,tools: list[BaseTool] | None = None,- jump_to: list[JumpTo] | None = None,+ can_jump_to: list[JumpTo] | None = None,name: str | None = None,) -> (Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]@@ -222,7 +266,7 @@ def before_model(state_schema: Optional custom state schema type. If not provided, uses the defaultAgentState schema.tools: Optional list of additional tools to register with this middleware.- jump_to: Optional list of valid jump destinations for conditional edges.+ can_jump_to: Optional list of valid jump destinations for conditional edges.Valid values are: "tools", "model", "end"name: Optional name for the generated middleware class. If not provided,uses the decorated function's name.@@ -246,7 +290,7 @@ def before_model(With conditional jumping:```python- @before_model(jump_to=["end"])+ @before_model(can_jump_to=["end"])def conditional_before_model(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:if some_condition(state):return {"jump_to": "end"}@@ -266,6 +310,10 @@ def before_model() -> AgentMiddleware[StateT, ContextT]:is_async = iscoroutinefunction(func)+ func_can_jump_to = (+ can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])+ )+if is_async:async def async_wrapped(@@ -275,6 +323,10 @@ def before_model() -> dict[str, Any] | Command | None:return await func(state, runtime) # type: ignore[misc]+ # Preserve can_jump_to metadata on the wrapped function+ if func_can_jump_to:+ async_wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]+middleware_name = name or cast("str", getattr(func, "__name__", "BeforeModelMiddleware"))@@ -285,7 +337,6 @@ def before_model({"state_schema": state_schema or AgentState,"tools": tools or [],- "before_model_jump_to": jump_to or [],"abefore_model": async_wrapped,},)()@@ -297,6 +348,11 @@ def before_model() -> dict[str, Any] | Command | None:return func(state, runtime) # type: ignore[return-value]+ # Preserve can_jump_to metadata on the wrapped function+ if func_can_jump_to:+ wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]++ # Use function name as default if no name providedmiddleware_name = name or cast("str", getattr(func, "__name__", "BeforeModelMiddleware"))return type(@@ -305,7 +361,6 @@ def before_model({"state_schema": state_schema or AgentState,"tools": tools or [],- "before_model_jump_to": jump_to or [],"before_model": wrapped,},)()@@ -464,7 +519,7 @@ def after_model(*,state_schema: type[StateT] | None = None,tools: list[BaseTool] | None = None,- jump_to: list[JumpTo] | None = None,+ can_jump_to: list[JumpTo] | None = None,name: str | None = None,) -> Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]@@ -476,7 +531,7 @@ def after_model(*,state_schema: type[StateT] | None = None,tools: list[BaseTool] | None = None,- jump_to: list[JumpTo] | None = None,+ can_jump_to: list[JumpTo] | None = None,name: str | None = None,) -> (Callable[[_CallableWithStateAndRuntime[StateT, ContextT]], AgentMiddleware[StateT, ContextT]]@@ -490,7 +545,7 @@ def after_model(state_schema: Optional custom state schema type. If not provided, uses the defaultAgentState schema.tools: Optional list of additional tools to register with this middleware.- jump_to: Optional list of valid jump destinations for conditional edges.+ can_jump_to: Optional list of valid jump destinations for conditional edges.Valid values are: "tools", "model", "end"name: Optional name for the generated middleware class. If not provided,uses the decorated function's name.@@ -524,6 +579,10 @@ def after_model(func: _CallableWithStateAndRuntime[StateT, ContextT],) -> AgentMiddleware[StateT, ContextT]:is_async = iscoroutinefunction(func)+ # Extract can_jump_to from decorator parameter or from function metadata+ func_can_jump_to = (+ can_jump_to if can_jump_to is not None else getattr(func, "__can_jump_to__", [])+ )if is_async:@@ -534,6 +593,10 @@ def after_model() -> dict[str, Any] | Command | None:return await func(state, runtime) # type: ignore[misc]+ # Preserve can_jump_to metadata on the wrapped function+ if func_can_jump_to:+ async_wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]+middleware_name = name or cast("str", getattr(func, "__name__", "AfterModelMiddleware"))return type(@@ -542,7 +605,6 @@ def after_model({"state_schema": state_schema or AgentState,"tools": tools or [],- "after_model_jump_to": jump_to or [],"aafter_model": async_wrapped,},)()@@ -554,6 +616,11 @@ def after_model() -> dict[str, Any] | Command | None:return func(state, runtime) # type: ignore[return-value]+ # Preserve can_jump_to metadata on the wrapped function+ if func_can_jump_to:+ wrapped.__can_jump_to__ = func_can_jump_to # type: ignore[attr-defined]++ # Use function name as default if no name providedmiddleware_name = name or cast("str", getattr(func, "__name__", "AfterModelMiddleware"))return type(@@ -562,7 +629,6 @@ def after_model({"state_schema": state_schema or AgentState,"tools": tools or [],- "after_model_jump_to": jump_to or [],"after_model": wrapped,},)()diff --git a/libs/langchain_v1/langchain/agents/middleware_agent.py b/libs/langchain_v1/langchain/agents/middleware_agent.pyindex f8494263bc..ce752aefb6 100644--- a/libs/langchain_v1/langchain/agents/middleware_agent.py+++ b/libs/langchain_v1/langchain/agents/middleware_agent.py@@ -85,6 +85,41 @@ def _extract_metadata(type_: type) -> list:return []+def _get_can_jump_to(middleware: AgentMiddleware[Any, Any], hook_name: str) -> list[JumpTo]:+ """Get the can_jump_to list from either sync or async hook methods.++ Args:+ middleware: The middleware instance to inspect.+ hook_name: The name of the hook ('before_model' or 'after_model').++ Returns:+ List of jump destinations, or empty list if not configured.+ """+ # Get the base class method for comparison+ base_sync_method = getattr(AgentMiddleware, hook_name, None)+ base_async_method = getattr(AgentMiddleware, f"a{hook_name}", None)++ # Try sync method first - only if it's overridden from base class+ sync_method = getattr(middleware.__class__, hook_name, None)+ if (+ sync_method+ and sync_method is not base_sync_method+ and hasattr(sync_method, "__can_jump_to__")+ ):+ return sync_method.__can_jump_to__++ # Try async method - only if it's overridden from base class+ async_method = getattr(middleware.__class__, f"a{hook_name}", None)+ if (+ async_method+ and async_method is not base_async_method+ and hasattr(async_method, "__can_jump_to__")+ ):+ return async_method.__can_jump_to__++ return []++def _supports_native_structured_output(model: str | BaseChatModel) -> bool:"""Check if a model supports native structured output."""model_name: str | None = None@@ -511,13 +546,13 @@ def create_agent( # noqa: PLR0915# If no tools, just go to END from modelgraph.add_edge(last_node, END)else:- # If after_model, then need to check for jump_to+ # If after_model, then need to check for can_jump_to_add_middleware_edge(graph,f"{middleware_w_after[0].__class__.__name__}.after_model",END,first_node,- jump_to=middleware_w_after[0].after_model_jump_to,+ can_jump_to=_get_can_jump_to(middleware_w_after[0], "after_model"),)# Add middleware edges (same as before)@@ -528,7 +563,7 @@ def create_agent( # noqa: PLR0915f"{m1.__class__.__name__}.before_model",f"{m2.__class__.__name__}.before_model",first_node,- jump_to=m1.before_model_jump_to,+ can_jump_to=_get_can_jump_to(m1, "before_model"),)# Go directly to model_request after the last before_model_add_middleware_edge(@@ -536,7 +571,7 @@ def create_agent( # noqa: PLR0915f"{middleware_w_before[-1].__class__.__name__}.before_model","model_request",first_node,- jump_to=middleware_w_before[-1].before_model_jump_to,+ can_jump_to=_get_can_jump_to(middleware_w_before[-1], "before_model"),)if middleware_w_after:@@ -549,7 +584,7 @@ def create_agent( # noqa: PLR0915f"{m1.__class__.__name__}.after_model",f"{m2.__class__.__name__}.after_model",first_node,- jump_to=m1.after_model_jump_to,+ can_jump_to=_get_can_jump_to(m1, "after_model"),)return graph@@ -643,7 +678,7 @@ def _add_middleware_edge(name: str,default_destination: str,model_destination: str,- jump_to: list[JumpTo] | None,+ can_jump_to: list[JumpTo] | None,) -> None:"""Add an edge to the graph for a middleware node.@@ -653,20 +688,20 @@ def _add_middleware_edge(name: The name of the middleware node.default_destination: The default destination for the edge.model_destination: The destination for the edge to the model.- jump_to: The conditionally jumpable destinations for the edge.+ can_jump_to: The conditionally jumpable destinations for the edge."""- if jump_to:+ if can_jump_to:def jump_edge(state: dict[str, Any]) -> str:return _resolve_jump(state.get("jump_to"), model_destination) or default_destinationdestinations = [default_destination]- if "end" in jump_to:+ if "end" in can_jump_to:destinations.append(END)- if "tools" in jump_to:+ if "tools" in can_jump_to:destinations.append("tools")- if "model" in jump_to and name != model_destination:+ if "model" in can_jump_to and name != model_destination:destinations.append(model_destination)graph.add_conditional_edges(name, jump_edge, destinations)diff --git a/libs/langchain_v1/tests/unit_tests/agents/__snapshots__/test_middleware_decorators.ambr b/libs/langchain_v1/tests/unit_tests/agents/__snapshots__/test_middleware_decorators.ambrnew file mode 100644index 0000000000..efdd8216a6--- /dev/null+++ b/libs/langchain_v1/tests/unit_tests/agents/__snapshots__/test_middleware_decorators.ambr@@ -0,0 +1,95 @@+# serializer version: 1+# name: test_async_middleware_with_can_jump_to_graph_snapshot+ '''+ ---+ config:+ flowchart:+ curve: linear+ ---+ graph TD;+ __start__([<p>__start__</p>]):::first+ model_request(model_request)+ async_before_with_jump\2ebefore_model(async_before_with_jump.before_model)+ __end__([<p>__end__</p>]):::last+ __start__ --> async_before_with_jump\2ebefore_model;+ async_before_with_jump\2ebefore_model -.-> __end__;+ async_before_with_jump\2ebefore_model -.-> model_request;+ model_request --> __end__;+ classDef default fill:#f2f0ff,line-height:1.2+ classDef first fill-opacity:0+ classDef last fill:#bfb6fc++ '''+# ---+# name: test_async_middleware_with_can_jump_to_graph_snapshot.1+ '''+ ---+ config:+ flowchart:+ curve: linear+ ---+ graph TD;+ __start__([<p>__start__</p>]):::first+ model_request(model_request)+ async_after_with_jump\2eafter_model(async_after_with_jump.after_model)+ __end__([<p>__end__</p>]):::last+ __start__ --> model_request;+ async_after_with_jump\2eafter_model -.-> __end__;+ async_after_with_jump\2eafter_model -.-> model_request;+ model_request --> async_after_with_jump\2eafter_model;+ classDef default fill:#f2f0ff,line-height:1.2+ classDef first fill-opacity:0+ classDef last fill:#bfb6fc++ '''+# ---+# name: test_async_middleware_with_can_jump_to_graph_snapshot.2+ '''+ ---+ config:+ flowchart:+ curve: linear+ ---+ graph TD;+ __start__([<p>__start__</p>]):::first+ model_request(model_request)+ async_before_early_exit\2ebefore_model(async_before_early_exit.before_model)+ async_after_retry\2eafter_model(async_after_retry.after_model)+ __end__([<p>__end__</p>]):::last+ __start__ --> async_before_early_exit\2ebefore_model;+ async_after_retry\2eafter_model -.-> __end__;+ async_after_retry\2eafter_model -.-> async_before_early_exit\2ebefore_model;+ async_before_early_exit\2ebefore_model -.-> __end__;+ async_before_early_exit\2ebefore_model -.-> model_request;+ model_request --> async_after_retry\2eafter_model;+ classDef default fill:#f2f0ff,line-height:1.2+ classDef first fill-opacity:0+ classDef last fill:#bfb6fc++ '''+# ---+# name: test_async_middleware_with_can_jump_to_graph_snapshot.3+ '''+ ---+ config:+ flowchart:+ curve: linear+ ---+ graph TD;+ __start__([<p>__start__</p>]):::first+ model_request(model_request)+ sync_before_with_jump\2ebefore_model(sync_before_with_jump.before_model)+ async_after_with_jumps\2eafter_model(async_after_with_jumps.after_model)+ __end__([<p>__end__</p>]):::last+ __start__ --> sync_before_with_jump\2ebefore_model;+ async_after_with_jumps\2eafter_model -.-> __end__;+ async_after_with_jumps\2eafter_model -.-> sync_before_with_jump\2ebefore_model;+ model_request --> async_after_with_jumps\2eafter_model;+ sync_before_with_jump\2ebefore_model -.-> __end__;+ sync_before_with_jump\2ebefore_model -.-> model_request;+ classDef default fill:#f2f0ff,line-height:1.2+ classDef first fill-opacity:0+ classDef last fill:#bfb6fc++ '''+# ---diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_middleware_agent.py b/libs/langchain_v1/tests/unit_tests/agents/test_middleware_agent.pyindex 3febca2e98..451849b977 100644--- a/libs/langchain_v1/tests/unit_tests/agents/test_middleware_agent.py+++ b/libs/langchain_v1/tests/unit_tests/agents/test_middleware_agent.py@@ -41,6 +41,7 @@ from langchain.agents.middleware.summarization import SummarizationMiddlewarefrom langchain.agents.middleware.types import (AgentMiddleware,AgentState,+ hook_config,ModelRequest,OmitFromInput,OmitFromOutput,@@ -340,8 +341,7 @@ def test_create_agent_jump(calls.append("NoopSeven.after_model")class NoopEight(AgentMiddleware):- before_model_jump_to = ["end"]-+ @hook_config(can_jump_to=["end"])def before_model(self, state, runtime) -> dict[str, Any]:calls.append("NoopEight.before_model")return {"jump_to": "end"}@@ -1777,15 +1777,22 @@ async def test_create_agent_async_jump() -> None:calls.append("AsyncMiddlewareOne.abefore_model")class AsyncMiddlewareTwo(AgentMiddleware):- before_model_jump_to = ["end"]-+ @hook_config(can_jump_to=["end"])async def abefore_model(self, state, runtime) -> dict[str, Any]:calls.append("AsyncMiddlewareTwo.abefore_model")return {"jump_to": "end"}+ @tool+ def my_tool(input: str) -> str:+ """A great tool"""+ calls.append("my_tool")+ return input.upper()+agent = create_agent(- model=FakeToolCallingModel(),- tools=[],+ model=FakeToolCallingModel(+ tool_calls=[[ToolCall(id="1", name="my_tool", args={"input": "yo"})]],+ ),+ tools=[my_tool],system_prompt="You are a helpful assistant.",middleware=[AsyncMiddlewareOne(), AsyncMiddlewareTwo()],).compile()diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_middleware_decorators.py b/libs/langchain_v1/tests/unit_tests/agents/test_middleware_decorators.pyindex ec8607ab19..535bd9bfae 100644--- a/libs/langchain_v1/tests/unit_tests/agents/test_middleware_decorators.py+++ b/libs/langchain_v1/tests/unit_tests/agents/test_middleware_decorators.py@@ -3,6 +3,7 @@import pytestfrom typing import Anyfrom typing_extensions import NotRequired+from syrupy.assertion import SnapshotAssertionfrom langchain_core.messages import HumanMessage, AIMessagefrom langchain_core.tools import tool@@ -16,8 +17,9 @@ from langchain.agents.middleware.types import (before_model,after_model,modify_model_request,+ hook_config,)-from langchain.agents.middleware_agent import create_agent+from langchain.agents.middleware_agent import create_agent, _get_can_jump_tofrom .model import FakeToolCallingModel@@ -37,19 +39,19 @@ def test_before_model_decorator() -> None:"""Test before_model decorator with all configuration options."""@before_model(- state_schema=CustomState, tools=[test_tool], jump_to=["__end__"], name="CustomBeforeModel"+ state_schema=CustomState, tools=[test_tool], can_jump_to=["end"], name="CustomBeforeModel")def custom_before_model(state: CustomState, runtime: Runtime) -> dict[str, Any]:- return {"jump_to": "__end__"}+ return {"jump_to": "end"}assert isinstance(custom_before_model, AgentMiddleware)assert custom_before_model.state_schema == CustomStateassert custom_before_model.tools == [test_tool]- assert custom_before_model.before_model_jump_to == ["__end__"]+ assert getattr(custom_before_model.__class__.before_model, "__can_jump_to__", []) == ["end"]assert custom_before_model.__class__.__name__ == "CustomBeforeModel"result = custom_before_model.before_model({"messages": [HumanMessage("Hello")]}, None)- assert result == {"jump_to": "__end__"}+ assert result == {"jump_to": "end"}def test_after_model_decorator() -> None:@@ -58,7 +60,7 @@ def test_after_model_decorator() -> None:@after_model(state_schema=CustomState,tools=[test_tool],- jump_to=["model", "__end__"],+ can_jump_to=["model", "end"],name="CustomAfterModel",)def custom_after_model(state: CustomState, runtime: Runtime) -> dict[str, Any]:@@ -68,7 +70,10 @@ def test_after_model_decorator() -> None:assert isinstance(custom_after_model, AgentMiddleware)assert custom_after_model.state_schema == CustomStateassert custom_after_model.tools == [test_tool]- assert custom_after_model.after_model_jump_to == ["model", "__end__"]+ assert getattr(custom_after_model.__class__.after_model, "__can_jump_to__", []) == [+ "model",+ "end",+ ]assert custom_after_model.__class__.__name__ == "CustomAfterModel"# Verify it works@@ -158,6 +163,82 @@ def test_decorators_use_function_names_as_default() -> None:assert my_after_hook.__class__.__name__ == "my_after_hook"+def test_hook_config_decorator_on_class_method() -> None:+ """Test hook_config decorator on AgentMiddleware class methods."""++ class JumpMiddleware(AgentMiddleware):+ @hook_config(can_jump_to=["end", "model"])+ def before_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ if len(state["messages"]) > 5:+ return {"jump_to": "end"}+ return None++ @hook_config(can_jump_to=["tools"])+ def after_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ return {"jump_to": "tools"}++ # Verify can_jump_to metadata is preserved+ assert getattr(JumpMiddleware.before_model, "__can_jump_to__", []) == ["end", "model"]+ assert getattr(JumpMiddleware.after_model, "__can_jump_to__", []) == ["tools"]+++def test_can_jump_to_with_before_model_decorator() -> None:+ """Test can_jump_to parameter used with before_model decorator."""++ @before_model(can_jump_to=["end"])+ def conditional_before(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ if len(state["messages"]) > 3:+ return {"jump_to": "end"}+ return None++ # Verify middleware was created and has can_jump_to metadata+ assert isinstance(conditional_before, AgentMiddleware)+ assert getattr(conditional_before.__class__.before_model, "__can_jump_to__", []) == ["end"]+++def test_can_jump_to_with_after_model_decorator() -> None:+ """Test can_jump_to parameter used with after_model decorator."""++ @after_model(can_jump_to=["model", "end"])+ def conditional_after(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ if state["messages"][-1].content == "retry":+ return {"jump_to": "model"}+ return None++ # Verify middleware was created and has can_jump_to metadata+ assert isinstance(conditional_after, AgentMiddleware)+ assert getattr(conditional_after.__class__.after_model, "__can_jump_to__", []) == [+ "model",+ "end",+ ]+++def test_can_jump_to_integration() -> None:+ """Test can_jump_to parameter in a full agent."""+ calls = []++ @before_model(can_jump_to=["end"])+ def early_exit(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ calls.append("early_exit")+ if state["messages"][0].content == "exit":+ return {"jump_to": "end"}+ return None++ agent = create_agent(model=FakeToolCallingModel(), middleware=[early_exit])+ agent = agent.compile()++ # Test with early exit+ result = agent.invoke({"messages": [HumanMessage("exit")]})+ assert calls == ["early_exit"]+ assert len(result["messages"]) == 1++ # Test without early exit+ calls.clear()+ result = agent.invoke({"messages": [HumanMessage("hello")]})+ assert calls == ["early_exit"]+ assert len(result["messages"]) > 1++# Async Decorator Tests@@ -324,3 +405,170 @@ async def test_mixed_sync_async_decorators_integration() -> None:"sync_after","async_after",]+++def test_async_before_model_preserves_can_jump_to() -> None:+ """Test that can_jump_to metadata is preserved for async before_model functions."""++ @before_model(can_jump_to=["end"])+ async def async_conditional_before(+ state: AgentState, runtime: Runtime+ ) -> dict[str, Any] | None:+ if len(state["messages"]) > 3:+ return {"jump_to": "end"}+ return None++ # Verify middleware was created and has can_jump_to metadata+ assert isinstance(async_conditional_before, AgentMiddleware)+ assert getattr(async_conditional_before.__class__.abefore_model, "__can_jump_to__", []) == [+ "end"+ ]+++def test_async_after_model_preserves_can_jump_to() -> None:+ """Test that can_jump_to metadata is preserved for async after_model functions."""++ @after_model(can_jump_to=["model", "end"])+ async def async_conditional_after(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ if state["messages"][-1].content == "retry":+ return {"jump_to": "model"}+ return None++ # Verify middleware was created and has can_jump_to metadata+ assert isinstance(async_conditional_after, AgentMiddleware)+ assert getattr(async_conditional_after.__class__.aafter_model, "__can_jump_to__", []) == [+ "model",+ "end",+ ]+++async def test_async_can_jump_to_integration() -> None:+ """Test can_jump_to parameter in a full agent with async middleware."""+ calls = []++ @before_model(can_jump_to=["end"])+ async def async_early_exit(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ calls.append("async_early_exit")+ if state["messages"][0].content == "exit":+ return {"jump_to": "end"}+ return None++ agent = create_agent(model=FakeToolCallingModel(), middleware=[async_early_exit])+ agent = agent.compile()++ # Test with early exit+ result = await agent.ainvoke({"messages": [HumanMessage("exit")]})+ assert calls == ["async_early_exit"]+ assert len(result["messages"]) == 1++ # Test without early exit+ calls.clear()+ result = await agent.ainvoke({"messages": [HumanMessage("hello")]})+ assert calls == ["async_early_exit"]+ assert len(result["messages"]) > 1+++def test_get_can_jump_to_no_false_positives() -> None:+ """Test that _get_can_jump_to doesn't return false positives for base class methods."""++ # Middleware with no overridden methods should return empty list+ class EmptyMiddleware(AgentMiddleware):+ pass++ empty_middleware = EmptyMiddleware()+ empty_middleware.tools = []++ # Should not return any jump destinations for base class methods+ assert _get_can_jump_to(empty_middleware, "before_model") == []+ assert _get_can_jump_to(empty_middleware, "after_model") == []+++def test_get_can_jump_to_only_overridden_methods() -> None:+ """Test that _get_can_jump_to only checks overridden methods."""++ # Middleware with only sync method overridden+ class SyncOnlyMiddleware(AgentMiddleware):+ @hook_config(can_jump_to=["end"])+ def before_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ return None++ sync_middleware = SyncOnlyMiddleware()+ sync_middleware.tools = []++ # Should return can_jump_to from overridden sync method+ assert _get_can_jump_to(sync_middleware, "before_model") == ["end"]++ # Middleware with only async method overridden+ class AsyncOnlyMiddleware(AgentMiddleware):+ @hook_config(can_jump_to=["model"])+ async def aafter_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ return None++ async_middleware = AsyncOnlyMiddleware()+ async_middleware.tools = []++ # Should return can_jump_to from overridden async method+ assert _get_can_jump_to(async_middleware, "after_model") == ["model"]+++def test_async_middleware_with_can_jump_to_graph_snapshot(snapshot: SnapshotAssertion) -> None:+ """Test that async middleware with can_jump_to creates correct graph structure with conditional edges."""++ # Test 1: Async before_model with can_jump_to+ @before_model(can_jump_to=["end"])+ async def async_before_with_jump(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ if len(state["messages"]) > 5:+ return {"jump_to": "end"}+ return None++ agent_async_before = create_agent(+ model=FakeToolCallingModel(), middleware=[async_before_with_jump]+ )++ assert agent_async_before.compile().get_graph().draw_mermaid() == snapshot++ # Test 2: Async after_model with can_jump_to+ @after_model(can_jump_to=["model", "end"])+ async def async_after_with_jump(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ if state["messages"][-1].content == "retry":+ return {"jump_to": "model"}+ return None++ agent_async_after = create_agent(+ model=FakeToolCallingModel(), middleware=[async_after_with_jump]+ )++ assert agent_async_after.compile().get_graph().draw_mermaid() == snapshot++ # Test 3: Multiple async middleware with can_jump_to+ @before_model(can_jump_to=["end"])+ async def async_before_early_exit(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ return None++ @after_model(can_jump_to=["model"])+ async def async_after_retry(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ return None++ agent_multiple_async = create_agent(+ model=FakeToolCallingModel(),+ middleware=[async_before_early_exit, async_after_retry],+ )++ assert agent_multiple_async.compile().get_graph().draw_mermaid() == snapshot++ # Test 4: Mixed sync and async middleware with can_jump_to+ @before_model(can_jump_to=["end"])+ def sync_before_with_jump(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ return None++ @after_model(can_jump_to=["model", "end"])+ async def async_after_with_jumps(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ return None++ agent_mixed = create_agent(+ model=FakeToolCallingModel(),+ middleware=[sync_before_with_jump, async_after_with_jumps],+ )++ assert agent_mixed.compile().get_graph().draw_mermaid() == snapshotdiff --git a/libs/langchain_v1/uv.lock b/libs/langchain_v1/uv.lockindex ee5b71b0e1..2c1f500f3a 100644--- a/libs/langchain_v1/uv.lock+++ b/libs/langchain_v1/uv.lock@@ -2261,7 +2261,7 @@ wheels = [[[package]]name = "langchain-openai"-version = "0.3.33"+version = "0.3.34"source = { editable = "../partners/openai" }dependencies = [{ name = "langchain-core" },@@ -2272,7 +2272,7 @@ dependencies = [[package.metadata]requires-dist = [{ name = "langchain-core", editable = "../core" },- { name = "openai", specifier = ">=1.104.2,<2.0.0" },+ { name = "openai", specifier = ">=1.104.2,<3.0.0" },{ name = "tiktoken", specifier = ">=0.7.0,<1.0.0" },]