Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
feat(tool): support custom input_schema in FunctionTool (#2378)
DavdGao9081bd774195
diff --git a/src/agentscope/tool/_adapters.py b/src/agentscope/tool/_adapters.pyindex b2ba5357c..4c623f79b 100644--- a/src/agentscope/tool/_adapters.py+++ b/src/agentscope/tool/_adapters.py@@ -9,6 +9,7 @@ from typing import Callable, Any, AsyncGenerator, Generatorfrom mcp import ClientSessionimport mcp+from pydantic import BaseModelfrom ._types import Functionfrom ._base import ToolBase, ToolMiddlewareBase@@ -17,7 +18,11 @@ from ..permission import (PermissionDecision,)from ._response import ToolChunk-from ._utils import _extract_func_description, _extract_input_schema+from ._utils import (+ _extract_func_description,+ _extract_input_schema,+ _remove_title_field,+)from .._logging import loggerfrom ..message import (TextBlock,@@ -51,6 +56,7 @@ class FunctionTool(ToolBase):func: Function,name: str | None = None,description: str | None = None,+ input_schema: dict | type[BaseModel] | None = None,is_concurrency_safe: bool = True,is_read_only: bool = False,is_state_injected: bool = False,@@ -65,6 +71,14 @@ class FunctionTool(ToolBase):Custom tool name. If None, uses the function name.description (`str | None`, optional):Custom tool description. If None, extracts from docstring.+ input_schema (`dict | type[BaseModel] | None`, optional):+ Custom input schema for the tool, either a JSON schema+ dict or a pydantic ``BaseModel`` subclass (converted via+ its ``model_json_schema()``). If None, generates the+ schema from the function's type annotations and+ docstring, where constraints (e.g. enums, value ranges)+ can be expressed with ``typing.Literal`` and+ ``typing.Annotated`` with ``pydantic.Field``.is_concurrency_safe (`bool`, optional):Whether this tool is safe to call concurrently.is_read_only (`bool`, optional):@@ -79,7 +93,14 @@ class FunctionTool(ToolBase):self.description = description or _extract_func_description(func.__doc__ or "",)- self.input_schema = _extract_input_schema(func)+ if isinstance(input_schema, type) and issubclass(+ input_schema,+ BaseModel,+ ):+ input_schema = _remove_title_field(+ input_schema.model_json_schema(),+ )+ self.input_schema = input_schema or _extract_input_schema(func)self.is_concurrency_safe = is_concurrency_safeself.is_read_only = is_read_onlyself.is_state_injected = is_state_injecteddiff --git a/tests/toolkit_test.py b/tests/toolkit_test.pyindex 194fd1540..5fb1b9ed1 100644--- a/tests/toolkit_test.py+++ b/tests/toolkit_test.py@@ -3,11 +3,12 @@"""Toolkit test case."""import base64import json-from typing import Any, AsyncGenerator, Generator+from typing import Any, AsyncGenerator, Generator, Literalfrom unittest import TestCasefrom unittest.async_case import IsolatedAsyncioTestCase+from pydantic import BaseModel, Fieldfrom utils import AnyStringfrom agentscope.mcp import HttpMCPConfig, MCPClient@@ -1134,6 +1135,125 @@ class RegisterFunctionTest(IsolatedAsyncioTestCase):f"started{expected_dict_text}",)+ async def test_custom_input_schema(self) -> None:+ """Test overriding the auto-extracted schema with a custom one."""++ def set_mode(mode: str) -> str:+ """Set the working mode.++ Args:+ mode: The mode to use+ """+ return f"Mode set to {mode}"++ toolkit = Toolkit(+ tools=[+ FunctionTool(+ set_mode,+ input_schema={+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "description": "The mode to use",+ "enum": ["fast", "slow"],+ },+ },+ "required": ["mode"],+ },+ ),+ ],+ )++ schemas = await toolkit.get_tool_schemas()+ self.assertListEqual(+ schemas,+ [+ {+ "type": "function",+ "function": {+ "name": "set_mode",+ "description": "Set the working mode.",+ "parameters": {+ "type": "object",+ "properties": {+ "mode": {+ "type": "string",+ "description": "The mode to use",+ "enum": ["fast", "slow"],+ },+ },+ "required": ["mode"],+ },+ },+ },+ ],+ )++ async def test_base_model_input_schema(self) -> None:+ """Test passing a pydantic BaseModel class as the input schema."""++ class SetModeInput(BaseModel):+ """The input model of the set_mode tool."""++ mode: Literal["fast", "slow"] = Field(+ description="The mode to use",+ )+ level: int = Field(+ default=5,+ ge=1,+ le=10,+ description="The level to use",+ )++ def set_mode(mode: str, level: int = 5) -> str:+ """Set the working mode."""+ return f"Mode set to {mode} at level {level}"++ toolkit = Toolkit(+ tools=[+ FunctionTool(+ set_mode,+ input_schema=SetModeInput,+ ),+ ],+ )++ schemas = await toolkit.get_tool_schemas()+ self.assertListEqual(+ schemas,+ [+ {+ "type": "function",+ "function": {+ "name": "set_mode",+ "description": "Set the working mode.",+ "parameters": {+ "type": "object",+ "description": (+ "The input model of the set_mode tool."+ ),+ "properties": {+ "mode": {+ "type": "string",+ "description": "The mode to use",+ "enum": ["fast", "slow"],+ },+ "level": {+ "type": "integer",+ "description": "The level to use",+ "default": 5,+ "minimum": 1,+ "maximum": 10,+ },+ },+ "required": ["mode"],+ },+ },+ },+ ],+ )+class ToolGroupTest(IsolatedAsyncioTestCase):"""The tool group test case."""