Skip to content

Commit 6a60d6a

Browse files
Om-singhaIcopybara-github
authored andcommitted
fix: stop partial tools colliding and send the __call__ docstring
Merge #7191 Fixes #7190 PiperOrigin-RevId: 996678271
1 parent 865a6d6 commit 6a60d6a

5 files changed

Lines changed: 160 additions & 14 deletions

File tree

‎src/google/adk/tools/_function_tool_declarations.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050

5151
from ..events.event import Event
5252
from ..events.request_input import RequestInput
53+
from ..utils._callable_utils import get_callable_doc
5354
from ..utils.variant_utils import get_google_llm_variant
5455
from ..utils.variant_utils import GoogleLLMVariant
5556

@@ -331,6 +332,8 @@ def get_callable_name(func: Callable[..., Any]) -> str:
331332
"""Returns the name a callable is advertised and registered under.
332333
333334
Callable objects carry no `__name__`, so they fall back to their class name.
335+
A functools.partial without a `__name__` of its own takes the name of the
336+
callable it wraps, so two partials of different functions do not collide.
334337
This is the single source of truth for both the declaration sent to the model
335338
and the key the tool is registered under: if the two disagree, the model is
336339
told about a tool it cannot invoke.
@@ -341,6 +344,8 @@ def get_callable_name(func: Callable[..., Any]) -> str:
341344
Returns:
342345
The name to use for the callable.
343346
"""
347+
if isinstance(func, functools.partial) and not hasattr(func, '__name__'):
348+
return get_callable_name(func.func)
344349
return getattr(func, '__name__', None) or func.__class__.__name__
345350

346351

