From 6a37899b39fb99b74a263daa099d853334e7d6bb Mon Sep 17 00:00:00 2001 From: Erick Friis Date: Thu, 19 Dec 2024 10:11:56 -0800 Subject: [PATCH] core: dont mutate tool_kwargs during tool run (#28824) fixes https://github.com/langchain-ai/langchain/issues/24621 --- libs/core/langchain_core/tools/base.py | 4 ++-- libs/core/tests/unit_tests/test_tools.py | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/libs/core/langchain_core/tools/base.py b/libs/core/langchain_core/tools/base.py index cf75528461415..625d532da3238 100644 --- a/libs/core/langchain_core/tools/base.py +++ b/libs/core/langchain_core/tools/base.py @@ -687,9 +687,9 @@ def run( context.run(_set_config_context, child_config) tool_args, tool_kwargs = self._to_args_and_kwargs(tool_input, tool_call_id) if signature(self._run).parameters.get("run_manager"): - tool_kwargs["run_manager"] = run_manager + tool_kwargs = tool_kwargs | {"run_manager": run_manager} if config_param := _get_runnable_config_param(self._run): - tool_kwargs[config_param] = config + tool_kwargs = tool_kwargs | {config_param: config} response = context.run(self._run, *tool_args, **tool_kwargs) if self.response_format == "content_and_artifact": if not isinstance(response, tuple) or len(response) != 2: diff --git a/libs/core/tests/unit_tests/test_tools.py b/libs/core/tests/unit_tests/test_tools.py index b21fc139a2154..c0d8c962dd31e 100644 --- a/libs/core/tests/unit_tests/test_tools.py +++ b/libs/core/tests/unit_tests/test_tools.py @@ -2268,3 +2268,20 @@ def foo(x: int) -> Bar: assert foo.invoke( {"type": "tool_call", "args": {"x": 0}, "name": "foo", "id": "bar"} ) == Bar(x=0) + + +def test_tool_mutate_input() -> None: + class MyTool(BaseTool): + name: str = "MyTool" + description: str = "a tool" + + def _run( + self, + x: str, + run_manager: Optional[CallbackManagerForToolRun] = None, + ) -> str: + return "hi" + + my_input = {"x": "hi"} + MyTool().invoke(my_input) + assert my_input == {"x": "hi"}