Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

core: improved method tools #28695

Closed
wants to merge 9 commits into from
1 change: 1 addition & 0 deletions libs/core/langchain_core/tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
from langchain_core.tools.convert import (
convert_runnable_to_tool as convert_runnable_to_tool,
)
from langchain_core.tools.convert import methodtool as methodtool
from langchain_core.tools.convert import tool as tool
from langchain_core.tools.render import ToolsRenderer as ToolsRenderer
from langchain_core.tools.render import (
Expand Down
57 changes: 55 additions & 2 deletions libs/core/langchain_core/tools/convert.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
import functools
import inspect
from typing import Any, Callable, Literal, Optional, Union, get_type_hints, overload
from typing import (
Any,
Callable,
Literal,
Optional,
Union,
cast,
get_type_hints,
overload,
)

from pydantic import BaseModel, Field, create_model

from langchain_core.callbacks import Callbacks
from langchain_core.runnables import Runnable
from langchain_core.tools.base import BaseTool
from langchain_core.tools.base import BaseTool, create_schema_from_function
from langchain_core.tools.simple import Tool
from langchain_core.tools.structured import StructuredTool

Expand Down Expand Up @@ -421,3 +431,46 @@ def invoke_wrapper(callbacks: Optional[Callbacks] = None, **kwargs: Any) -> Any:
description=description,
args_schema=args_schema,
)


class MethodTool:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we make this a function instead of a class?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see - this maybe solves the issue of typing. going to suggest some ideas - not sure if they work

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The class is needed for classmethod support. I have created a wrapper function methodtool that simply returns MethodTool(func). How's that?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why is it needed for classmethod support?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I mentioned in another reply:

With the way the __get__ descriptor works owner is for the class itself and instance is for the instance of the class.

Keep in mind that in your other solution (a function that returns a property), you are still returning a descriptor class. That class, property. works for our regular method tool case, but it will not work for class methods. Notice in the MethodTool class that it will pass in owner (class itself) for outer_instance with classmethods, and instance (class instance) for regular methods. Since the property class is not enough for our use, I had to create a custom descriptor that did exactly what we wanted it to.

"Why could we not do classmethod(property(func)) for classmethods?" you may ask. That is because classmethod no longer wraps descriptors as of Python 3.13.

If, for syntax reasons, you would like the decorator to be a function that is something that I have added to the code. The function is simply a wrapper for the MethodTool class since that overloaded __get__ method is needed, but the MethodTool class never needs to be exposed to client code.

"""A descriptor that converts a method into a tool."""

def __init__(self, func: Union[Callable, classmethod]) -> None:
self.func = func

def __get__(self, instance: Any, owner: Any) -> BaseTool:
# casting to Callable to avoid mypy error
tool_func: Callable = cast(
Callable,
self.func.__func__ if isinstance(self.func, classmethod) else self.func,
)
outer_instance = owner if isinstance(self.func, classmethod) else instance

new_func = functools.partial(tool_func, outer_instance)
new_func.__doc__ = tool_func.__doc__

# remove the first argument (typically 'self' or 'cls') from the schema
args_schema = create_schema_from_function(
tool_func.__name__,
tool_func,
filter_args=[
list(inspect.signature(tool_func).parameters.values())[0].name
],
)

return tool(tool_func.__name__, args_schema=args_schema, infer_schema=False)(
new_func
)


