The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
chore(langchain): fix types in test_decorators (#34583)
Christophe Bornet3b659855518a
diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_decorators.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_decorators.pyindex 22901d5848..a68f9b44d7 100644--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_decorators.py+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/core/test_decorators.py@@ -1,11 +1,19 @@"""Consolidated tests for middleware decorators: before_model, after_model, and wrap_model_call."""-from typing import Any+from collections.abc import Awaitable, Callable+from typing import Any, Genericimport pytest-from langchain_core.messages import AIMessage, HumanMessage+from langchain_core.messages import (+ AIMessage,+ HumanMessage,+ SystemMessage,+ ToolMessage,+)from langchain_core.tools import tool+from langgraph.prebuilt.tool_node import ToolCallRequestfrom langgraph.runtime import Runtime+from langgraph.types import Commandfrom syrupy.assertion import SnapshotAssertionfrom typing_extensions import NotRequired@@ -13,7 +21,10 @@ from langchain.agents.factory import _get_can_jump_to, create_agentfrom langchain.agents.middleware.types import (AgentMiddleware,AgentState,+ ModelCallResult,ModelRequest,+ ModelResponse,+ ResponseT,after_model,before_model,dynamic_prompt,@@ -24,7 +35,7 @@ from langchain.agents.middleware.types import (from tests.unit_tests.agents.model import FakeToolCallingModel-class CustomState(AgentState):+class CustomState(AgentState[ResponseT], Generic[ResponseT]):"""Custom state schema for testing."""custom_field: NotRequired[str]@@ -42,7 +53,7 @@ def test_before_model_decorator() -> None:@before_model(state_schema=CustomState, tools=[test_tool], can_jump_to=["end"], name="CustomBeforeModel")- def custom_before_model(state: CustomState, runtime: Runtime) -> dict[str, Any]:+ def custom_before_model(*_args: Any, **_kwargs: Any) -> dict[str, Any]:return {"jump_to": "end"}assert isinstance(custom_before_model, AgentMiddleware)@@ -51,7 +62,7 @@ def test_before_model_decorator() -> None: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)+ result = custom_before_model.before_model({"messages": [HumanMessage("Hello")]}, Runtime())assert result == {"jump_to": "end"}@@ -64,7 +75,7 @@ def test_after_model_decorator() -> None:can_jump_to=["model", "end"],name="CustomAfterModel",)- def custom_after_model(state: CustomState, runtime: Runtime) -> dict[str, Any]:+ def custom_after_model(*_args: Any, **_kwargs: Any) -> dict[str, Any]:return {"jump_to": "model"}# Verify all options were applied@@ -79,7 +90,7 @@ def test_after_model_decorator() -> None:# Verify it worksresult = custom_after_model.after_model(- {"messages": [HumanMessage("Hello"), AIMessage("Hi!")]}, None+ {"messages": [HumanMessage("Hello"), AIMessage("Hi!")]}, Runtime())assert result == {"jump_to": "model"}@@ -88,8 +99,11 @@ def test_on_model_call_decorator() -> None:"""Test wrap_model_call decorator with all configuration options."""@wrap_model_call(state_schema=CustomState, tools=[test_tool], name="CustomOnModelCall")- def custom_on_model_call(request, handler):- return handler(request.override(system_prompt="Modified"))+ def custom_on_model_call(+ request: ModelRequest,+ handler: Callable[[ModelRequest], ModelResponse],+ ) -> ModelCallResult:+ return handler(request.override(system_message=SystemMessage(content="Modified")))# Verify all options were appliedassert isinstance(custom_on_model_call, AgentMiddleware)@@ -99,7 +113,7 @@ def test_on_model_call_decorator() -> None:# Verify it worksoriginal_request = ModelRequest(- model="test-model",+ model=FakeToolCallingModel(),system_prompt="Original",messages=[HumanMessage("Hello")],tool_choice=None,@@ -109,11 +123,14 @@ def test_on_model_call_decorator() -> None:runtime=None,)- def mock_handler(req):- return AIMessage(content=f"Handled with prompt: {req.system_prompt}")+ def mock_handler(req: ModelRequest) -> ModelResponse:+ return ModelResponse(+ result=[AIMessage(content=f"Handled with prompt: {req.system_prompt}")]+ )result = custom_on_model_call.wrap_model_call(original_request, mock_handler)- assert result.content == "Handled with prompt: Modified"+ assert isinstance(result, ModelResponse)+ assert result.result[0].content == "Handled with prompt: Modified"def test_all_decorators_integration() -> None:@@ -121,16 +138,19 @@ def test_all_decorators_integration() -> None:call_order = []@before_model- def track_before(state: AgentState, runtime: Runtime) -> None:+ def track_before(*_args: Any, **_kwargs: Any) -> None:call_order.append("before")@wrap_model_call- def track_on_call(request, handler):+ def track_on_call(+ request: ModelRequest,+ handler: Callable[[ModelRequest], ModelResponse],+ ) -> ModelCallResult:call_order.append("on_call")return handler(request)@after_model- def track_after(state: AgentState, runtime: Runtime) -> None:+ def track_after(*_args: Any, **_kwargs: Any) -> None:call_order.append("after")agent = create_agent(@@ -146,15 +166,18 @@ def test_decorators_use_function_names_as_default() -> None:"""Test that decorators use function names as default middleware names."""@before_model- def my_before_hook(state: AgentState, runtime: Runtime) -> None:+ def my_before_hook(*_args: Any, **_kwargs: Any) -> None:return None@wrap_model_call- def my_on_call_hook(request, handler):+ def my_on_call_hook(+ request: ModelRequest,+ handler: Callable[[ModelRequest], ModelResponse],+ ) -> ModelCallResult:return handler(request)@after_model- def my_after_hook(state: AgentState, runtime: Runtime) -> None:+ def my_after_hook(*_args: Any, **_kwargs: Any) -> None:return None# Verify that function names are used as middleware class names@@ -168,13 +191,17 @@ def test_hook_config_decorator_on_class_method() -> None:class JumpMiddleware(AgentMiddleware):@hook_config(can_jump_to=["end", "model"])- def before_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ def before_model(+ self, state: AgentState[Any], runtime: Runtime[None]+ ) -> 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:+ def after_model(+ self, state: AgentState[Any], runtime: Runtime[None]+ ) -> dict[str, Any] | None:return {"jump_to": "tools"}# Verify can_jump_to metadata is preserved@@ -186,7 +213,9 @@ 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:+ def conditional_before(+ state: AgentState[Any], *_args: Any, **_kwargs: Any+ ) -> dict[str, Any] | None:if len(state["messages"]) > 3:return {"jump_to": "end"}return None@@ -200,7 +229,9 @@ 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:+ def conditional_after(+ state: AgentState[Any], *_args: Any, **_kwargs: Any+ ) -> dict[str, Any] | None:if state["messages"][-1].content == "retry":return {"jump_to": "model"}return None@@ -218,7 +249,7 @@ def test_can_jump_to_integration() -> None:calls = []@before_model(can_jump_to=["end"])- def early_exit(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ def early_exit(state: AgentState[Any], *_args: Any, **_kwargs: Any) -> dict[str, Any] | None:calls.append("early_exit")if state["messages"][0].content == "exit":return {"jump_to": "end"}@@ -246,7 +277,7 @@ def test_async_before_model_decorator() -> None:"""Test before_model decorator with async function."""@before_model(state_schema=CustomState, tools=[test_tool], name="AsyncBeforeModel")- async def async_before_model(state: CustomState, runtime: Runtime) -> dict[str, Any]:+ async def async_before_model(*_args: Any, **_kwargs: Any) -> dict[str, Any]:return {"custom_field": "async_value"}assert isinstance(async_before_model, AgentMiddleware)@@ -259,7 +290,7 @@ def test_async_after_model_decorator() -> None:"""Test after_model decorator with async function."""@after_model(state_schema=CustomState, tools=[test_tool], name="AsyncAfterModel")- async def async_after_model(state: CustomState, runtime: Runtime) -> dict[str, Any]:+ async def async_after_model(*_args: Any, **_kwargs: Any) -> dict[str, Any]:return {"custom_field": "async_value"}assert isinstance(async_after_model, AgentMiddleware)@@ -272,8 +303,13 @@ def test_async_on_model_call_decorator() -> None:"""Test wrap_model_call decorator with async function."""@wrap_model_call(state_schema=CustomState, tools=[test_tool], name="AsyncOnModelCall")- async def async_on_model_call(request, handler):- return await handler(request.override(system_prompt="Modified async"))+ async def async_on_model_call(+ request: ModelRequest,+ handler: Callable[[ModelRequest], Awaitable[ModelResponse]],+ ) -> ModelCallResult:+ return await handler(+ request.override(system_message=SystemMessage(content="Modified async"))+ )assert isinstance(async_on_model_call, AgentMiddleware)assert async_on_model_call.state_schema == CustomState@@ -285,19 +321,25 @@ def test_mixed_sync_async_decorators() -> None:"""Test decorators with both sync and async functions."""@before_model(name="MixedBeforeModel")- def sync_before(state: AgentState, runtime: Runtime) -> None:+ def sync_before(*_args: Any, **_kwargs: Any) -> None:return None@before_model(name="MixedBeforeModel")- async def async_before(state: AgentState, runtime: Runtime) -> None:+ async def async_before(*_args: Any, **_kwargs: Any) -> None:return None@wrap_model_call(name="MixedOnModelCall")- def sync_on_call(request, handler):+ def sync_on_call(+ request: ModelRequest,+ handler: Callable[[ModelRequest], ModelResponse],+ ) -> ModelCallResult:return handler(request)@wrap_model_call(name="MixedOnModelCall")- async def async_on_call(request, handler):+ async def async_on_call(+ request: ModelRequest,+ handler: Callable[[ModelRequest], Awaitable[ModelResponse]],+ ) -> ModelCallResult:return await handler(request)# Both should create valid middleware instances@@ -312,16 +354,19 @@ async def test_async_decorators_integration() -> None:call_order = []@before_model- async def track_async_before(state: AgentState, runtime: Runtime) -> None:+ async def track_async_before(*_args: Any, **_kwargs: Any) -> None:call_order.append("async_before")@wrap_model_call- async def track_async_on_call(request, handler):+ async def track_async_on_call(+ request: ModelRequest,+ handler: Callable[[ModelRequest], Awaitable[ModelResponse]],+ ) -> ModelCallResult:call_order.append("async_on_call")return await handler(request)@after_model- async def track_async_after(state: AgentState, runtime: Runtime) -> None:+ async def track_async_after(*_args: Any, **_kwargs: Any) -> None:call_order.append("async_after")agent = create_agent(@@ -339,29 +384,35 @@ async def test_mixed_sync_async_decorators_integration() -> None:call_order = []@before_model- def track_sync_before(state: AgentState, runtime: Runtime) -> None:+ def track_sync_before(*_args: Any, **_kwargs: Any) -> None:call_order.append("sync_before")@before_model- async def track_async_before(state: AgentState, runtime: Runtime) -> None:+ async def track_async_before(*_args: Any, **_kwargs: Any) -> None:call_order.append("async_before")@wrap_model_call- async def track_async_on_call(request, handler):+ async def track_async_on_call(+ request: ModelRequest,+ handler: Callable[[ModelRequest], Awaitable[ModelResponse]],+ ) -> ModelCallResult:call_order.append("async_on_call")return await handler(request)@wrap_tool_call- async def track_sync_on_tool_call(request, handler):+ async def track_sync_on_tool_call(+ request: ToolCallRequest,+ handler: Callable[[ToolCallRequest], Awaitable[ToolMessage | Command[Any]]],+ ) -> ToolMessage | Command[Any]:call_order.append("async_on_tool_call")return await handler(request)@after_model- async def track_async_after(state: AgentState, runtime: Runtime) -> None:+ async def track_async_after(*_args: Any, **_kwargs: Any) -> None:call_order.append("async_after")@after_model- def track_sync_after(state: AgentState, runtime: Runtime) -> None:+ def track_sync_after(*_args: Any, **_kwargs: Any) -> None:call_order.append("sync_after")agent = create_agent(@@ -395,7 +446,7 @@ def test_async_before_model_preserves_can_jump_to() -> None:@before_model(can_jump_to=["end"])async def async_conditional_before(- state: AgentState, runtime: Runtime+ state: AgentState[Any], *_args: Any, **_kwargs: Any) -> dict[str, Any] | None:if len(state["messages"]) > 3:return {"jump_to": "end"}@@ -412,7 +463,9 @@ 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:+ async def async_conditional_after(+ state: AgentState[Any], *_args: Any, **_kwargs: Any+ ) -> dict[str, Any] | None:if state["messages"][-1].content == "retry":return {"jump_to": "model"}return None@@ -430,7 +483,9 @@ async def test_async_can_jump_to_integration() -> None:calls = []@before_model(can_jump_to=["end"])- async def async_early_exit(state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ async def async_early_exit(+ state: AgentState[Any], *_args: Any, **_kwargs: Any+ ) -> dict[str, Any] | None:calls.append("async_early_exit")if state["messages"][0].content == "exit":return {"jump_to": "end"}@@ -472,7 +527,9 @@ def test_get_can_jump_to_only_overridden_methods() -> None:# Middleware with only sync method overriddenclass SyncOnlyMiddleware(AgentMiddleware):@hook_config(can_jump_to=["end"])- def before_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ def before_model(+ self, state: AgentState[Any], runtime: Runtime[None]+ ) -> dict[str, Any] | None:return Nonesync_middleware = SyncOnlyMiddleware()@@ -484,7 +541,9 @@ def test_get_can_jump_to_only_overridden_methods() -> None:# Middleware with only async method overriddenclass AsyncOnlyMiddleware(AgentMiddleware):@hook_config(can_jump_to=["model"])- async def aafter_model(self, state: AgentState, runtime: Runtime) -> dict[str, Any] | None:+ async def aafter_model(+ self, state: AgentState[Any], runtime: Runtime[None]+ ) -> dict[str, Any] | None:return Noneasync_middleware = AsyncOnlyMiddleware()@@ -503,7 +562,9 @@ def test_async_middleware_with_can_jump_to_graph_snapshot(snapshot: SnapshotAsse# 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:+ async def async_before_with_jump(+ state: AgentState[Any], *_args: Any, **_kwargs: Any+ ) -> dict[str, Any] | None:if len(state["messages"]) > 5:return {"jump_to": "end"}return None@@ -516,7 +577,9 @@ def test_async_middleware_with_can_jump_to_graph_snapshot(snapshot: SnapshotAsse# 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:+ async def async_after_with_jump(+ state: AgentState[Any], *_args: Any, **_kwargs: Any+ ) -> dict[str, Any] | None:if state["messages"][-1].content == "retry":return {"jump_to": "model"}return None@@ -529,11 +592,11 @@ def test_async_middleware_with_can_jump_to_graph_snapshot(snapshot: SnapshotAsse# 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:+ async def async_before_early_exit(*_args: Any, **_kwargs: Any) -> 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:+ async def async_after_retry(*_args: Any, **_kwargs: Any) -> dict[str, Any] | None:return Noneagent_multiple_async = create_agent(@@ -545,11 +608,11 @@ def test_async_middleware_with_can_jump_to_graph_snapshot(snapshot: SnapshotAsse# 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:+ def sync_before_with_jump(*_args: Any, **_kwargs: Any) -> 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:+ async def async_after_with_jumps(*_args: Any, **_kwargs: Any) -> dict[str, Any] | None:return Noneagent_mixed = create_agent(@@ -574,7 +637,7 @@ def test_dynamic_prompt_decorator() -> None:# Verify it modifies the request correctlyoriginal_request = ModelRequest(- model="test-model",+ model=FakeToolCallingModel(),system_prompt="Original",messages=[HumanMessage("Hello")],tool_choice=None,@@ -584,11 +647,12 @@ def test_dynamic_prompt_decorator() -> None:runtime=None,)- def mock_handler(req):- return AIMessage(content=req.system_prompt)+ def mock_handler(req: ModelRequest) -> ModelResponse:+ return ModelResponse(result=[AIMessage(content=req.system_prompt)])result = my_prompt.wrap_model_call(original_request, mock_handler)- assert result.content == "Dynamic test prompt"+ assert isinstance(result, ModelResponse)+ assert result.result[0].content == "Dynamic test prompt"def test_dynamic_prompt_uses_state() -> None:@@ -601,7 +665,7 @@ def test_dynamic_prompt_uses_state() -> None:# Verify it uses state correctlyoriginal_request = ModelRequest(- model="test-model",+ model=FakeToolCallingModel(),system_prompt="Original",messages=[HumanMessage("Hello")],tool_choice=None,@@ -611,11 +675,12 @@ def test_dynamic_prompt_uses_state() -> None:runtime=None,)- def mock_handler(req):- return AIMessage(content=req.system_prompt)+ def mock_handler(req: ModelRequest) -> ModelResponse:+ return ModelResponse(result=[AIMessage(content=req.system_prompt)])result = custom_prompt.wrap_model_call(original_request, mock_handler)- assert result.content == "Prompt with 2 messages"+ assert isinstance(result, ModelResponse)+ assert result.result[0].content == "Prompt with 2 messages"def test_dynamic_prompt_integration() -> None: