The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
chore(langchain_v1): rename on_model_call to wrap_model_call (#33370)
Eugene Yurtsevf33b1b3d77eb
diff --git a/libs/langchain_v1/langchain/agents/factory.py b/libs/langchain_v1/langchain/agents/factory.pyindex 319560c245..e3079b29df 100644--- a/libs/langchain_v1/langchain/agents/factory.py+++ b/libs/langchain_v1/langchain/agents/factory.py@@ -98,7 +98,7 @@ def _chain_model_call_handlers(]| None):- """Compose multiple on_model_call handlers into single middleware stack.+ """Compose multiple wrap_model_call handlers into single middleware stack.Composes handlers so first in list becomes outermost layer. Each handlerreceives a handler callback to execute inner layers.@@ -189,7 +189,7 @@ def _chain_async_model_call_handlers(]| None):- """Compose multiple async on_model_call handlers into single middleware stack.+ """Compose multiple async wrap_model_call handlers into single middleware stack.Args:handlers: List of async handlers. First handler wraps all others.@@ -609,24 +609,26 @@ def create_agent( # noqa: PLR0915if m.__class__.after_agent is not AgentMiddleware.after_agentor m.__class__.aafter_agent is not AgentMiddleware.aafter_agent]- middleware_w_on_model_call = [- m for m in middleware if m.__class__.on_model_call is not AgentMiddleware.on_model_call+ middleware_w_wrap_model_call = [+ m for m in middleware if m.__class__.wrap_model_call is not AgentMiddleware.wrap_model_call]- middleware_w_aon_model_call = [- m for m in middleware if m.__class__.aon_model_call is not AgentMiddleware.aon_model_call+ middleware_w_awrap_model_call = [+ m+ for m in middleware+ if m.__class__.awrap_model_call is not AgentMiddleware.awrap_model_call]- # Compose on_model_call handlers into a single middleware stack (sync)- on_model_call_handler = None- if middleware_w_on_model_call:- sync_handlers = [m.on_model_call for m in middleware_w_on_model_call]- on_model_call_handler = _chain_model_call_handlers(sync_handlers)+ # Compose wrap_model_call handlers into a single middleware stack (sync)+ wrap_model_call_handler = None+ if middleware_w_wrap_model_call:+ sync_handlers = [m.wrap_model_call for m in middleware_w_wrap_model_call]+ wrap_model_call_handler = _chain_model_call_handlers(sync_handlers)- # Compose aon_model_call handlers into a single middleware stack (async)- aon_model_call_handler = None- if middleware_w_aon_model_call:- async_handlers = [m.aon_model_call for m in middleware_w_aon_model_call]- aon_model_call_handler = _chain_async_model_call_handlers(async_handlers)+ # Compose awrap_model_call handlers into a single middleware stack (async)+ awrap_model_call_handler = None+ if middleware_w_awrap_model_call:+ async_handlers = [m.awrap_model_call for m in middleware_w_awrap_model_call]+ awrap_model_call_handler = _chain_async_model_call_handlers(async_handlers)state_schemas = {m.state_schema for m in middleware}state_schemas.add(AgentState)@@ -858,7 +860,7 @@ def create_agent( # noqa: PLR0915def _execute_model_sync(request: ModelRequest) -> _InternalModelResponse:"""Execute model and return result or exception.- This is the core model execution logic wrapped by on_model_call handlers.+ This is the core model execution logic wrapped by wrap_model_call handlers."""try:# Get the bound model (with auto-detection if needed)@@ -909,12 +911,12 @@ def create_agent( # noqa: PLR0915effective_response_format = internal_response.effective_response_formatreturn internal_response.result- if on_model_call_handler is None:+ if wrap_model_call_handler is None:# No handlers - execute directlyoutput = base_handler(request)else:# Call composed handler with base handler- output = on_model_call_handler(request, base_handler)+ output = wrap_model_call_handler(request, base_handler)return {"thread_model_call_count": state.get("thread_model_call_count", 0) + 1,"run_model_call_count": state.get("run_model_call_count", 0) + 1,@@ -924,7 +926,7 @@ def create_agent( # noqa: PLR0915async def _execute_model_async(request: ModelRequest) -> _InternalModelResponse:"""Execute model asynchronously and return result or exception.- This is the core async model execution logic wrapped by on_model_call handlers.+ This is the core async model execution logic wrapped by wrap_model_call handlers."""try:# Get the bound model (with auto-detection if needed)@@ -975,12 +977,12 @@ def create_agent( # noqa: PLR0915effective_response_format = internal_response.effective_response_formatreturn internal_response.result- if aon_model_call_handler is None:+ if awrap_model_call_handler is None:# No async handlers - execute directlyoutput = await base_handler(request)else:# Call composed async handler with base handler- output = await aon_model_call_handler(request, base_handler)+ output = await awrap_model_call_handler(request, base_handler)return {"thread_model_call_count": state.get("thread_model_call_count", 0) + 1,"run_model_call_count": state.get("run_model_call_count", 0) + 1,diff --git a/libs/langchain_v1/langchain/agents/middleware/__init__.py b/libs/langchain_v1/langchain/agents/middleware/__init__.pyindex 9ef36daa77..d7066c6792 100644--- a/libs/langchain_v1/langchain/agents/middleware/__init__.py+++ b/libs/langchain_v1/langchain/agents/middleware/__init__.py@@ -23,7 +23,7 @@ from .types import (before_model,dynamic_prompt,hook_config,- on_model_call,+ wrap_model_call,)__all__ = [@@ -49,5 +49,5 @@ __all__ = ["before_model","dynamic_prompt","hook_config",- "on_model_call",+ "wrap_model_call",]diff --git a/libs/langchain_v1/langchain/agents/middleware/context_editing.py b/libs/langchain_v1/langchain/agents/middleware/context_editing.pyindex ede15ed54c..224a96c9a4 100644--- a/libs/langchain_v1/langchain/agents/middleware/context_editing.py+++ b/libs/langchain_v1/langchain/agents/middleware/context_editing.py@@ -206,7 +206,7 @@ class ContextEditingMiddleware(AgentMiddleware):self.edits = list(edits or (ClearToolUsesEdit(),))self.token_count_method = token_count_method- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],diff --git a/libs/langchain_v1/langchain/agents/middleware/model_fallback.py b/libs/langchain_v1/langchain/agents/middleware/model_fallback.pyindex 69b8fdccb3..048eb8edb8 100644--- a/libs/langchain_v1/langchain/agents/middleware/model_fallback.py+++ b/libs/langchain_v1/langchain/agents/middleware/model_fallback.py@@ -65,7 +65,7 @@ class ModelFallbackMiddleware(AgentMiddleware):else:self.models.append(model)- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],diff --git a/libs/langchain_v1/langchain/agents/middleware/planning.py b/libs/langchain_v1/langchain/agents/middleware/planning.pyindex 5b36505d52..3f78be947e 100644--- a/libs/langchain_v1/langchain/agents/middleware/planning.py+++ b/libs/langchain_v1/langchain/agents/middleware/planning.py@@ -186,7 +186,7 @@ class PlanningMiddleware(AgentMiddleware):self.tools = [write_todos]- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],diff --git a/libs/langchain_v1/langchain/agents/middleware/prompt_caching.py b/libs/langchain_v1/langchain/agents/middleware/prompt_caching.pyindex 99eec8bd06..af0d1c7037 100644--- a/libs/langchain_v1/langchain/agents/middleware/prompt_caching.py+++ b/libs/langchain_v1/langchain/agents/middleware/prompt_caching.py@@ -42,7 +42,7 @@ class AnthropicPromptCachingMiddleware(AgentMiddleware):self.min_messages_to_cache = min_messages_to_cacheself.unsupported_model_behavior = unsupported_model_behavior- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],diff --git a/libs/langchain_v1/langchain/agents/middleware/tool_selection.py b/libs/langchain_v1/langchain/agents/middleware/tool_selection.pyindex 67d3e505af..f63fb68be7 100644--- a/libs/langchain_v1/langchain/agents/middleware/tool_selection.py+++ b/libs/langchain_v1/langchain/agents/middleware/tool_selection.py@@ -242,7 +242,7 @@ class LLMToolSelectorMiddleware(AgentMiddleware):request.tools = [*selected_tools, *provider_tools]return request- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],@@ -273,7 +273,7 @@ class LLMToolSelectorMiddleware(AgentMiddleware):)return handler(modified_request)- async def aon_model_call(+ async def awrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], Awaitable[AIMessage]],diff --git a/libs/langchain_v1/langchain/agents/middleware/types.py b/libs/langchain_v1/langchain/agents/middleware/types.pyindex f76a9419c0..d0cc40b377 100644--- a/libs/langchain_v1/langchain/agents/middleware/types.py+++ b/libs/langchain_v1/langchain/agents/middleware/types.py@@ -50,7 +50,6 @@ __all__ = ["before_model","dynamic_prompt","hook_config",- "on_model_call","wrap_tool_call",]@@ -165,7 +164,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):) -> dict[str, Any] | None:"""Async logic to run after the model is called."""- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],@@ -189,7 +188,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):Examples:Retry on error:```python- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):for attempt in range(3):try:return handler(request)@@ -200,14 +199,14 @@ class AgentMiddleware(Generic[StateT, ContextT]):Rewrite response:```python- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):result = handler(request)return AIMessage(content=f"[{result.content}]")```Error to fallback:```python- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):try:return handler(request)except Exception:@@ -216,7 +215,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):Cache/short-circuit:```python- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):if cached := get_cache(request):return cached # Short-circuit with cached resultresult = handler(request)@@ -226,12 +225,12 @@ class AgentMiddleware(Generic[StateT, ContextT]):"""raise NotImplementedError- async def aon_model_call(+ async def awrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], Awaitable[AIMessage]],) -> AIMessage:- """Async version of on_model_call.+ """Async version of wrap_model_call.Args:request: Model request to execute (includes state and runtime).@@ -243,7 +242,7 @@ class AgentMiddleware(Generic[StateT, ContextT]):Examples:Retry on error:```python- async def aon_model_call(self, request, handler):+ async def awrap_model_call(self, request, handler):for attempt in range(3):try:return await handler(request)@@ -988,7 +987,7 @@ def dynamic_prompt():"""Decorator used to dynamically generate system prompts for the model.- This is a convenience decorator that creates middleware using `on_model_call`+ This is a convenience decorator that creates middleware using `wrap_model_call`specifically for dynamic prompt generation. The decorated function should returna string that will be set as the system prompt for the model request.@@ -1052,7 +1051,7 @@ def dynamic_prompt({"state_schema": AgentState,"tools": [],- "aon_model_call": async_wrapped,+ "awrap_model_call": async_wrapped,},)()@@ -1073,7 +1072,7 @@ def dynamic_prompt({"state_schema": AgentState,"tools": [],- "on_model_call": wrapped,+ "wrap_model_call": wrapped,},)()@@ -1083,13 +1082,13 @@ def dynamic_prompt(@overload-def on_model_call(+def wrap_model_call(func: _CallableReturningModelResponse[StateT, ContextT],) -> AgentMiddleware[StateT, ContextT]: ...@overload-def on_model_call(+def wrap_model_call(func: None = None,*,state_schema: type[StateT] | None = None,@@ -1101,7 +1100,7 @@ def on_model_call(]: ...-def on_model_call(+def wrap_model_call(func: _CallableReturningModelResponse[StateT, ContextT] | None = None,*,state_schema: type[StateT] | None = None,@@ -1114,7 +1113,7 @@ def on_model_call(]| AgentMiddleware[StateT, ContextT]):- """Create middleware with on_model_call hook from a function.+ """Create middleware with wrap_model_call hook from a function.Converts a function with handler callback into middleware that can interceptmodel calls, implement retry logic, handle errors, and rewrite responses.@@ -1132,7 +1131,7 @@ def on_model_call(Examples:Basic retry logic:```python- @on_model_call+ @wrap_model_calldef retry_on_error(request, handler):max_retries = 3for attempt in range(max_retries):@@ -1145,7 +1144,7 @@ def on_model_call(Model fallback:```python- @on_model_call+ @wrap_model_calldef fallback_model(request, handler):# Try primary modeltry:@@ -1160,7 +1159,7 @@ def on_model_call(Rewrite response content:```python- @on_model_call+ @wrap_model_calldef uppercase_responses(request, handler):result = handler(request)return AIMessage(content=result.content.upper())@@ -1182,7 +1181,7 @@ def on_model_call(return await func(request, handler) # type: ignore[misc, arg-type]middleware_name = name or cast(- "str", getattr(func, "__name__", "OnModelCallMiddleware")+ "str", getattr(func, "__name__", "WrapModelCallMiddleware"))return type(@@ -1191,7 +1190,7 @@ def on_model_call({"state_schema": state_schema or AgentState,"tools": tools or [],- "aon_model_call": async_wrapped,+ "awrap_model_call": async_wrapped,},)()@@ -1202,7 +1201,7 @@ def on_model_call() -> AIMessage:return func(request, handler)- middleware_name = name or cast("str", getattr(func, "__name__", "OnModelCallMiddleware"))+ middleware_name = name or cast("str", getattr(func, "__name__", "WrapModelCallMiddleware"))return type(middleware_name,@@ -1210,7 +1209,7 @@ def on_model_call({"state_schema": state_schema or AgentState,"tools": tools or [],- "on_model_call": wrapped,+ "wrap_model_call": wrapped,},)()diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/test_llm_tool_selection.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/test_llm_tool_selection.pyindex 8955a41516..031bb60fe2 100644--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/test_llm_tool_selection.py+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/test_llm_tool_selection.py@@ -7,7 +7,7 @@ from itertools import cyclefrom pydantic import BaseModelfrom langchain.agents import create_agent-from langchain.agents.middleware import AgentState, ModelRequest, on_model_call+from langchain.agents.middleware import AgentState, ModelRequest, wrap_model_callfrom langchain.agents.middleware import LLMToolSelectorMiddlewarefrom langchain.messages import AIMessagefrom langchain_core.language_models import LanguageModelInput@@ -110,7 +110,7 @@ class TestLLMToolSelectorBasic:model_requests = []- @on_model_call+ @wrap_model_calldef trace_model_requests(request, handler):"""Middleware to select relevant tools based on state/context."""# Select a small, relevant subset of tools based on state/context@@ -215,7 +215,7 @@ class TestMaxToolsLimiting:"""Test that max_tools limits selection when model selects too many tools."""model_requests = []- @on_model_call+ @wrap_model_calldef trace_model_requests(request, handler):model_requests.append(request)return handler(request)@@ -270,7 +270,7 @@ class TestMaxToolsLimiting:"""Test that when max_tools is None, all selected tools are used."""model_requests = []- @on_model_call+ @wrap_model_calldef trace_model_requests(request, handler):model_requests.append(request)return handler(request)@@ -332,7 +332,7 @@ class TestAlwaysInclude:"""Test that always_include tools are always present in the request."""model_requests = []- @on_model_call+ @wrap_model_calldef trace_model_requests(request, handler):model_requests.append(request)return handler(request)@@ -382,7 +382,7 @@ class TestAlwaysInclude:"""Test that always_include tools don't count against max_tools limit."""model_requests = []- @on_model_call+ @wrap_model_calldef trace_model_requests(request, handler):model_requests.append(request)return handler(request)@@ -436,7 +436,7 @@ class TestAlwaysInclude:"""Test that multiple always_include tools are all present."""model_requests = []- @on_model_call+ @wrap_model_calldef trace_model_requests(request, handler):model_requests.append(request)return handler(request)@@ -493,7 +493,7 @@ class TestDuplicateAndInvalidTools:"""Test that duplicate tool selections are deduplicated."""model_requests = []- @on_model_call+ @wrap_model_calldef trace_model_requests(request, handler):model_requests.append(request)return handler(request)@@ -546,7 +546,7 @@ class TestDuplicateAndInvalidTools:"""Test that max_tools works correctly with duplicate selections."""model_requests = []- @on_model_call+ @wrap_model_calldef trace_model_requests(request, handler):model_requests.append(request)return handler(request)diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/test_on_model_call_decorator.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_model_call_decorator.pysimilarity index 94%rename from libs/langchain_v1/tests/unit_tests/agents/middleware/test_on_model_call_decorator.pyrename to libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_model_call_decorator.pyindex ba4d85c399..17b201d313 100644--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/test_on_model_call_decorator.py+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_model_call_decorator.py@@ -1,4 +1,4 @@-"""Unit tests for the @on_model_call decorator."""+"""Unit tests for the @wrap_model_call decorator."""import pytestfrom langchain_core.language_models.fake_chat_models import GenericFakeChatModel@@ -9,17 +9,17 @@ from langchain.agents.middleware.types import (AgentMiddleware,AgentState,ModelRequest,- on_model_call,+ wrap_model_call,)class TestOnModelCallDecorator:- """Test the @on_model_call decorator for creating middleware."""+ """Test the @wrap_model_call decorator for creating middleware."""def test_basic_decorator_usage(self) -> None:"""Test basic decorator usage without parameters."""- @on_model_call+ @wrap_model_calldef passthrough_middleware(request, handler):return handler(request)@@ -37,7 +37,7 @@ class TestOnModelCallDecorator:def test_decorator_with_custom_name(self) -> None:"""Test decorator with custom middleware name."""- @on_model_call(name="CustomMiddleware")+ @wrap_model_call(name="CustomMiddleware")def my_middleware(request, handler):return handler(request)@@ -55,7 +55,7 @@ class TestOnModelCallDecorator:raise ValueError("First call fails")return super()._generate(messages, **kwargs)- @on_model_call+ @wrap_model_calldef retry_once(request, handler):try:return handler(request)@@ -74,7 +74,7 @@ class TestOnModelCallDecorator:def test_decorator_response_rewriting(self) -> None:"""Test decorator for rewriting responses."""- @on_model_call+ @wrap_model_calldef uppercase_responses(request, handler):result = handler(request)return AIMessage(content=result.content.upper())@@ -93,7 +93,7 @@ class TestOnModelCallDecorator:def _generate(self, messages, **kwargs):raise ValueError("Model error")- @on_model_call+ @wrap_model_calldef error_to_fallback(request, handler):try:return handler(request)@@ -111,7 +111,7 @@ class TestOnModelCallDecorator:"""Test decorator accessing agent state."""state_values = []- @on_model_call+ @wrap_model_calldef log_state(request, handler):state_values.append(request.state.get("messages"))return handler(request)@@ -130,14 +130,14 @@ class TestOnModelCallDecorator:"""Test composition of multiple decorated middleware."""execution_order = []- @on_model_call+ @wrap_model_calldef outer_middleware(request, handler):execution_order.append("outer-before")result = handler(request)execution_order.append("outer-after")return result- @on_model_call+ @wrap_model_calldef inner_middleware(request, handler):execution_order.append("inner-before")result = handler(request)@@ -164,7 +164,7 @@ class TestOnModelCallDecorator:messages: listcustom_field: str- @on_model_call(state_schema=CustomState)+ @wrap_model_call(state_schema=CustomState)def middleware_with_schema(request, handler):return handler(request)@@ -181,7 +181,7 @@ class TestOnModelCallDecorator:"""A test tool."""return f"Result: {query}"- @on_model_call(tools=[test_tool])+ @wrap_model_call(tools=[test_tool])def middleware_with_tools(request, handler):return handler(request)@@ -193,12 +193,12 @@ class TestOnModelCallDecorator:"""Test that decorator works both with and without parentheses."""# Without parentheses- @on_model_call+ @wrap_model_calldef middleware_no_parens(request, handler):return handler(request)# With parentheses- @on_model_call()+ @wrap_model_call()def middleware_with_parens(request, handler):return handler(request)@@ -208,7 +208,7 @@ class TestOnModelCallDecorator:def test_decorator_preserves_function_name(self) -> None:"""Test that decorator uses function name for class name."""- @on_model_call+ @wrap_model_calldef my_custom_middleware(request, handler):return handler(request)@@ -218,7 +218,7 @@ class TestOnModelCallDecorator:"""Test decorated middleware mixed with class-based middleware."""execution_order = []- @on_model_call+ @wrap_model_calldef decorated_middleware(request, handler):execution_order.append("decorated-before")result = handler(request)@@ -226,7 +226,7 @@ class TestOnModelCallDecorator:return resultclass ClassMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):execution_order.append("class-before")result = handler(request)execution_order.append("class-after")@@ -260,7 +260,7 @@ class TestOnModelCallDecorator:raise ValueError(f"Attempt {call_count['value']} failed")return super()._generate(messages, **kwargs)- @on_model_call+ @wrap_model_calldef retry_with_tracking(request, handler):max_retries = 3last_exception = None@@ -288,7 +288,7 @@ class TestOnModelCallDecorator:"""Test that decorated middleware works with async agent invocation."""call_log = []- @on_model_call+ @wrap_model_callasync def logging_middleware(request, handler):call_log.append("before")result = await handler(request)@@ -307,7 +307,7 @@ class TestOnModelCallDecorator:"""Test decorator modifying request before execution."""modified_prompts = []- @on_model_call+ @wrap_model_calldef add_system_prompt(request, handler):# Modify request to add system promptmodified_request = ModelRequest(@@ -333,7 +333,7 @@ class TestOnModelCallDecorator:def test_decorator_multi_stage_transformation(self) -> None:"""Test decorator applying multiple transformations."""- @on_model_call+ @wrap_model_calldef multi_transform(request, handler):result = handler(request)diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/test_on_model_call_middleware.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_model_call_middleware.pysimilarity index 91%rename from libs/langchain_v1/tests/unit_tests/agents/middleware/test_on_model_call_middleware.pyrename to libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_model_call_middleware.pyindex 7a211c4375..893432bd51 100644--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/test_on_model_call_middleware.py+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/test_wrap_model_call_middleware.py@@ -1,4 +1,4 @@-"""Unit tests for on_model_call middleware generator protocol."""+"""Unit tests for wrap_model_call middleware generator protocol."""import pytestfrom langchain_core.language_models.fake_chat_models import GenericFakeChatModel@@ -13,13 +13,13 @@ from langchain.agents.middleware.types import (class TestBasicOnModelCall:- """Test basic on_model_call functionality."""+ """Test basic wrap_model_call functionality."""def test_passthrough_middleware(self) -> None:"""Test middleware that simply passes through without modification."""class PassthroughMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):return handler(request)model = GenericFakeChatModel(messages=iter([AIMessage(content="Hello")]))@@ -35,7 +35,7 @@ class TestBasicOnModelCall:call_log = []class LoggingMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):call_log.append("before")result = handler(request)call_log.append("after")@@ -57,7 +57,7 @@ class TestBasicOnModelCall:super().__init__()self.call_count = 0- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):self.call_count += 1return handler(request)@@ -71,7 +71,7 @@ class TestBasicOnModelCall:class TestRetryMiddleware:- """Test retry logic with on_model_call."""+ """Test retry logic with wrap_model_call."""def test_simple_retry_on_error(self) -> None:"""Test middleware that retries once on error."""@@ -89,7 +89,7 @@ class TestRetryMiddleware:super().__init__()self.retry_count = 0- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):try:result = handler(request)return result@@ -120,7 +120,7 @@ class TestRetryMiddleware:self.max_retries = max_retriesself.attempts = []- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):last_exception = Nonefor attempt in range(self.max_retries):self.attempts.append(attempt + 1)@@ -145,13 +145,13 @@ class TestRetryMiddleware:class TestResponseRewriting:- """Test response content rewriting with on_model_call."""+ """Test response content rewriting with wrap_model_call."""def test_uppercase_response(self) -> None:"""Test middleware that transforms response to uppercase."""class UppercaseMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):result = handler(request)return AIMessage(content=result.content.upper())@@ -170,7 +170,7 @@ class TestResponseRewriting:super().__init__()self.prefix = prefix- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):result = handler(request)return AIMessage(content=f"{self.prefix}{result.content}")@@ -183,7 +183,7 @@ class TestResponseRewriting:class TestErrorHandling:- """Test error handling with on_model_call."""+ """Test error handling with wrap_model_call."""def test_convert_error_to_response(self) -> None:"""Test middleware that converts errors to successful responses."""@@ -193,7 +193,7 @@ class TestErrorHandling:raise ValueError("Model error")class ErrorToSuccessMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):try:return handler(request)except Exception:@@ -216,7 +216,7 @@ class TestErrorHandling:raise ConnectionError("Network error")class SelectiveErrorMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):try:return handler(request)except ConnectionError:@@ -235,7 +235,7 @@ class TestErrorHandling:call_log = []class ErrorRecoveryMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):try:call_log.append("before-yield")result = handler(request)@@ -271,7 +271,7 @@ class TestErrorHandling:class TestShortCircuit:- """Test short-circuit patterns with on_model_call."""+ """Test short-circuit patterns with wrap_model_call."""def test_cache_short_circuit(self) -> None:"""Test middleware that short-circuits with cached response."""@@ -279,7 +279,7 @@ class TestShortCircuit:model_calls = []class CachingMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):# Simple cache key based on last messagecache_key = str(request.messages[-1].content) if request.messages else ""@@ -324,7 +324,7 @@ class TestShortCircuit:class TestRequestModification:- """Test request modification with on_model_call."""+ """Test request modification with wrap_model_call."""def test_add_system_prompt(self) -> None:"""Test middleware that adds a system prompt to requests."""@@ -335,7 +335,7 @@ class TestRequestModification:super().__init__()self.system_prompt = system_prompt- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):# Modify request to add system promptmodified_request = ModelRequest(model=request.model,@@ -365,14 +365,14 @@ class TestRequestModification:class TestStateAndRuntime:- """Test state and runtime access in on_model_call."""+ """Test state and runtime access in wrap_model_call."""def test_access_state_in_middleware(self) -> None:"""Test middleware can read and use state."""state_values = []class StateAwareMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):# Access state from requeststate_values.append({@@ -395,7 +395,7 @@ class TestStateAndRuntime:"""Test middleware that tracks retry count in state."""class StateTrackingRetryMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):max_retries = 2for attempt in range(max_retries):try:@@ -424,21 +424,21 @@ class TestStateAndRuntime:class TestMiddlewareComposition:- """Test composition of multiple on_model_call middleware."""+ """Test composition of multiple wrap_model_call middleware."""def test_two_middleware_composition(self) -> None:"""Test that two middleware compose correctly (outer wraps inner)."""execution_order = []class OuterMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):execution_order.append("outer-before")response = handler(request)execution_order.append("outer-after")return responseclass InnerMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):execution_order.append("inner-before")response = handler(request)execution_order.append("inner-after")@@ -470,14 +470,14 @@ class TestMiddlewareComposition:return super()._generate(messages, **kwargs)class LoggingMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):log.append("logging-before")result = handler(request)log.append("logging-after")return resultclass RetryMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):log.append("retry-before")try:result = handler(request)@@ -509,12 +509,12 @@ class TestMiddlewareComposition:"""Test multiple middleware that each transform the response."""class PrefixMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):result = handler(request)return AIMessage(content=f"[PREFIX] {result.content}")class SuffixMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):result = handler(request)return AIMessage(content=f"{result.content} [SUFFIX]")@@ -540,7 +540,7 @@ class TestMiddlewareComposition:return super()._generate(messages, **kwargs)class RetryMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):try:result = handler(request)return result@@ -549,7 +549,7 @@ class TestMiddlewareComposition:return resultclass UppercaseMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):result = handler(request)return AIMessage(content=result.content.upper())@@ -567,21 +567,21 @@ class TestMiddlewareComposition:execution_order = []class FirstMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):execution_order.append("first-before")response = handler(request)execution_order.append("first-after")return responseclass SecondMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):execution_order.append("second-before")response = handler(request)execution_order.append("second-after")return responseclass ThirdMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):execution_order.append("third-before")response = handler(request)execution_order.append("third-after")@@ -611,14 +611,14 @@ class TestMiddlewareComposition:model_calls = []class OuterMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):execution_order.append("outer-before")result = handler(request)execution_order.append("outer-after")return resultclass MiddleRetryMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):execution_order.append("middle-before")# Always retry once (call handler twice)result = handler(request)@@ -628,7 +628,7 @@ class TestMiddlewareComposition:return resultclass InnerMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):execution_order.append("inner-before")result = handler(request)execution_order.append("inner-after")@@ -666,14 +666,14 @@ class TestMiddlewareComposition:class TestAsyncOnModelCall:- """Test async execution with on_model_call."""+ """Test async execution with wrap_model_call."""async def test_async_model_with_middleware(self) -> None:- """Test that on_model_call works with async model execution."""+ """Test that wrap_model_call works with async model execution."""log = []class LoggingMiddleware(AgentMiddleware):- async def aon_model_call(self, request, handler):+ async def awrap_model_call(self, request, handler):log.append("before")result = await handler(request)log.append("after")@@ -700,7 +700,7 @@ class TestAsyncOnModelCall:return await super()._agenerate(messages, **kwargs)class RetryMiddleware(AgentMiddleware):- async def aon_model_call(self, request, handler):+ async def awrap_model_call(self, request, handler):try:return await handler(request)except Exception:@@ -723,7 +723,7 @@ class TestEdgeCases:modified_messages = []class RequestModifyingMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):# Add a system message to the requestmodified_request = requestmodified_messages.append(len(modified_request.messages))@@ -741,7 +741,7 @@ class TestEdgeCases:attempts = []class MultiModelRetryMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):attempts.append("first-attempt")try:result = handler(request)diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_context_editing_middleware.py b/libs/langchain_v1/tests/unit_tests/agents/test_context_editing_middleware.pyindex f2e7df2144..3ba8bb285b 100644--- a/libs/langchain_v1/tests/unit_tests/agents/test_context_editing_middleware.py+++ b/libs/langchain_v1/tests/unit_tests/agents/test_context_editing_middleware.py@@ -85,8 +85,8 @@ def test_no_edit_when_below_trigger() -> None:def mock_handler(req: ModelRequest) -> AIMessage:return AIMessage(content="mock response")- # Call on_model_call which modifies the request- middleware.on_model_call(request, mock_handler)+ # Call wrap_model_call which modifies the request+ middleware.wrap_model_call(request, mock_handler)# The request should have been modified in placeassert request.messages[0].content == ""@@ -118,8 +118,8 @@ def test_clear_tool_outputs_and_inputs() -> None:def mock_handler(req: ModelRequest) -> AIMessage:return AIMessage(content="mock response")- # Call on_model_call which modifies the request- middleware.on_model_call(request, mock_handler)+ # Call wrap_model_call which modifies the request+ middleware.wrap_model_call(request, mock_handler)cleared_ai = request.messages[0]cleared_tool = request.messages[1]@@ -170,8 +170,8 @@ def test_respects_keep_last_tool_results() -> None:def mock_handler(req: ModelRequest) -> AIMessage:return AIMessage(content="mock response")- # Call on_model_call which modifies the request- middleware.on_model_call(request, mock_handler)+ # Call wrap_model_call which modifies the request+ middleware.wrap_model_call(request, mock_handler)cleared_messages = [msg@@ -218,8 +218,8 @@ def test_exclude_tools_prevents_clearing() -> None:def mock_handler(req: ModelRequest) -> AIMessage:return AIMessage(content="mock response")- # Call on_model_call which modifies the request- middleware.on_model_call(request, mock_handler)+ # Call wrap_model_call which modifies the request+ middleware.wrap_model_call(request, mock_handler)search_tool = request.messages[1]calc_tool = request.messages[3]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 1f3374705c..df696090b1 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@@ -115,7 +115,7 @@ def test_create_agent_diagram(def before_model(self, state, runtime):pass- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],@@ -129,7 +129,7 @@ def test_create_agent_diagram(def before_model(self, state, runtime):pass- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],@@ -257,12 +257,12 @@ def test_create_agent_invoke(def before_model(self, state, runtime):calls.append("NoopSeven.before_model")- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],) -> AIMessage:- calls.append("NoopSeven.on_model_call")+ calls.append("NoopSeven.wrap_model_call")return handler(request)def after_model(self, state, runtime):@@ -272,12 +272,12 @@ def test_create_agent_invoke(def before_model(self, state, runtime):calls.append("NoopEight.before_model")- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],) -> AIMessage:- calls.append("NoopEight.on_model_call")+ calls.append("NoopEight.wrap_model_call")return handler(request)def after_model(self, state, runtime):@@ -334,15 +334,15 @@ def test_create_agent_invoke(assert calls == ["NoopSeven.before_model","NoopEight.before_model",- "NoopSeven.on_model_call",- "NoopEight.on_model_call",+ "NoopSeven.wrap_model_call",+ "NoopEight.wrap_model_call","NoopEight.after_model","NoopSeven.after_model","my_tool","NoopSeven.before_model","NoopEight.before_model",- "NoopSeven.on_model_call",- "NoopEight.on_model_call",+ "NoopSeven.wrap_model_call",+ "NoopEight.wrap_model_call","NoopEight.after_model","NoopSeven.after_model",]@@ -358,12 +358,12 @@ def test_create_agent_jump(def before_model(self, state, runtime):calls.append("NoopSeven.before_model")- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],) -> AIMessage:- calls.append("NoopSeven.on_model_call")+ calls.append("NoopSeven.wrap_model_call")return handler(request)def after_model(self, state, runtime):@@ -375,12 +375,12 @@ def test_create_agent_jump(calls.append("NoopEight.before_model")return {"jump_to": "end"}- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],) -> AIMessage:- calls.append("NoopEight.on_model_call")+ calls.append("NoopEight.wrap_model_call")return handler(request)def after_model(self, state, runtime):@@ -1047,7 +1047,7 @@ def test_anthropic_prompt_caching_middleware_initialization() -> None:def mock_handler(req: ModelRequest) -> AIMessage:return AIMessage(content="mock response", **req.model_settings)- result = middleware.on_model_call(fake_request, mock_handler)+ result = middleware.wrap_model_call(fake_request, mock_handler)# Check that model_settings were passed through via the requestassert fake_request.model_settings == {"cache_control": {"type": "ephemeral", "ttl": "5m"}}@@ -1077,7 +1077,7 @@ def test_anthropic_prompt_caching_middleware_unsupported_model() -> None:ValueError,match="AnthropicPromptCachingMiddleware caching middleware only supports Anthropic models. Please install langchain-anthropic.",):- middleware.on_model_call(fake_request, mock_handler)+ middleware.wrap_model_call(fake_request, mock_handler)langchain_anthropic = ModuleType("langchain_anthropic")@@ -1091,12 +1091,12 @@ def test_anthropic_prompt_caching_middleware_unsupported_model() -> None:ValueError,match="AnthropicPromptCachingMiddleware caching middleware only supports Anthropic models, not instances of",):- middleware.on_model_call(fake_request, mock_handler)+ middleware.wrap_model_call(fake_request, mock_handler)middleware = AnthropicPromptCachingMiddleware(unsupported_model_behavior="warn")with warnings.catch_warnings(record=True) as w:- result = middleware.on_model_call(fake_request, mock_handler)+ result = middleware.wrap_model_call(fake_request, mock_handler)assert len(w) == 1assert ("AnthropicPromptCachingMiddleware caching middleware only supports Anthropic models. Please install langchain-anthropic."@@ -1106,7 +1106,7 @@ def test_anthropic_prompt_caching_middleware_unsupported_model() -> None:with warnings.catch_warnings(record=True) as w:with patch.dict("sys.modules", {"langchain_anthropic": langchain_anthropic}):- result = middleware.on_model_call(fake_request, mock_handler)+ result = middleware.wrap_model_call(fake_request, mock_handler)assert isinstance(result, AIMessage)assert len(w) == 1assert (@@ -1116,11 +1116,11 @@ def test_anthropic_prompt_caching_middleware_unsupported_model() -> None:middleware = AnthropicPromptCachingMiddleware(unsupported_model_behavior="ignore")- result = middleware.on_model_call(fake_request, mock_handler)+ result = middleware.wrap_model_call(fake_request, mock_handler)assert isinstance(result, AIMessage)with patch.dict("sys.modules", {"langchain_anthropic": {"ChatAnthropic": object()}}):- result = middleware.on_model_call(fake_request, mock_handler)+ result = middleware.wrap_model_call(fake_request, mock_handler)assert isinstance(result, AIMessage)@@ -1343,7 +1343,7 @@ def test_summarization_middleware_full_workflow() -> None:def test_on_model_call() -> None:class ModifyMiddleware(AgentMiddleware):- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],@@ -1479,7 +1479,7 @@ def test_runtime_injected_into_middleware() -> None:assert runtime is not Nonereturn None- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],@@ -1575,7 +1575,7 @@ def test_planning_middleware_initialization() -> None:],)def test_planning_middleware_on_model_call(original_prompt, expected_prompt_prefix) -> None:- """Test that on_model_call handles system prompts correctly."""+ """Test that wrap_model_call handles system prompts correctly."""middleware = PlanningMiddleware()model = FakeToolCallingModel()@@ -1596,8 +1596,8 @@ def test_planning_middleware_on_model_call(original_prompt, expected_prompt_prefdef mock_handler(req: ModelRequest) -> AIMessage:return AIMessage(content="mock response")- # Call on_model_call to trigger the middleware logic- middleware.on_model_call(request, mock_handler)+ # Call wrap_model_call to trigger the middleware logic+ middleware.wrap_model_call(request, mock_handler)# Check that the request was modified in placeassert request.system_prompt.startswith(expected_prompt_prefix)@@ -1728,8 +1728,8 @@ def test_planning_middleware_custom_system_prompt() -> None:def mock_handler(req: ModelRequest) -> AIMessage:return AIMessage(content="mock response")- # Call on_model_call to trigger the middleware logic- middleware.on_model_call(request, mock_handler)+ # Call wrap_model_call to trigger the middleware logic+ middleware.wrap_model_call(request, mock_handler)# Check that the request was modified in placeassert request.system_prompt == f"Original prompt\n\n{custom_system_prompt}"@@ -1772,8 +1772,8 @@ def test_planning_middleware_custom_system_prompt_and_tool_description() -> Nonedef mock_handler(req: ModelRequest) -> AIMessage:return AIMessage(content="mock response")- # Call on_model_call to trigger the middleware logic- middleware.on_model_call(request, mock_handler)+ # Call wrap_model_call to trigger the middleware logic+ middleware.wrap_model_call(request, mock_handler)# Check that the request was modified in placeassert request.system_prompt == custom_system_prompt@@ -2044,12 +2044,12 @@ async def test_create_agent_async_invoke() -> None:async def abefore_model(self, state, runtime) -> None:calls.append("AsyncMiddleware.abefore_model")- async def aon_model_call(+ async def awrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], Awaitable[AIMessage]],) -> AIMessage:- calls.append("AsyncMiddleware.aon_model_call")+ calls.append("AsyncMiddleware.awrap_model_call")request.messages.append(HumanMessage("async middleware message"))return await handler(request)@@ -2088,11 +2088,11 @@ async def test_create_agent_async_invoke() -> None:assert result["messages"][1].content == "async middleware message"assert calls == ["AsyncMiddleware.abefore_model",- "AsyncMiddleware.aon_model_call",+ "AsyncMiddleware.awrap_model_call","AsyncMiddleware.aafter_model","my_tool","AsyncMiddleware.abefore_model",- "AsyncMiddleware.aon_model_call",+ "AsyncMiddleware.awrap_model_call","AsyncMiddleware.aafter_model",]@@ -2105,12 +2105,12 @@ async def test_create_agent_async_invoke_multiple_middleware() -> None:async def abefore_model(self, state, runtime) -> None:calls.append("AsyncMiddlewareOne.abefore_model")- async def aon_model_call(+ async def awrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], Awaitable[AIMessage]],) -> AIMessage:- calls.append("AsyncMiddlewareOne.aon_model_call")+ calls.append("AsyncMiddlewareOne.awrap_model_call")return await handler(request)async def aafter_model(self, state, runtime) -> None:@@ -2120,12 +2120,12 @@ async def test_create_agent_async_invoke_multiple_middleware() -> None:async def abefore_model(self, state, runtime) -> None:calls.append("AsyncMiddlewareTwo.abefore_model")- async def aon_model_call(+ async def awrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], Awaitable[AIMessage]],) -> AIMessage:- calls.append("AsyncMiddlewareTwo.aon_model_call")+ calls.append("AsyncMiddlewareTwo.awrap_model_call")return await handler(request)async def aafter_model(self, state, runtime) -> None:@@ -2143,8 +2143,8 @@ async def test_create_agent_async_invoke_multiple_middleware() -> None:assert calls == ["AsyncMiddlewareOne.abefore_model","AsyncMiddlewareTwo.abefore_model",- "AsyncMiddlewareOne.aon_model_call",- "AsyncMiddlewareTwo.aon_model_call",+ "AsyncMiddlewareOne.awrap_model_call",+ "AsyncMiddlewareTwo.awrap_model_call","AsyncMiddlewareTwo.aafter_model","AsyncMiddlewareOne.aafter_model",]@@ -2193,12 +2193,12 @@ async def test_create_agent_mixed_sync_async_middleware() -> None:def before_model(self, state, runtime) -> None:calls.append("SyncMiddleware.before_model")- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],) -> AIMessage:- calls.append("SyncMiddleware.on_model_call")+ calls.append("SyncMiddleware.wrap_model_call")return handler(request)def after_model(self, state, runtime) -> None:@@ -2208,12 +2208,12 @@ async def test_create_agent_mixed_sync_async_middleware() -> None:async def abefore_model(self, state, runtime) -> None:calls.append("AsyncMiddleware.abefore_model")- async def aon_model_call(+ async def awrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], Awaitable[AIMessage]],) -> AIMessage:- calls.append("AsyncMiddleware.aon_model_call")+ calls.append("AsyncMiddleware.awrap_model_call")return await handler(request)async def aafter_model(self, state, runtime) -> None:@@ -2229,20 +2229,20 @@ async def test_create_agent_mixed_sync_async_middleware() -> None:result = await agent.ainvoke({"messages": [HumanMessage("hello")]})# In async mode, both sync and async middleware should work- # Note: Sync on_model_call is not called when running in async mode,+ # Note: Sync wrap_model_call is not called when running in async mode,# as the async version is preferredassert calls == ["SyncMiddleware.before_model","AsyncMiddleware.abefore_model",- "AsyncMiddleware.aon_model_call",+ "AsyncMiddleware.awrap_model_call","AsyncMiddleware.aafter_model","SyncMiddleware.after_model",]-# Tests for on_model_call hook-def test_on_model_call_hook() -> None:- """Test that on_model_call hook is called on model errors."""+# Tests for wrap_model_call hook+def test_wrap_model_call_hook() -> None:+ """Test that wrap_model_call hook is called on model errors."""call_count = {"value": 0}class FailingModel(BaseChatModel):@@ -2265,7 +2265,7 @@ def test_on_model_call_hook() -> None:super().__init__()self.retry_count = 0- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):try:return handler(request)except Exception:@@ -2287,8 +2287,8 @@ def test_on_model_call_hook() -> None:assert result["messages"][1].content == "Success on retry"-def test_on_model_call_retry_count() -> None:- """Test that on_model_call can retry multiple times."""+def test_wrap_model_call_retry_count() -> None:+ """Test that wrap_model_call can retry multiple times."""class AlwaysFailingModel(BaseChatModel):"""Model that always fails."""@@ -2305,7 +2305,7 @@ def test_on_model_call_retry_count() -> None:super().__init__()self.attempts = []- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):max_retries = 3last_exception = Nonefor attempt in range(max_retries):@@ -2333,7 +2333,7 @@ def test_on_model_call_retry_count() -> None:assert tracker.attempts == [1, 2, 3]-def test_on_model_call_no_retry() -> None:+def test_wrap_model_call_no_retry() -> None:"""Test that error is propagated when middleware doesn't retry."""class FailingModel(BaseChatModel):@@ -2347,7 +2347,7 @@ def test_on_model_call_no_retry() -> None:return "failing"class NoRetryMiddleware(AgentMiddleware):- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):return handler(request)agent = create_agent(model=FailingModel(), middleware=[NoRetryMiddleware()])@@ -2443,7 +2443,7 @@ def test_model_fallback_middleware_initialization() -> None:assert len(middleware.models) == 2-def test_on_model_call_max_attempts() -> None:+def test_wrap_model_call_max_attempts() -> None:"""Test that middleware controls termination via retry limits."""class AlwaysFailingModel(BaseChatModel):@@ -2464,7 +2464,7 @@ def test_on_model_call_max_attempts() -> None:self.max_retries = max_retriesself.attempt_count = 0- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):last_exception = Nonefor attempt in range(self.max_retries):self.attempt_count += 1@@ -2491,8 +2491,8 @@ def test_on_model_call_max_attempts() -> None:assert middleware.attempt_count == 10-async def test_on_model_call_async() -> None:- """Test on_model_call hook with async model execution."""+async def test_wrap_model_call_async() -> None:+ """Test wrap_model_call hook with async model execution."""call_count = {"value": 0}class AsyncFailingModel(BaseChatModel):@@ -2518,7 +2518,7 @@ async def test_on_model_call_async() -> None:super().__init__()self.retry_count = 0- async def aon_model_call(self, request, handler):+ async def awrap_model_call(self, request, handler):try:return await handler(request)except Exception:@@ -2540,7 +2540,7 @@ async def test_on_model_call_async() -> None:assert result["messages"][1].content == "Async retry success"-def test_on_model_call_rewrite_response() -> None:+def test_wrap_model_call_rewrite_response() -> None:"""Test that middleware can rewrite model responses."""class SimpleModel(BaseChatModel):@@ -2558,7 +2558,7 @@ def test_on_model_call_rewrite_response() -> None:class ResponseRewriteMiddleware(AgentMiddleware):"""Middleware that rewrites the response."""- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):result = handler(request)# Rewrite the response@@ -2575,7 +2575,7 @@ def test_on_model_call_rewrite_response() -> None:assert result["messages"][1].content == "REWRITTEN: Original response"-def test_on_model_call_convert_error_to_response() -> None:+def test_wrap_model_call_convert_error_to_response() -> None:"""Test that middleware can convert errors to successful responses."""class AlwaysFailingModel(BaseChatModel):@@ -2591,7 +2591,7 @@ def test_on_model_call_convert_error_to_response() -> None:class ErrorToResponseMiddleware(AgentMiddleware):"""Middleware that converts errors to success responses."""- def on_model_call(self, request, handler):+ def wrap_model_call(self, request, handler):try:return handler(request)except Exception as e:@@ -2615,7 +2615,7 @@ def test_create_agent_sync_invoke_with_only_async_middleware_raises_error() -> N"""Test that sync invoke with only async middleware works via run_in_executor."""class AsyncOnlyMiddleware(AgentMiddleware):- async def aon_model_call(+ async def awrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], Awaitable[AIMessage]],@@ -2646,20 +2646,20 @@ def test_create_agent_sync_invoke_with_mixed_middleware() -> None:async def abefore_model(self, state, runtime) -> None:calls.append("MixedMiddleware.abefore_model")- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],) -> AIMessage:- calls.append("MixedMiddleware.on_model_call")+ calls.append("MixedMiddleware.wrap_model_call")return handler(request)- async def aon_model_call(+ async def awrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], Awaitable[AIMessage]],) -> AIMessage:- calls.append("MixedMiddleware.aon_model_call")+ calls.append("MixedMiddleware.awrap_model_call")return await handler(request)agent = create_agent(@@ -2674,5 +2674,5 @@ def test_create_agent_sync_invoke_with_mixed_middleware() -> None:# In sync mode, only sync methods should be calledassert calls == ["MixedMiddleware.before_model",- "MixedMiddleware.on_model_call",+ "MixedMiddleware.wrap_model_call",]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 eafec1c8e8..7663616bbc 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@@ -1,4 +1,4 @@-"""Consolidated tests for middleware decorators: before_model, after_model, and on_model_call."""+"""Consolidated tests for middleware decorators: before_model, after_model, and wrap_model_call."""import pytestfrom typing import Any@@ -17,7 +17,7 @@ from langchain.agents.middleware.types import (before_model,after_model,dynamic_prompt,- on_model_call,+ wrap_model_call,hook_config,)from langchain.agents.factory import create_agent, _get_can_jump_to@@ -85,9 +85,9 @@ def test_after_model_decorator() -> None:def test_on_model_call_decorator() -> None:- """Test on_model_call decorator with all configuration options."""+ """Test wrap_model_call decorator with all configuration options."""- @on_model_call(state_schema=CustomState, tools=[test_tool], name="CustomOnModelCall")+ @wrap_model_call(state_schema=CustomState, tools=[test_tool], name="CustomOnModelCall")def custom_on_model_call(request, handler):request.system_prompt = "Modified"return handler(request)@@ -113,7 +113,7 @@ def test_on_model_call_decorator() -> None:def mock_handler(req):return AIMessage(content=f"Handled with prompt: {req.system_prompt}")- result = custom_on_model_call.on_model_call(original_request, mock_handler)+ result = custom_on_model_call.wrap_model_call(original_request, mock_handler)assert result.content == "Handled with prompt: Modified"@@ -126,7 +126,7 @@ def test_all_decorators_integration() -> None:call_order.append("before")return None- @on_model_call+ @wrap_model_calldef track_on_call(request, handler):call_order.append("on_call")return handler(request)@@ -152,7 +152,7 @@ def test_decorators_use_function_names_as_default() -> None:def my_before_hook(state: AgentState, runtime: Runtime) -> None:return None- @on_model_call+ @wrap_model_calldef my_on_call_hook(request, handler):return handler(request)@@ -272,9 +272,9 @@ def test_async_after_model_decorator() -> None:def test_async_on_model_call_decorator() -> None:- """Test on_model_call decorator with async function."""+ """Test wrap_model_call decorator with async function."""- @on_model_call(state_schema=CustomState, tools=[test_tool], name="AsyncOnModelCall")+ @wrap_model_call(state_schema=CustomState, tools=[test_tool], name="AsyncOnModelCall")async def async_on_model_call(request, handler):request.system_prompt = "Modified async"return await handler(request)@@ -296,11 +296,11 @@ def test_mixed_sync_async_decorators() -> None:async def async_before(state: AgentState, runtime: Runtime) -> None:return None- @on_model_call(name="MixedOnModelCall")+ @wrap_model_call(name="MixedOnModelCall")def sync_on_call(request, handler):return handler(request)- @on_model_call(name="MixedOnModelCall")+ @wrap_model_call(name="MixedOnModelCall")async def async_on_call(request, handler):return await handler(request)@@ -321,7 +321,7 @@ async def test_async_decorators_integration() -> None:call_order.append("async_before")return None- @on_model_call+ @wrap_model_callasync def track_async_on_call(request, handler):call_order.append("async_on_call")return await handler(request)@@ -356,12 +356,12 @@ async def test_mixed_sync_async_decorators_integration() -> None:call_order.append("async_before")return None- @on_model_call+ @wrap_model_calldef track_sync_on_call(request, handler):call_order.append("sync_on_call")return handler(request)- @on_model_call+ @wrap_model_callasync def track_async_on_call(request, handler):call_order.append("async_on_call")return await handler(request)@@ -390,7 +390,7 @@ async def test_mixed_sync_async_decorators_integration() -> None:# Agent is already compiledawait agent.ainvoke({"messages": [HumanMessage("Hello")]})- # In async mode, only async on_model_call is invoked (not sync)+ # In async mode, only async wrap_model_call is invoked (not sync)# Sync before_model and after_model are still called via run_in_executorassert call_order == ["sync_before",@@ -595,7 +595,7 @@ def test_dynamic_prompt_decorator() -> None:def mock_handler(req):return AIMessage(content=req.system_prompt)- result = my_prompt.on_model_call(original_request, mock_handler)+ result = my_prompt.wrap_model_call(original_request, mock_handler)assert result.content == "Dynamic test prompt"@@ -622,7 +622,7 @@ def test_dynamic_prompt_uses_state() -> None:def mock_handler(req):return AIMessage(content=req.system_prompt)- result = custom_prompt.on_model_call(original_request, mock_handler)+ result = custom_prompt.wrap_model_call(original_request, mock_handler)assert result.content == "Prompt with 2 messages"@@ -708,7 +708,7 @@ def test_dynamic_prompt_multiple_in_sequence() -> None:return "Second prompt."# When used together, the last middleware in the list should win- # since they're both on_model_call hooks composed in sequence+ # since they're both wrap_model_call hooks composed in sequenceagent = create_agent(model=FakeToolCallingModel(), middleware=[first_prompt, second_prompt])# Agent is already compileddiff --git a/libs/langchain_v1/tests/unit_tests/agents/test_middleware_tools.py b/libs/langchain_v1/tests/unit_tests/agents/test_middleware_tools.pyindex 01a3419b4d..b9a9336a3d 100644--- a/libs/langchain_v1/tests/unit_tests/agents/test_middleware_tools.py+++ b/libs/langchain_v1/tests/unit_tests/agents/test_middleware_tools.py@@ -27,7 +27,7 @@ def test_model_request_tools_are_base_tools() -> None:return f"Result: {expression}"class RequestCapturingMiddleware(AgentMiddleware):- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],@@ -73,7 +73,7 @@ def test_middleware_can_modify_tools() -> None:return "C"class ToolFilteringMiddleware(AgentMiddleware):- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],@@ -118,7 +118,7 @@ def test_unknown_tool_raises_error() -> None:return "unknown"class BadMiddleware(AgentMiddleware):- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],@@ -157,7 +157,7 @@ def test_middleware_can_add_and_remove_tools() -> None:class ConditionalToolMiddleware(AgentMiddleware[AdminState]):state_schema = AdminState- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],@@ -195,7 +195,7 @@ def test_empty_tools_list_is_valid() -> None:return "result"class NoToolsMiddleware(AgentMiddleware):- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],@@ -238,7 +238,7 @@ def test_tools_preserved_across_multiple_middleware() -> None:return "C"class FirstMiddleware(AgentMiddleware):- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],@@ -249,7 +249,7 @@ def test_tools_preserved_across_multiple_middleware() -> None:return handler(request)class SecondMiddleware(AgentMiddleware):- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], AIMessage],diff --git a/libs/langchain_v1/tests/unit_tests/agents/test_response_format.py b/libs/langchain_v1/tests/unit_tests/agents/test_response_format.pyindex c9cba1ea36..89f2a6aef5 100644--- a/libs/langchain_v1/tests/unit_tests/agents/test_response_format.py+++ b/libs/langchain_v1/tests/unit_tests/agents/test_response_format.py@@ -727,7 +727,7 @@ class TestDynamicModelWithResponseFormat:# Create middleware that swaps the model in the requestclass ModelSwappingMiddleware(AgentMiddleware):- def on_model_call(+ def wrap_model_call(self,request: ModelRequest,handler: Callable[[ModelRequest], CoreAIMessage],