Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(tool): add func_name parameter to support custom tool renaming (#1115)
qbc8c61aebf1ac4
diff --git a/src/agentscope/tool/_toolkit.py b/src/agentscope/tool/_toolkit.pyindex 13e499172..ac7f9f99a 100644--- a/src/agentscope/tool/_toolkit.py+++ b/src/agentscope/tool/_toolkit.py@@ -208,6 +208,7 @@ Check "{dir}/SKILL.md" for how to use this skill"""tool_func: ToolFunction,group_name: str | Literal["basic"] = "basic",preset_kwargs: dict[str, JSONSerializableObject] | None = None,+ func_name: str | None = None,func_description: str | None = None,json_schema: dict | None = None,include_long_description: bool = True,@@ -246,6 +247,11 @@ Check "{dir}/SKILL.md" for how to use this skill"""optional):Preset arguments by the user, which will not be included inthe JSON schema, nor exposed to the agent.+ func_name (`str | None`, optional):+ The custom function name, which should be consistent with the+ name in function_description and json_schema (if provided).+ By default, the function name will be extracted from the+ function automatically.func_description (`str | None`, optional):The function description. If not provided, the descriptionwill be extracted from the docstring automatically.@@ -301,7 +307,7 @@ Check "{dir}/SKILL.md" for how to use this skill"""# Handle MCP tool function and regular function respectivelymcp_name = Noneif isinstance(tool_func, MCPToolFunction):- func_name = tool_func.name+ input_func_name = tool_func.nameoriginal_func = tool_func.__call__json_schema = json_schema or tool_func.json_schemamcp_name = tool_func.mcp_name@@ -323,7 +329,7 @@ Check "{dir}/SKILL.md" for how to use this skill"""**(preset_kwargs or {}),}- func_name = tool_func.func.__name__+ input_func_name = tool_func.func.__name__original_func = tool_func.funcjson_schema = json_schema or _parse_tool_function(tool_func.func,@@ -334,7 +340,7 @@ Check "{dir}/SKILL.md" for how to use this skill"""else:# normal function- func_name = tool_func.__name__+ input_func_name = tool_func.__name__original_func = tool_funcjson_schema = json_schema or _parse_tool_function(tool_func,@@ -343,6 +349,15 @@ Check "{dir}/SKILL.md" for how to use this skill"""include_var_keyword=include_var_keyword,)+ # Record the original function name if the func_name is given+ original_name = input_func_name if func_name else None++ # Use the given function name if provided+ func_name = func_name or input_func_name++ # Always set the function name in json_schema+ json_schema["function"]["name"] = func_name+# Override the description if providedif func_description:json_schema["function"]["description"] = func_description@@ -375,6 +390,7 @@ Check "{dir}/SKILL.md" for how to use this skill"""original_func=original_func,json_schema=json_schema,preset_kwargs=preset_kwargs or {},+ original_name=original_name,extended_model=None,mcp_name=mcp_name,postprocess_func=postprocess_func,@@ -425,7 +441,7 @@ Check "{dir}/SKILL.md" for how to use this skill""")# Replace the function name with the new one- func_obj.original_name = func_name+ func_obj.original_name = original_name or func_namefunc_obj.name = new_func_namefunc_obj.json_schema["function"]["name"] = new_func_namediff --git a/tests/toolkit_basic_test.py b/tests/toolkit_basic_test.pyindex cf689ec6c..a5101bfcf 100644--- a/tests/toolkit_basic_test.py+++ b/tests/toolkit_basic_test.py@@ -1,4 +1,5 @@# -*- coding: utf-8 -*-+# pylint: disable=too-many-lines# mypy: disable-error-code="index""""Test toolkit module in agentscope."""import asyncio@@ -974,6 +975,102 @@ class ToolkitBasicTest(IsolatedAsyncioTestCase):"Received: a=1, b=test, c=[1, 2, 3], d=xyz",)+ async def test_func_name_parameter(self) -> None:+ """Test func_name parameter for custom tool renaming."""+ # Test 1: Regular function with func_name+ self.toolkit.register_tool_function(+ sync_func,+ func_name="custom_sync_func",+ )+ self.assertIn("custom_sync_func", self.toolkit.tools)+ self.assertNotIn("sync_func", self.toolkit.tools)++ # Verify the JSON schema uses the custom name+ schemas = self.toolkit.get_json_schemas()+ self.assertEqual(schemas[0]["function"]["name"], "custom_sync_func")++ # Verify original_name is set when func_name is provided+ tool_obj = self.toolkit.tools["custom_sync_func"]+ self.assertEqual(tool_obj.original_name, "sync_func")++ # Test 2: Regular function without func_name (backward compatibility)+ def another_func(x: int) -> ToolResponse:+ """Another test function."""+ return ToolResponse(content=[TextBlock(type="text", text=str(x))])++ self.toolkit.register_tool_function(another_func)+ self.assertIn("another_func", self.toolkit.tools)+ tool_obj = self.toolkit.tools["another_func"]+ self.assertIsNone(tool_obj.original_name)++ # Test 3: Partial function with func_name+ partial_func = partial(sync_func, arg1=10)+ self.toolkit.register_tool_function(+ partial_func,+ func_name="custom_partial_func",+ )+ self.assertIn("custom_partial_func", self.toolkit.tools)+ tool_obj = self.toolkit.tools["custom_partial_func"]+ self.assertEqual(tool_obj.original_name, "sync_func")++ # Test 4: func_name with namesake_strategy="rename"+ self.toolkit.register_tool_function(+ sync_func,+ func_name="custom_sync_func", # Already exists+ namesake_strategy="rename",+ )+ # Should create a new name with random suffix+ renamed_tools = [+ name+ for name in self.toolkit.tools+ if name.startswith("custom_sync_func_")+ ]+ self.assertEqual(len(renamed_tools), 1)+ renamed_name = renamed_tools[0]+ tool_obj = self.toolkit.tools[renamed_name]+ # original_name should be "sync_func" (the true original function name)+ # because original_name records the actual function name, not the+ # func_name+ self.assertEqual(tool_obj.original_name, "sync_func")++ # Test 5: func_name with namesake_strategy="rename" but no func_name+ # (should use original function name as original_name)+ def test_func() -> ToolResponse:+ """Test function."""+ return ToolResponse(content=[TextBlock(type="text", text="test")])++ self.toolkit.register_tool_function(test_func)+ self.toolkit.register_tool_function(+ test_func,+ namesake_strategy="rename",+ )+ # Find the renamed tool+ renamed_test_tools = [+ name+ for name in self.toolkit.tools+ if name.startswith("test_func_")+ ]+ self.assertEqual(len(renamed_test_tools), 1)+ renamed_test_name = renamed_test_tools[0]+ tool_obj = self.toolkit.tools[renamed_test_name]+ # original_name should be "test_func" (the original function name)+ self.assertEqual(tool_obj.original_name, "test_func")++ # Test 6: Verify tool can be called with custom name+ res = await self.toolkit.call_tool_function(+ ToolUseBlock(+ type="tool_use",+ id="123",+ name="custom_sync_func",+ input={"arg1": 42},+ ),+ )+ async for chunk in res:+ self.assertEqual(+ chunk.content[0]["text"],+ "arg1: 42, arg2: None",+ )+async def asyncTearDown(self) -> None:"""Clean up after each test."""self.toolkit = None