Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(tool): resolve PEP 563 lazy annotations when extracting tool schemas (#2371)
DavdGaoed6ba75e39d3
diff --git a/src/agentscope/tool/_utils.py b/src/agentscope/tool/_utils.pyindex 20c6ad001..bb364c031 100644--- a/src/agentscope/tool/_utils.py+++ b/src/agentscope/tool/_utils.py@@ -1,6 +1,7 @@# -*- coding: utf-8 -*-"""The tool module utils."""import inspect+import typingfrom typing import Any, Dict, Callablefrom docstring_parser import parse@@ -65,6 +66,15 @@ def _extract_func_description(docstring: str) -> str:return "\n".join(descriptions)+def _build_param_field(description: str | None, default: Any) -> Any:+ """Build the pydantic ``Field`` for a parameter, omitting an absent+ description so it doesn't override metadata carried by+ ``Annotated[..., Field(...)]`` annotations."""+ if description is None:+ return Field(default=default)+ return Field(description=description, default=default)++def _extract_input_schema(tool_func: Callable,include_var_positional: bool = False,@@ -88,6 +98,16 @@ def _extract_input_schema(docstring = parse(tool_func.__doc__ or "")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 = {}+# Create a dynamic model with the function signaturefields = {}for name, param in inspect.signature(tool_func).parameters.items():@@ -95,6 +115,8 @@ def _extract_input_schema(if name in ["self", "cls"]:continue+ annotation = type_hints.get(name, param.annotation)+# Handle `**kwargs`if param.kind == inspect.Parameter.VAR_KEYWORD:if not include_var_keyword:@@ -102,9 +124,9 @@ def _extract_input_schema(fields[name] = (Dict[str, Any]- if param.annotation == inspect.Parameter.empty- else Dict[str, param.annotation], # type: ignore- Field(+ if annotation == inspect.Parameter.empty+ else Dict[str, annotation], # type: ignore+ _build_param_field(description=params_docstring.get(f"**{name}",params_docstring.get(name, None),@@ -121,9 +143,9 @@ def _extract_input_schema(fields[name] = (list[Any]- if param.annotation == inspect.Parameter.empty- else list[param.annotation], # type: ignore- Field(+ if annotation == inspect.Parameter.empty+ else list[annotation], # type: ignore+ _build_param_field(description=params_docstring.get(f"*{name}",params_docstring.get(name, None),@@ -136,10 +158,8 @@ def _extract_input_schema(else:fields[name] = (- Any- if param.annotation == inspect.Parameter.empty- else param.annotation,- Field(+ Any if annotation == inspect.Parameter.empty else annotation,+ _build_param_field(description=params_docstring.get(name, None),default=...if param.default is param.emptydiff --git a/tests/tool_lazy_annotations_test.py b/tests/tool_lazy_annotations_test.pynew file mode 100644index 000000000..6f4f50334--- /dev/null+++ b/tests/tool_lazy_annotations_test.py@@ -0,0 +1,145 @@+# -*- coding: utf-8 -*-+# pylint: disable=unused-argument+"""Test schema extraction under PEP 563 lazy annotations.++The ``from __future__ import annotations`` import below is the point of+this test module: it turns all annotations into strings, which must be+resolved back to real types before being handed to pydantic.+"""+from __future__ import annotations++from typing import Annotated+from unittest import TestCase++from pydantic import BaseModel, Field++from agentscope.tool import FunctionTool+from agentscope.tool._utils import _extract_input_schema+++class Location(BaseModel):+ """A location model used as a parameter type."""++ city: str = Field(description="The city name")+++def annotated_tool(+ query: Annotated[str, Field(description="The search query")],+ limit: int = 5,+) -> str:+ """Search for something."""+ return query+++def kwargs_tool(**kwargs: Annotated[str, Field(description="Extras")]) -> None:+ """A tool receiving keyword arguments only."""+++def model_tool(location: Location) -> str:+ """Report the weather.++ Args:+ location: Where to report the weather for.+ """+ return location.city+++class LazyAnnotationsTest(TestCase):+ """Schema extraction must work with stringized annotations."""++ def test_annotated_field_parameter(self) -> None:+ """`Annotated[str, Field(...)]` params must be resolved."""+ schema = _extract_input_schema(annotated_tool)+ self.assertDictEqual(+ schema,+ {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": "The search query",+ },+ "limit": {+ "type": "integer",+ "default": 5,+ },+ },+ "required": ["query"],+ },+ )++ def test_annotated_var_keyword(self) -> None:+ """`**kwargs` annotations must be resolved as well."""+ schema = _extract_input_schema(+ kwargs_tool,+ include_var_keyword=True,+ )+ self.assertDictEqual(+ schema,+ {+ "type": "object",+ "properties": {+ "kwargs": {+ "type": "object",+ "additionalProperties": {+ "type": "string",+ "description": "Extras",+ },+ "default": {},+ },+ },+ },+ )++ def test_pydantic_model_parameter(self) -> None:+ """Custom model types must be resolved from the defining module."""+ schema = _extract_input_schema(model_tool)+ self.assertDictEqual(+ schema,+ {+ "type": "object",+ "$defs": {+ "Location": {+ "type": "object",+ "description": (+ "A location model used as a parameter type."+ ),+ "properties": {+ "city": {+ "type": "string",+ "description": "The city name",+ },+ },+ "required": ["city"],+ },+ },+ "properties": {+ "location": {+ "$ref": "#/$defs/Location",+ "description": "Where to report the weather for.",+ },+ },+ "required": ["location"],+ },+ )++ def test_function_tool_registration(self) -> None:+ """FunctionTool must expose the resolved schema end to end."""+ tool = FunctionTool(annotated_tool)+ self.assertDictEqual(+ tool.input_schema,+ {+ "type": "object",+ "properties": {+ "query": {+ "type": "string",+ "description": "The search query",+ },+ "limit": {+ "type": "integer",+ "default": 5,+ },+ },+ "required": ["query"],+ },+ )