@@ -486,15 +491,15 @@ def _build_response_json_schema(
486491
logging.debug(
487492
'Failed to build schema with config, retrying without config for'
488493
' %s: %s',
489-
func.__name__,
494+
get_callable_name(func),
490495
e,
491496
)
492497
adapter = pydantic.TypeAdapter(return_annotation)
493498
return adapter.json_schema()
494499
except Exception:
495500
logging.warning(
496501
'Failed to build response JSON schema for %s',
497-
func.__name__,
502+
get_callable_name(func),
498503
exc_info=True,
499504
)
500505
# Fall back to untyped response
@@ -556,7 +561,7 @@ def build_function_declaration_with_json_schema(
556561
)
557562

558563
# Handle Callable functions
559-
description = inspect.cleandoc(func.__doc__) if func.__doc__ else None
564+
description = get_callable_doc(func) or None
560565
func_name = get_callable_name(func)
561566
declaration = types.FunctionDeclaration(
562567
name=func_name,

‎src/google/adk/utils/_callable_utils.py‎

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@
3333
logger = logging.getLogger("google_adk." + __name__)
3434

3535
_DEFAULT_CALL_DOC = inspect.getdoc(type.__call__)
36+
_DEFAULT_PARTIAL_DOC = inspect.getdoc(functools.partial)
3637

3738
_METHOD_WRAPPER_TYPES = (
3839
type((1).__add__),
@@ -109,6 +110,31 @@ def get_type_hints_cached(func: Callable[..., Any]) -> dict[str, Any]:
109110
return hints
110111

111112

113+
def get_callable_doc(func: Callable[..., Any]) -> str:
114+
"""Returns the cleaned docstring of a callable, or "" if it has none.
115+
116+
A functools.partial without a docstring of its own resolves to the wrapped
117+
callable's docstring, and a callable object without one falls back to its
118+
`__call__` docstring. CallableSpec uses this for FunctionTool's description,
119+
and `build_function_declaration_with_json_schema` uses it for the
120+
declaration sent to the model. That covers only the JSON schema path: with
121+
JSON_SCHEMA_FOR_FUNC_DECL off, `from_function_with_options` still reads
122+
`func.__doc__` directly, so the two can differ there.
123+
"""
124+
doc = inspect.getdoc(func) or ""
125+
if isinstance(func, functools.partial) and doc == _DEFAULT_PARTIAL_DOC:
126+
return get_callable_doc(func.func)
127+
if not doc and not _is_routine(func) and not isinstance(func, type):
128+
call_method = getattr(func, "__call__", None)
129+
if call_method is not None:
130+
call_doc = inspect.getdoc(call_method) or ""
131+
if call_doc and call_doc != _DEFAULT_CALL_DOC:
132+
doc = call_doc
133+
if doc == _DEFAULT_CALL_DOC:
134+
doc = ""
135+
return doc
136+
137+
112138
class CallableSpec:
113139
"""Unified specification and introspection for a callable.
114140
@@ -131,18 +157,8 @@ def __init__(self, func: Callable[..., Any] | None) -> None:
131157
self.func = func
132158
self.unwrapped_func = unwrap_callable(func) if func is not None else None
133159

134-
# Docstring resolution (prioritize direct func.__doc__, then func.__call__.__doc__)
135160
if func is not None:
136-
doc = inspect.getdoc(func) or ""
137-
if not doc and not _is_routine(func) and not isinstance(func, type):
138-
call_method = getattr(func, "__call__", None)
139-
if call_method is not None:
140-
call_doc = inspect.getdoc(call_method) or ""
141-
if call_doc and call_doc != _DEFAULT_CALL_DOC:
142-
doc = call_doc
143-
if doc == _DEFAULT_CALL_DOC:
144-
doc = ""
145-
self.doc = doc
161+
self.doc = get_callable_doc(func)
146162

147163
# Context parameter detection
148164
self.context_param_name = context_utils.find_context_parameter(func)

‎tests/unittests/tools/test_function_tool.py‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
# limitations under the License.
1414

1515
from enum import Enum
16+
import functools
1617
import inspect
1718
from typing import Any
1819
from typing import Optional
@@ -24,6 +25,7 @@
2425
from google.adk.agents.invocation_context import InvocationContext
2526
from google.adk.features import FeatureName
2627
from google.adk.features._feature_registry import temporary_feature_override
28+
from google.adk.models.llm_request import LlmRequest
2729
from google.adk.sessions.session import Session
2830
from google.adk.tools.function_tool import _build_declaration_cached
2931
from google.adk.tools.function_tool import FunctionTool
@@ -167,6 +169,56 @@ async def test_run_async_with_tool_context_async_callable():
167169
assert tool.description == "Async call doc"
168170

169171

172+
def test_callable_declaration_uses_call_docstring():
173+
"""The declaration carries the same __call__ docstring as tool.description."""
174+
tool = FunctionTool(AsyncCallableWith1ArgAndToolContext())
175+
176+
llm_request = LlmRequest()
177+
llm_request.append_tools([tool])
178+
179+
declaration = llm_request.config.tools[0].function_declarations[0]
180+
assert declaration.description == "Async call doc"
181+
182+
183+
def test_partial_tools_do_not_shadow_each_other():
184+
"""Partials of different functions keep their own names and docstrings."""
185+
186+
def get_weather(api_key: str, city: str) -> str:
187+
"""Returns the current weather for a city."""
188+
return city
189+
190+
def get_forecast(api_key: str, city: str, days: int = 3) -> str:
191+
"""Returns a forecast for a city."""
192+
return city
193+
194+
llm_request = LlmRequest()
195+
llm_request.append_tools([
196+
FunctionTool(functools.partial(get_weather, "key")),
197+
FunctionTool(functools.partial(get_forecast, "key")),
198+
])
199+
200+
declarations = llm_request.config.tools[0].function_declarations
201+
assert [d.name for d in declarations] == ["get_weather", "get_forecast"]
202+
assert [d.description for d in declarations] == [
203+
"Returns the current weather for a city.",
204+
"Returns a forecast for a city.",
205+
]
206+
assert list(llm_request.tools_dict) == ["get_weather", "get_forecast"]
207+
208+
with temporary_feature_override(FeatureName.JSON_SCHEMA_FOR_FUNC_DECL, False):
209+
legacy_request = LlmRequest()
210+
legacy_request.append_tools([
211+
FunctionTool(functools.partial(get_weather, "key")),
212+
FunctionTool(functools.partial(get_forecast, "key")),
213+
])
214+
legacy_declarations = legacy_request.config.tools[0].function_declarations
215+
assert [d.name for d in legacy_declarations] == [
216+
"get_weather",
217+
"get_forecast",
218+
]
219+
assert list(legacy_request.tools_dict) == ["get_weather", "get_forecast"]
220+
221+
170222
@pytest.mark.asyncio
171223
async def test_run_async_without_tool_context_async_func():
172224
"""Test that run_async calls the function without tool_context when tool_context is not in signature (async function)."""

‎tests/unittests/tools/test_function_tool_declarations.py‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from collections.abc import Sequence
2424
import dataclasses
2525
from enum import Enum
26+
import functools
2627
import os
2728
from typing import Annotated
2829
from typing import Any
@@ -1220,6 +1221,38 @@ def undocumented(x: int) -> int:
12201221
},
12211222
)
12221223

1224+
def test_callable_object_docstring_on_call(self):
1225+
"""Test callable object documented only on __call__."""
1226+
1227+
class OrderLookup:
1228+
1229+
def __call__(self, order_id: str) -> str:
1230+
"""Looks up an order by its id."""
1231+
return order_id
1232+
1233+
decl = build_function_declaration_with_json_schema(OrderLookup())
1234+
1235+
self.assertEqual(decl.name, "OrderLookup")
1236+
self.assertEqual(decl.description, "Looks up an order by its id.")
1237+
1238+
def test_partial_uses_wrapped_name_and_docstring(self):
1239+
"""Test functools.partial is declared as the function it wraps."""
1240+
1241+
def get_weather(api_key: str, city: str) -> Address:
1242+
"""Returns the current weather for a city."""
1243+
return Address(street=api_key, city=city, zip_code="12345")
1244+
1245+
decl = build_function_declaration_with_json_schema(
1246+
functools.partial(get_weather, "key")
1247+
)
1248+
1249+
self.assertEqual(decl.name, "get_weather")
1250+
self.assertEqual(
1251+
decl.description, "Returns the current weather for a city."
1252+
)
1253+
self.assertEqual(list(decl.parameters_json_schema["properties"]), ["city"])
1254+
self.assertEqual(decl.response_json_schema["title"], "Address")
1255+
12231256

12241257
class TestComplexFunction(parameterized.TestCase):
12251258
"""Test the complex function from the user's prototype."""

‎tests/unittests/utils/test_callable_utils.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,46 @@ def __call__(self, x: int) -> int:
175175
assert CallableSpec(UndocCallable()).doc == ""
176176

177177

178+
def _wrapped_with_doc(a: int, b: int) -> int:
179+
"""Wrapped function docstring."""
180+
return a + b
181+
182+
183+
class _DocCallable:
184+
185+
def __call__(self, a: int, b: int) -> int:
186+
"""Call method docstring."""
187+
return a + b
188+
189+
190+
_documented_partial = functools.partial(_wrapped_with_doc, 1)
191+
_documented_partial.__doc__ = "Partial docstring."
192+
193+
194+
@pytest.mark.parametrize(
195+
("partial_fn", "expected_doc"),
196+
[
197+
(
198+
functools.partial(_wrapped_with_doc, 1),
199+
"Wrapped function docstring.",
200+
),
201+
(
202+
functools.partial(_DocCallable(), 1),
203+
"Call method docstring.",
204+
),
205+
(
206+
_documented_partial,
207+
"Partial docstring.",
208+
),
209+
],
210+
)
211+
def test_callable_spec_partial_doc(
212+
partial_fn: functools.partial[int], expected_doc: str
213+
) -> None:
214+
"""A partial resolves doc from the callable it wraps unless it has its own."""
215+
assert CallableSpec(partial_fn).doc == expected_doc
216+
217+
178218
def test_callable_spec_raises_on_unintrospectable_callable():
179219
"""CallableSpec raises ValueError when signature of unintrospectable callable is accessed."""
180220
spec = CallableSpec(dir)

0 commit comments

Comments
 (0)