def methodtool(func: Union[Callable, classmethod]) -> MethodTool:
"""Convert a method into a tool.

Args:
func: The method to convert.

Returns:
The method tool.
"""
return MethodTool(func)
161 changes: 161 additions & 0 deletions libs/core/tests/unit_tests/test_tools.py
ethanglide marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
StructuredTool,
Tool,
ToolException,
methodtool,
tool,
)
from langchain_core.tools.base import (
Expand Down Expand Up @@ -2174,3 +2175,163 @@ def foo(x: int) -> Bar:
assert foo.invoke(
{"type": "tool_call", "args": {"x": 0}, "name": "foo", "id": "bar"}
) == Bar(x=0)


def test_method_tool_self_ref() -> None:
"""Test that a method tool can reference self."""

class A:
def __init__(self, c: int):
self.c = c

@methodtool
def foo(self, a: int, b: int) -> int:
"""Add two numbers to c."""
return a + b + self.c

a = A(10)
assert a.foo.invoke({"a": 1, "b": 2}) == 13
ethanglide marked this conversation as resolved.
Show resolved Hide resolved
ethanglide marked this conversation as resolved.
Show resolved Hide resolved
assert a.foo.args == {
"a": {"title": "A", "type": "integer"},
"b": {"title": "B", "type": "integer"},
}
assert a.foo.name == "foo"
assert a.foo.description == "Add two numbers to c."


async def test_method_tool_async() -> None:
"""Test that a method tool can be async."""

class A:
def __init__(self, c: int):
self.c = c

@methodtool
async def foo(self, a: int, b: int) -> int:
"""Add two numbers to c."""
return a + b + self.c

a = A(10)
async_response = await a.foo.ainvoke({"a": 1, "b": 2})
assert async_response == 13
assert a.foo.args == {
"a": {"title": "A", "type": "integer"},
"b": {"title": "B", "type": "integer"},
}
assert a.foo.name == "foo"
assert a.foo.description == "Add two numbers to c."


def test_method_tool_string_invoke() -> None:
"""Test that a method tool can be invoked with a string."""

class A:
def __init__(self, a: str):
self.a = a

@methodtool
def foo(self, b: str) -> str:
"""Concatenate a and b."""
return self.a + b

a = A("a")
assert a.foo.invoke("b") == "ab"
assert a.foo.args == {"b": {"title": "B", "type": "string"}}
assert a.foo.name == "foo"
assert a.foo.description == "Concatenate a and b."


def test_method_tool_toolcall_invoke() -> None:
"""Test that a method tool can be invoked with a ToolCall."""

class A:
def __init__(self, c: int):
self.c = c

@methodtool
def foo(self, a: int, b: int) -> int:
"""Add two numbers to c."""
return a + b + self.c

a = A(10)

tool_call = {
"name": a.foo.name,
"args": {"a": 1, "b": 2},
"id": "123",
"type": "tool_call",
}

tool_message = a.foo.invoke(tool_call)

assert int(tool_message.content) == 13
assert a.foo.args == {
"a": {"title": "A", "type": "integer"},
"b": {"title": "B", "type": "integer"},
}
assert a.foo.name == "foo"
assert a.foo.description == "Add two numbers to c."


def test_method_tool_classmethod() -> None:
"""Test that a method tool can be a classmethod."""

class A:
c = 10

@methodtool
@classmethod
def foo(cls, a: int, b: int) -> int:
"""Add two numbers to c."""
return a + b + cls.c

assert A.foo.invoke({"a": 1, "b": 2}) == 13
assert A.foo.args == {
"a": {"title": "A", "type": "integer"},
"b": {"title": "B", "type": "integer"},
}
assert A.foo.name == "foo"
assert A.foo.description == "Add two numbers to c."


def test_method_tool_nonstandard_self() -> None:
"""Test that a method tool can use a non-standard self name."""

class A:
def __init__(self, c: int):
self.c = c

@methodtool
def foo(s, a: int, b: int) -> int: # noqa: N805
"""Add two numbers to c."""
return a + b + s.c

a = A(10)
assert a.foo.invoke({"a": 1, "b": 2}) == 13
assert a.foo.args == {
"a": {"title": "A", "type": "integer"},
"b": {"title": "B", "type": "integer"},
}
assert a.foo.name == "foo"
assert a.foo.description == "Add two numbers to c."


def test_method_tool_nonstandard_cls() -> None:
"""Test that a classmethod tool can use a non-standard cls name."""

class A:
c = 10

@methodtool
@classmethod
def foo(c, a: int, b: int) -> int: # noqa: N804
"""Add two numbers to c."""
return a + b + c.c

assert A.foo.invoke({"a": 1, "b": 2}) == 13
assert A.foo.args == {
"a": {"title": "A", "type": "integer"},
"b": {"title": "B", "type": "integer"},
}
assert A.foo.name == "foo"
assert A.foo.description == "Add two numbers to c."
Loading