Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(tool): preserve annotations and docstrings for partial functions (#3257)
Jingbo Chai9b94a63407ec
diff --git a/src/agentscope/tool/_adapters.py b/src/agentscope/tool/_adapters.pyindex a199a81f0..798f8bada 100644--- a/src/agentscope/tool/_adapters.py+++ b/src/agentscope/tool/_adapters.py@@ -20,6 +20,8 @@ from ._response import ToolChunkfrom ._utils import (_extract_func_description,_extract_input_schema,+ _get_callable_docstring,+ _get_callable_name,_remove_title_field,)from .._logging import logger@@ -92,9 +94,9 @@ class FunctionTool(ToolBase):user will be asked to confirm the tool call."""super().__init__(middlewares=middlewares)- self.name = name or func.__name__+ self.name = name or _get_callable_name(func)self.description = description or _extract_func_description(- func.__doc__ or "",+ _get_callable_docstring(func),)if isinstance(input_schema, type) and issubclass(input_schema,diff --git a/src/agentscope/tool/_utils.py b/src/agentscope/tool/_utils.pyindex 672700d88..f64046d24 100644--- a/src/agentscope/tool/_utils.py+++ b/src/agentscope/tool/_utils.py@@ -2,12 +2,124 @@"""The tool module utils."""import inspectimport typing+from functools import partialfrom typing import Any, Dict, Callablefrom docstring_parser import parsefrom pydantic import Field, create_model, ConfigDict+def _get_callable_name(tool_func: Callable) -> str:+ """Get the effective name of a callable."""+ named_func = tool_func++ while isinstance(named_func, partial):+ explicit_name = vars(named_func).get("__name__")+ if explicit_name is not None:+ return explicit_name++ named_func = named_func.func++ return named_func.__name__+++def _get_callable_docstring(tool_func: Callable) -> str:+ """Get the effective docstring of a callable.++ An explicitly assigned partial docstring takes precedence. Otherwise,+ unwrap partial objects to avoid using ``functools.partial``'s generic+ documentation.+ """+ documented_func = tool_func++ while isinstance(documented_func, partial):+ if "__doc__" in vars(documented_func):+ return documented_func.__doc__ or ""++ documented_func = documented_func.func++ return documented_func.__doc__ or ""+++def _resolve_annotation(+ annotation: Any,+ globalns: dict[str, Any] | None,+) -> Any:+ """Resolve one annotation with the provided global namespace."""++ def _annotation_holder() -> None:+ pass++ _annotation_holder.__annotations__ = {+ "value": annotation,+ }+ return typing.get_type_hints(+ _annotation_holder,+ globalns=globalns,+ include_extras=True,+ )["value"]+++def _resolve_partial_type_hints(+ partial_func: partial,+ globalns: dict[str, Any] | None,+) -> dict[str, Any]:+ """Resolve each annotation on a partial independently."""+ raw_annotations = getattr(+ partial_func,+ "__annotations__",+ {},+ )+ if not isinstance(raw_annotations, dict):+ return {}++ type_hints = {}+ for name, annotation in raw_annotations.items():+ try:+ type_hints[name] = _resolve_annotation(+ annotation,+ globalns,+ )+ except Exception:+ continue++ return type_hints+++def _resolve_type_hints(tool_func: Callable) -> dict[str, Any]:+ """Resolve and merge annotations from a callable and its partials.++ Annotations are merged from the underlying callable to the outermost+ partial, allowing each partial to override selected annotations.+ """+ partial_funcs = []+ annotated_func = tool_func++ while isinstance(annotated_func, partial):+ partial_funcs.append(annotated_func)+ annotated_func = annotated_func.func++ try:+ type_hints = typing.get_type_hints(+ annotated_func,+ include_extras=True,+ )+ except Exception:+ type_hints = {}++ globalns = getattr(annotated_func, "__globals__", None)++ for partial_func in reversed(partial_funcs):+ type_hints.update(+ _resolve_partial_type_hints(+ partial_func,+ globalns,+ ),+ )++ return type_hints++def _remove_title_field(schema: dict) -> dict:"""Remove the title field from the JSON schema to avoidmisleading the LLM."""@@ -95,18 +207,13 @@ def _extract_input_schema(`dict`:The extracted input JSON schema."""- docstring = parse(tool_func.__doc__ or "")+ docstring = parse(_get_callable_docstring(tool_func))params_docstring = {_.arg_name: _.description for _ in docstring.params}# Under PEP 563 (`from __future__ import annotations`) the annotations# in the signature are raw strings, which pydantic cannot resolve# outside the function's own module. Resolve them here instead.- try:- type_hints = typing.get_type_hints(tool_func, include_extras=True)- except Exception:- # e.g. `functools.partial` objects, or annotations referencing- # TYPE_CHECKING-only names; fall back to the raw annotations- type_hints = {}+ type_hints = _resolve_type_hints(tool_func)# Create a dynamic model with the function signaturefields = {}diff --git a/tests/tool_lazy_annotations_test.py b/tests/tool_lazy_annotations_test.pyindex 6f4f50334..8018177f9 100644--- a/tests/tool_lazy_annotations_test.py+++ b/tests/tool_lazy_annotations_test.py@@ -8,6 +8,7 @@ resolved back to real types before being handed to pydantic."""from __future__ import annotations+from functools import partialfrom typing import Annotatedfrom unittest import TestCase@@ -23,6 +24,12 @@ class Location(BaseModel):city: str = Field(description="The city name")+class SearchQuery(BaseModel):+ """A structured catalog-search query."""++ text: str = Field(description="The query text")++def annotated_tool(query: Annotated[str, Field(description="The search query")],limit: int = 5,@@ -44,6 +51,36 @@ def model_tool(location: Location) -> str:return location.city+def catalog_search(+ catalog: str,+ query: Annotated[SearchQuery, Field(description="The search query")],+ limit: Annotated[int, Field(gt=0, description="Maximum results")] = 5,+) -> str:+ """Search a catalog."""+ return f"{catalog}:{query.text}:{limit}"+++def documented_search(catalog: str, query: str) -> str:+ """Search the selected catalog.++ Args:+ catalog: The catalog identifier.+ query: The query to run.+ """+ return f"{catalog}:{query}"+++def primitive_parameter_with_unresolvable_return(value: int) -> str:+ """Keep the parameter annotation usable when the return hint is not."""+ return str(value)+++primitive_parameter_with_unresolvable_return.__annotations__ = {+ "value": int,+ "return": "NotDefined",+}++class LazyAnnotationsTest(TestCase):"""Schema extraction must work with stringized annotations."""@@ -143,3 +180,226 @@ class LazyAnnotationsTest(TestCase):"required": ["query"],},)++ def test_positional_partial_resolves_lazy_model_annotations(self) -> None:+ """A partial keeps its signature while using its function's hints."""+ tool_func = partial(catalog_search, "catalog-a")+ expected = {+ "type": "object",+ "$defs": {+ "SearchQuery": {+ "type": "object",+ "description": "A structured catalog-search query.",+ "properties": {+ "text": {+ "type": "string",+ "description": "The query text",+ },+ },+ "required": ["text"],+ },+ },+ "properties": {+ "query": {+ "$ref": "#/$defs/SearchQuery",+ "description": "The search query",+ },+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "description": "Maximum results",+ "default": 5,+ },+ },+ "required": ["query"],+ }++ self.assertDictEqual(_extract_input_schema(tool_func), expected)+ self.assertDictEqual(+ FunctionTool(tool_func, name="catalog_search").input_schema,+ expected,+ )++ def test_nested_partial_uses_remaining_keyword_default(self) -> None:+ """Nested partials retain the signature-provided default."""+ tool_func = partial(partial(catalog_search, "catalog-a"), limit=3)+ schema = _extract_input_schema(tool_func)++ self.assertEqual(schema["required"], ["query"])+ self.assertEqual(schema["properties"]["limit"]["default"], 3)+ self.assertEqual(+ schema["properties"]["query"]["$ref"],+ "#/$defs/SearchQuery",+ )++ def test_partial_uses_its_own_annotations_before_underlying_function(+ self,+ ) -> None:+ """Explicit annotations on a partial override its function hints."""+ tool_func = partial(catalog_search, "catalog-a")+ tool_func.__annotations__ = {"query": str}++ self.assertDictEqual(+ _extract_input_schema(tool_func),+ {+ "type": "object",+ "properties": {+ "query": {"type": "string"},+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "description": "Maximum results",+ "default": 5,+ },+ },+ "required": ["query"],+ },+ )++ def test_partial_keeps_valid_annotation_override(self) -> None:+ """An invalid annotation does not discard valid overrides."""+ tool_func = partial(catalog_search, "catalog-a")+ tool_func.__annotations__ = {+ "query": str,+ "limit": "TotallyUnresolvable",+ }++ self.assertDictEqual(+ _extract_input_schema(tool_func),+ {+ "type": "object",+ "properties": {+ "query": {"type": "string"},+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "description": "Maximum results",+ "default": 5,+ },+ },+ "required": ["query"],+ },+ )++ def test_unresolvable_partial_annotation_keeps_function_hint(+ self,+ ) -> None:+ """An invalid partial annotation does not replace valid hints."""+ tool_func = partial(catalog_search, "catalog-a")+ tool_func.__annotations__ = {+ "query": "TotallyUnresolvable",+ }++ self.assertDictEqual(+ _extract_input_schema(tool_func),+ {+ "type": "object",+ "$defs": {+ "SearchQuery": {+ "type": "object",+ "description": "A structured catalog-search query.",+ "properties": {+ "text": {+ "type": "string",+ "description": "The query text",+ },+ },+ "required": ["text"],+ },+ },+ "properties": {+ "query": {+ "$ref": "#/$defs/SearchQuery",+ "description": "The search query",+ },+ "limit": {+ "type": "integer",+ "exclusiveMinimum": 0,+ "description": "Maximum results",+ "default": 5,+ },+ },+ "required": ["query"],+ },+ )++ def test_partial_uses_underlying_function_name(self) -> None:+ """A partial inherits its default tool name."""+ tool = FunctionTool(+ partial(documented_search, "catalog-a"),+ )++ self.assertEqual(tool.name, "documented_search")++ def test_partial_uses_underlying_function_docstring(self) -> None:+ """A partial inherits tool and parameter documentation."""+ tool = FunctionTool(+ partial(documented_search, "catalog-a"),+ name="documented_search",+ )++ self.assertEqual(+ tool.description,+ "Search the selected catalog.",+ )+ self.assertDictEqual(+ tool.input_schema,+ {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": "The query to run.",+ },+ },+ "required": ["query"],+ },+ )++ def test_partial_prefers_its_explicit_docstring(self) -> None:+ """An explicitly assigned partial docstring takes precedence."""+ tool_func = partial(documented_search, "catalog-a")+ tool_func.__doc__ = """Search a custom catalog.++ Args:+ query: The custom query to run.+ """+ tool = FunctionTool(+ tool_func,+ name="documented_search",+ )++ self.assertEqual(+ tool.description,+ "Search a custom catalog.",+ )+ self.assertDictEqual(+ tool.input_schema,+ {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": "The custom query to run.",+ },+ },+ "required": ["query"],+ },+ )++ def test_partial_falls_back_to_usable_raw_parameter_annotation(+ self,+ ) -> None:+ """An unresolvable return hint does not discard a usable parameter."""+ schema = _extract_input_schema(+ partial(primitive_parameter_with_unresolvable_return),+ )++ self.assertDictEqual(+ schema,+ {+ "type": "object",+ "properties": {"value": {"type": "integer"}},+ "required": ["value"],+ },+ )