跳到内容

dspy.Tool

dspy.Tool(func: Callable, name: Optional[str] = None, desc: Optional[str] = None, args: Optional[dict[str, Any]] = None, arg_types: Optional[dict[str, Any]] = None, arg_desc: Optional[dict[str, str]] = None)

Tool 类。

此类用于简化在 LLM 中进行工具调用(函数调用)的工具创建。目前仅支持函数。

初始化 Tool 类。

用户可以选择指定 namedescargsarg_types,或者让 dspy.Tool 从函数中自动推断值。对于用户指定的值,将不会对其执行自动推断。

参数

名称 类型 描述 默认值
func Callable

工具包装的实际函数。

必需
name 可选[字符串]

工具的名称。默认为 None。

None
desc 可选[字符串]

工具的描述。默认为 None。

None
args 可选[字典[字符串, 任意类型]]

工具的参数及其模式,表示为一个字典,从参数名称到参数的 JSON 模式。默认为 None。

None
arg_types 可选[字典[字符串, 任意类型]]

工具的参数类型,表示为一个字典,从参数名称到参数的类型。默认为 None。

None
arg_desc 可选[字典[字符串, 字符串]]

每个参数的描述,表示为一个字典,从参数名称到描述字符串。默认为 None。

None

Example

def foo(x: int, y: str = "hello"):
    return str(x) + y

tool = Tool(foo)
print(tool.args)
# Expected output: {'x': {'type': 'integer'}, 'y': {'type': 'string', 'default': 'hello'}}
源代码位于 dspy/primitives/tool.py
def __init__(
    self,
    func: Callable,
    name: Optional[str] = None,
    desc: Optional[str] = None,
    args: Optional[dict[str, Any]] = None,
    arg_types: Optional[dict[str, Any]] = None,
    arg_desc: Optional[dict[str, str]] = None,
):
    """Initialize the Tool class.

    Users can choose to specify the `name`, `desc`, `args`, and `arg_types`, or let the `dspy.Tool`
    automatically infer the values from the function. For values that are specified by the user, automatic inference
    will not be performed on them.

    Args:
        func (Callable): The actual function that is being wrapped by the tool.
        name (Optional[str], optional): The name of the tool. Defaults to None.
        desc (Optional[str], optional): The description of the tool. Defaults to None.
        args (Optional[dict[str, Any]], optional): The args and their schema of the tool, represented as a
            dictionary from arg name to arg's json schema. Defaults to None.
        arg_types (Optional[dict[str, Any]], optional): The argument types of the tool, represented as a dictionary
            from arg name to the type of the argument. Defaults to None.
        arg_desc (Optional[dict[str, str]], optional): Descriptions for each arg, represented as a
            dictionary from arg name to description string. Defaults to None.

    Example:

    ```python
    def foo(x: int, y: str = "hello"):
        return str(x) + y

    tool = Tool(foo)
    print(tool.args)
    # Expected output: {'x': {'type': 'integer'}, 'y': {'type': 'string', 'default': 'hello'}}
    ```
    """
    self.func = func
    self.name = name
    self.desc = desc
    self.args = args
    self.arg_types = arg_types
    self.arg_desc = arg_desc
    self.has_kwargs = False

    self._parse_function(func, arg_desc)

函数

__call__(**kwargs)

源代码位于 dspy/primitives/tool.py
@with_callbacks
def __call__(self, **kwargs):
    parsed_kwargs = self._validate_and_parse_args(**kwargs)
    result = self.func(**parsed_kwargs)
    if asyncio.iscoroutine(result):
        raise ValueError("You are calling `__call__` on an async tool, please use `acall` instead.")
    return result

acall(**kwargs) async

源代码位于 dspy/primitives/tool.py
@with_callbacks
async def acall(self, **kwargs):
    parsed_kwargs = self._validate_and_parse_args(**kwargs)
    result = self.func(**parsed_kwargs)
    if asyncio.iscoroutine(result):
        return await result
    else:
        # We should allow calling a sync tool in the async path.
        return result

from_mcp_tool(session: mcp.client.session.ClientSession, tool: mcp.types.Tool) -> Tool classmethod

从 MCP 工具和 ClientSession 构建 DSPy 工具。

参数

名称 类型 描述 默认值
session ClientSession

要使用的 MCP 会话。

必需
tool 工具

要转换的 MCP 工具。

必需

返回值

类型 描述
工具

一个 Tool 对象。

源代码位于 dspy/primitives/tool.py
@classmethod
def from_mcp_tool(cls, session: "mcp.client.session.ClientSession", tool: "mcp.types.Tool") -> "Tool":
    """
    Build a DSPy tool from an MCP tool and a ClientSession.

    Args:
        session: The MCP session to use.
        tool: The MCP tool to convert.

    Returns:
        A Tool object.
    """
    from dspy.utils.mcp import convert_mcp_tool

    return convert_mcp_tool(session, tool)