The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
fix(langchain): handle import error in `LLMToolEmulator` by `model` (#39290)
Nishitha Ma4fb5f1a7a84
diff --git a/libs/langchain_v1/langchain/agents/middleware/tool_emulator.py b/libs/langchain_v1/langchain/agents/middleware/tool_emulator.pyindex fe0b1766ea..51e3941e8e 100644--- a/libs/langchain_v1/langchain/agents/middleware/tool_emulator.py+++ b/libs/langchain_v1/langchain/agents/middleware/tool_emulator.py@@ -2,6 +2,7 @@from __future__ import annotations+import warningsfrom typing import TYPE_CHECKING, Any, Genericfrom langchain_core.language_models.chat_models import BaseChatModel@@ -22,6 +23,8 @@ if TYPE_CHECKING:from langchain.agents.middleware.types import ToolCallRequestfrom langchain.tools import BaseTool+_DEFAULT_EMULATOR_MODEL = "anthropic:claude-sonnet-4-5-20250929"+class LLMToolEmulator(AgentMiddleware[AgentState[Any], ContextT], Generic[ContextT]):"""Emulates specified tools using an LLM instead of executing them.@@ -90,7 +93,14 @@ class LLMToolEmulator(AgentMiddleware[AgentState[Any], ContextT], Generic[ContexIf empty list, no tools will be emulated.model: Model to use for emulation.- Defaults to `'anthropic:claude-sonnet-4-5-20250929'`.+ Defaults to `'anthropic:claude-sonnet-4-5-20250929'`, which requires+ `langchain-anthropic` to be installed.++ !!! warning "Deprecated"+ Relying on the implicit default is deprecated and will be+ removed in a future release, since it makes this middleware+ depend on `langchain-anthropic` even when unspecified. Pass+ `model` explicitly instead.Can be a model identifier string or `BaseChatModel` instance."""@@ -101,7 +111,7 @@ class LLMToolEmulator(AgentMiddleware[AgentState[Any], ContextT], Generic[Contexself.emulate_all = tools is Noneself.tools_to_emulate: set[str] = set()- if not self.emulate_all and tools is not None:+ if tools is not None:for tool in tools:if isinstance(tool, str):self.tools_to_emulate.add(tool)@@ -111,7 +121,22 @@ class LLMToolEmulator(AgentMiddleware[AgentState[Any], ContextT], Generic[Contex# Initialize emulator modelif model is None:- self.model = init_chat_model("anthropic:claude-sonnet-4-5-20250929", temperature=1)+ warnings.warn(+ "LLMToolEmulator's default model "+ f"({_DEFAULT_EMULATOR_MODEL!r}) is deprecated and will be removed "+ "in a future release. Pass `model` explicitly instead.",+ DeprecationWarning,+ stacklevel=2,+ )+ try:+ self.model = init_chat_model(_DEFAULT_EMULATOR_MODEL, temperature=1)+ except ImportError as e:+ msg = (+ "LLMToolEmulator's default model requires `langchain-anthropic` "+ "to be installed. Install it with `pip install langchain-anthropic`, "+ "or pass `model=...` explicitly to use a different provider."+ )+ raise ImportError(msg) from eelif isinstance(model, BaseChatModel):self.model = modelelse:diff --git a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_emulator.py b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_emulator.pyindex d2a28c975f..54feacc868 100644--- a/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_emulator.py+++ b/libs/langchain_v1/tests/unit_tests/agents/middleware/implementations/test_tool_emulator.py@@ -4,6 +4,7 @@ from collections.abc import Callable, Sequencefrom itertools import cyclefrom typing import Any, Literal+import pytestfrom langchain_core.language_models import LanguageModelInputfrom langchain_core.language_models.chat_models import BaseChatModelfrom langchain_core.language_models.fake_chat_models import GenericFakeChatModel@@ -12,6 +13,7 @@ from langchain_core.outputs import ChatGeneration, ChatResultfrom langchain_core.runnables import Runnable, RunnableConfigfrom langchain_core.tools import BaseTool, toolfrom pydantic import BaseModel, Field+from pytest_mock import MockerFixturefrom typing_extensions import overridefrom langchain.agents import create_agent@@ -460,17 +462,38 @@ class TestLLMToolEmulatorModelConfiguration:# Should use the custom model for emulationassert isinstance(result["messages"][-1], AIMessage)- def test_default_model_used_when_none(self) -> None:- """Test that default model is used when model=None."""- # Just test that initialization doesn't fail - don't require anthropic package- # The actual default model requires langchain_anthropic which may not be installed- try:- emulator = LLMToolEmulator(tools=["get_weather"], model=None)- assert emulator.model is not None- except ImportError:- # If anthropic isn't installed, that's fine for this unit test- # The integration tests will verify the full functionality- pass+ def test_default_model_deprecated_and_missing_langchain_anthropic_raises_clear_error(+ self,+ ) -> None:+ """Test the `model=None` default path without `langchain-anthropic` installed.++ Regression test: omitting `model` used to either silently depend on+ `langchain-anthropic` or (in an earlier draft of this fix) raise a+ `TypeError` for a previously-supported call shape. It should instead+ keep working when a model provider is available, and raise an+ actionable `ImportError` (plus a `DeprecationWarning`) when it isn't.+ """+ with (+ pytest.warns(DeprecationWarning, match="deprecated"),+ pytest.raises(ImportError, match="langchain-anthropic"),+ ):+ LLMToolEmulator(tools=["get_weather"])++ def test_default_model_used_when_none(self, mocker: MockerFixture) -> None:+ """Test that the default model is used and a deprecation warning is raised."""+ fake_model = FakeEmulatorModel(responses=["response"])+ init_chat_model_mock = mocker.patch(+ "langchain.agents.middleware.tool_emulator.init_chat_model",+ return_value=fake_model,+ )++ with pytest.warns(DeprecationWarning, match="deprecated"):+ emulator = LLMToolEmulator(tools=["get_weather"])++ assert emulator.model is fake_model+ init_chat_model_mock.assert_called_once_with(+ "anthropic:claude-sonnet-4-5-20250929", temperature=1+ )class TestLLMToolEmulatorAsync: