Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions python/packages/core/agent_framework/_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1743,6 +1743,26 @@ def _validate_arguments_against_schema(
return parsed_arguments


def _get_callable_name(func: Callable[..., Any]) -> str:
"""Return the name of a callable, looking through ``functools.partial`` objects without their own name."""
while not hasattr(func, "__name__") and isinstance(func, partial):
func = func.func
return getattr(func, "__name__", type(func).__name__)


def _get_callable_description(func: Callable[..., Any]) -> str:
"""Return the docstring of a callable, looking through ``functools.partial`` objects without their own docstring."""
while isinstance(func, partial) and func.__doc__ == partial.__doc__:
func = func.func
doc = func.__doc__
# A class's __call__ belongs to its metaclass, and built-in __call__ slots share a generic docstring.
if not doc and not isinstance(func, (partial, type)):
call = type(func).__call__
if inspect.isfunction(call):
doc = call.__doc__
return doc or ""


@overload
def tool(
func: Callable[..., Any],
Expand Down Expand Up @@ -1810,9 +1830,13 @@ def tool(

Keyword Args:
name: The name of the function. If not provided, the function's ``__name__``
attribute will be used.
attribute will be used. A ``functools.partial`` without its own ``__name__``
uses the name of the callable it wraps, and a callable instance uses its class
name.
description: A description of the function. If not provided, the function's
docstring will be used.
docstring will be used. A ``functools.partial`` without its own docstring uses
the docstring of the callable it wraps, and a callable instance without a class
docstring uses the docstring of its ``__call__`` method.
schema: An explicit input schema for the function. This can be a Pydantic
``BaseModel`` subclass or a JSON schema dictionary (``Mapping[str, Any]``).
Dictionary schemas are passed through to providers and receive only
Expand Down Expand Up @@ -1924,8 +1948,8 @@ def get_weather(location: str, unit: str = "celsius") -> str:
def decorator(func: Callable[..., Any]) -> FunctionTool:
@wraps(func)
def wrapper(f: Callable[..., Any]) -> FunctionTool:
tool_name: str = name or getattr(f, "__name__", "unknown_function")
tool_desc: str = description or (f.__doc__ or "")
tool_name: str = name or _get_callable_name(f)
tool_desc: str = description or _get_callable_description(f)
return FunctionTool(
name=tool_name,
description=tool_desc,
Expand Down
71 changes: 71 additions & 0 deletions python/packages/core/tests/core/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
import threading
from contextvars import ContextVar
from datetime import date, datetime
from enum import Enum
from functools import partial
from typing import Annotated, Any, Literal, get_args, get_origin
from unittest.mock import Mock

Expand Down Expand Up @@ -764,6 +766,75 @@ def test_tool() -> int:
assert test_tool() == 3


def search_index(query: str, index: str) -> str:
"""Search an index."""
return f"{index}: {query}"


def undocumented(value: int) -> int:
return value


class Lookup:
def __call__(self, key: str) -> str:
"""Look up a key."""
return key


class DocumentedLookup:
"""Look up a documented key."""

def __call__(self, key: str) -> str:
"""Look up a key."""
return key


class Color(Enum):
RED = "red"


named_search = partial(search_index, index="docs")
named_search.__name__ = "search_docs" # type: ignore[attr-defined] # ty: ignore[unresolved-attribute]
documented_search = partial(search_index, index="docs")
documented_search.__doc__ = "Search the docs index." # type: ignore[assignment]


@pytest.mark.parametrize(
("func", "expected_name", "expected_description"),
[
(partial(search_index, index="docs"), "search_index", "Search an index."),
(Lookup(), "Lookup", "Look up a key."),
(DocumentedLookup(), "DocumentedLookup", "Look up a documented key."),
(named_search, "search_docs", "Search an index."),
(documented_search, "search_index", "Search the docs index."),
(partial(named_search), "search_docs", "Search an index."),
(partial(documented_search), "search_index", "Search the docs index."),
(partial(Lookup()), "Lookup", "Look up a key."),
(Color, "Color", ""),
(undocumented, "undocumented", ""),
],
ids=[
"partial",
"call_docstring",
"class_docstring",
"partial_own_name",
"partial_own_docstring",
"nested_partial_own_name",
"nested_partial_own_docstring",
"partial_instance",
"class_object",
"no_docstring",
],
)
def test_tool_default_name_and_description(func: Any, expected_name: str, expected_description: str) -> None:
"""Test the default name and description of partials, callable instances, and classes."""
func_tool = tool(func)

assert func_tool.name == expected_name
assert func_tool.description == expected_description
assert func_tool.func is func


async def test_tool_decorator_with_async():
"""Test the tool decorator with an async function."""

Expand Down
Loading