Skip to content

The agent engineering platform.

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.py
index 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 warnings
from typing import TYPE_CHECKING, Any, Generic
from langchain_core.language_models.chat_models import BaseChatModel
@@ -22,6 +23,8 @@ if TYPE_CHECKING:
from langchain.agents.middleware.types import ToolCallRequest
from 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[Contex
If 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[Contex
self.emulate_all = tools is None
self.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 model
if 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 e
elif isinstance(model, BaseChatModel):
self.model = model
else:
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.py
index 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, Sequence
from itertools import cycle
from typing import Any, Literal
+import pytest
from langchain_core.language_models import LanguageModelInput
from langchain_core.language_models.chat_models import BaseChatModel
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
@@ -12,6 +13,7 @@ from langchain_core.outputs import ChatGeneration, ChatResult
from langchain_core.runnables import Runnable, RunnableConfig
from langchain_core.tools import BaseTool, tool
from pydantic import BaseModel, Field
+from pytest_mock import MockerFixture
from typing_extensions import override
from langchain.agents import create_agent
@@ -460,17 +462,38 @@ class TestLLMToolEmulatorModelConfiguration:
# Should use the custom model for emulation
assert 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: