Skip to content

The agent engineering platform.

fix(anthropic): preserve caller `tool_choice` (#39206)

ccurme8034b64e66f2
diff --git a/libs/partners/anthropic/langchain_anthropic/chat_models.py b/libs/partners/anthropic/langchain_anthropic/chat_models.py
index 998338c418..9f68a7e214 100644
--- a/libs/partners/anthropic/langchain_anthropic/chat_models.py
+++ b/libs/partners/anthropic/langchain_anthropic/chat_models.py
@@ -2089,7 +2089,7 @@ class ChatAnthropic(BaseChatModel):
if not tool_choice:
pass
elif isinstance(tool_choice, dict):
- kwargs["tool_choice"] = tool_choice
+ kwargs["tool_choice"] = tool_choice.copy()
elif isinstance(tool_choice, str) and tool_choice in ("any", "auto"):
kwargs["tool_choice"] = {"type": tool_choice}
elif isinstance(tool_choice, str):
diff --git a/libs/partners/anthropic/tests/unit_tests/test_chat_models.py b/libs/partners/anthropic/tests/unit_tests/test_chat_models.py
index 6915a65bbf..0f27b893a6 100644
--- a/libs/partners/anthropic/tests/unit_tests/test_chat_models.py
+++ b/libs/partners/anthropic/tests/unit_tests/test_chat_models.py
@@ -1603,6 +1603,25 @@ def test_anthropic_bind_tools_tool_choice() -> None:
}
+def test_anthropic_bind_tools_does_not_mutate_tool_choice() -> None:
+ chat_model = ChatAnthropic( # type: ignore[call-arg, call-arg]
+ model=MODEL_NAME,
+ anthropic_api_key="secret-api-key",
+ )
+ tool_choice = {"type": "tool", "name": "GetWeather"}
+
+ chat_model_with_tools = chat_model.bind_tools(
+ [GetWeather], tool_choice=tool_choice, parallel_tool_calls=False
+ )
+
+ assert tool_choice == {"type": "tool", "name": "GetWeather"}
+ assert cast("RunnableBinding", chat_model_with_tools).kwargs["tool_choice"] == {
+ "type": "tool",
+ "name": "GetWeather",
+ "disable_parallel_tool_use": True,
+ }
+
+
def test_fine_grained_tool_streaming_beta() -> None:
"""Test that fine-grained tool streaming beta can be enabled."""
# Test with betas parameter at initialization