跳转至

Tools

MCPToolApprovalFunction module-attribute

MCPToolApprovalFunction = Callable[[MCPToolApprovalRequest], MaybeAwaitable[MCPToolApprovalFunctionResult]]

用于批准或拒绝工具调用的函数。

LocalShellExecutor module-attribute

LocalShellExecutor = Callable[[LocalShellCommandRequest], MaybeAwaitable[str]]

用于在 shell 上执行命令的函数。

Tool module-attribute

可在 agent 中使用的工具。

FunctionToolResult dataclass

Source code in agents/tool.py
@dataclass
class FunctionToolResult:
    tool: FunctionTool
    """被运行的工具。"""

    output: Any
    """工具的输出结果。"""

    run_item: RunItem
    """工具调用产生的运行项。"""

tool instance-attribute

被运行的工具。

output instance-attribute

output: Any

工具的输出结果。

run_item instance-attribute

run_item: RunItem

工具调用产生的运行项。

FunctionTool dataclass

包装函数的工具。在大多数情况下,你应该使用 function_tool 辅助函数来创建 FunctionTool, 因为它们可以让你轻松地包装一个 Python 函数。

Source code in agents/tool.py
@dataclass
class FunctionTool:
    """包装函数的工具。在大多数情况下,你应该使用 `function_tool` 辅助函数来创建 FunctionTool,
    因为它们可以让你轻松地包装一个 Python 函数。
    """

    name: str
    """工具的名称,会展示给 LLM。通常为函数名。"""

    description: str
    """工具的描述,会展示给 LLM。"""

    params_json_schema: dict[str, Any]
    """工具参数的 JSON schema。"""

    on_invoke_tool: Callable[[RunContextWrapper[Any], str], Awaitable[Any]]
    """用于根据给定上下文和参数调用工具的函数。传递的参数为:
    1. 工具运行上下文。
    2. 来自 LLM 的参数,作为 JSON 字符串。

    你必须返回工具输出的字符串表示,或者可以调用 `str()` 的对象。
    如果发生错误,你可以抛出异常(这会导致运行失败),或者返回字符串错误信息(会反馈给 LLM)。
    """

    strict_json_schema: bool = True
    """JSON schema 是否为严格模式。我们**强烈**建议设置为 True,
    因为这会提高正确 JSON 输入的概率。"""

name instance-attribute

name: str

工具的名称,会展示给 LLM。通常为函数名。

description instance-attribute

description: str

工具的描述,会展示给 LLM。

params_json_schema instance-attribute

params_json_schema: dict[str, Any]

工具参数的 JSON schema。

on_invoke_tool instance-attribute

on_invoke_tool: Callable[[RunContextWrapper[Any], str], Awaitable[Any]]

用于根据给定上下文和参数调用工具的函数。传递的参数为: 1. 工具运行上下文。 2. 来自 LLM 的参数,作为 JSON 字符串。

你必须返回工具输出的字符串表示,或者可以调用 str() 的对象。 如果发生错误,你可以抛出异常(这会导致运行失败),或者返回字符串错误信息(会反馈给 LLM)。

strict_json_schema class-attribute instance-attribute

strict_json_schema: bool = True

JSON schema 是否为严格模式。我们强烈建议设置为 True, 因为这会提高正确 JSON 输入的概率。

FileSearchTool dataclass

托管工具,允许 LLM 搜索向量存储。目前仅支持 OpenAI 模型,使用 Responses API。

Source code in agents/tool.py
@dataclass
class FileSearchTool:
    """托管工具,允许 LLM 搜索向量存储。目前仅支持 OpenAI 模型,使用 Responses API。
    """

    vector_store_ids: list[str]
    """要搜索的向量存储 ID 列表。"""

    max_num_results: int | None = None
    """返回结果的最大数量。"""

    include_search_results: bool = False
    """是否在 LLM 产生的输出中包含搜索结果。"""

    ranking_options: RankingOptions | None = None
    """搜索的排序选项。"""

    filters: Filters | None = None
    """基于文件属性应用的过滤条件。"""

    @property
    def name(self):
        return "file_search"

vector_store_ids instance-attribute

vector_store_ids: list[str]

要搜索的向量存储 ID 列表。

max_num_results class-attribute instance-attribute

max_num_results: int | None = None

返回结果的最大数量。

include_search_results class-attribute instance-attribute

include_search_results: bool = False

是否在 LLM 产生的输出中包含搜索结果。

ranking_options class-attribute instance-attribute

ranking_options: RankingOptions | None = None

搜索的排序选项。

filters class-attribute instance-attribute

filters: Filters | None = None

基于文件属性应用的过滤条件。

WebSearchTool dataclass

托管工具,允许 LLM 搜索互联网。目前仅支持 OpenAI 模型,使用 Responses API。

Source code in agents/tool.py
@dataclass
class WebSearchTool:
    """托管工具,允许 LLM 搜索互联网。目前仅支持 OpenAI 模型,使用 Responses API。
    """

    user_location: UserLocation | None = None
    """可选的搜索位置。可让你自定义与某地相关的搜索结果。"""

    search_context_size: Literal["low", "medium", "high"] = "medium"
    """用于搜索的上下文量。"""

    @property
    def name(self):
        return "web_search_preview"

user_location class-attribute instance-attribute

user_location: UserLocation | None = None

可选的搜索位置。可让你自定义与某地相关的搜索结果。

search_context_size class-attribute instance-attribute

search_context_size: Literal['low', 'medium', 'high'] = 'medium'

用于搜索的上下文量。

ComputerTool dataclass

托管工具,允许 LLM 控制计算机。

Source code in agents/tool.py
@dataclass
class ComputerTool:
    """托管工具,允许 LLM 控制计算机。"""

    computer: Computer | AsyncComputer
    """计算机实现,描述计算机的环境和维度,并实现如点击、截图等计算机操作。
    """

    @property
    def name(self):
        return "computer_use_preview"

computer instance-attribute

computer: Computer | AsyncComputer

计算机实现,描述计算机的环境和维度,并实现如点击、截图等计算机操作。

MCPToolApprovalRequest dataclass

工具调用审批请求。

Source code in agents/tool.py
@dataclass
class MCPToolApprovalRequest:
    """工具调用审批请求。"""

    ctx_wrapper: RunContextWrapper[Any]
    """运行上下文。"""

    data: McpApprovalRequest
    """来自 MCP 工具审批请求的数据。"""

ctx_wrapper instance-attribute

ctx_wrapper: RunContextWrapper[Any]

运行上下文。

data instance-attribute

data: McpApprovalRequest

来自 MCP 工具审批请求的数据。

MCPToolApprovalFunctionResult

Bases: TypedDict

MCP 工具审批函数的结果。

Source code in agents/tool.py
class MCPToolApprovalFunctionResult(TypedDict):
    """MCP 工具审批函数的结果。"""

    approve: bool
    """是否批准工具调用。"""

    reason: NotRequired[str]
    """可选的拒绝原因。"""

approve instance-attribute

approve: bool

是否批准工具调用。

reason instance-attribute

reason: NotRequired[str]

可选的拒绝原因。

HostedMCPTool dataclass

允许 LLM 使用远程 MCP 服务器的工具。LLM 会自动列出并调用工具,无需你的代码往返。 如果你想通过 stdio 在本地、VPC 或其他非公网环境运行 MCP 服务器,或者你更喜欢本地运行工具调用, 可以使用 agents.mcp 中的服务器,并将 Agent(mcp_servers=[...]) 传递给 agent。

Source code in agents/tool.py
@dataclass
class HostedMCPTool:
    """允许 LLM 使用远程 MCP 服务器的工具。LLM 会自动列出并调用工具,无需你的代码往返。
    如果你想通过 stdio 在本地、VPC 或其他非公网环境运行 MCP 服务器,或者你更喜欢本地运行工具调用,
    可以使用 `agents.mcp` 中的服务器,并将 `Agent(mcp_servers=[...])` 传递给 agent。
    """

    tool_config: Mcp
    """MCP 工具配置,包括服务器 URL 及其他设置。"""

    on_approval_request: MCPToolApprovalFunction | None = None
    """可选函数,当 MCP 工具请求审批时会被调用。如果未提供,你需要手动在输入中添加批准/拒绝并再次调用
    `Runner.run(...)`。
    """

    @property
    def name(self):
        return "hosted_mcp"

tool_config instance-attribute

tool_config: Mcp

MCP 工具配置,包括服务器 URL 及其他设置。

on_approval_request class-attribute instance-attribute

on_approval_request: MCPToolApprovalFunction | None = None

可选函数,当 MCP 工具请求审批时会被调用。如果未提供,你需要手动在输入中添加批准/拒绝并再次调用 Runner.run(...)

CodeInterpreterTool dataclass

允许 LLM 在沙箱环境中执行代码的工具。

Source code in agents/tool.py
@dataclass
class CodeInterpreterTool:
    """允许 LLM 在沙箱环境中执行代码的工具。"""

    tool_config: CodeInterpreter
    """工具配置,包括容器及其他设置。"""

    @property
    def name(self):
        return "code_interpreter"

tool_config instance-attribute

tool_config: CodeInterpreter

工具配置,包括容器及其他设置。

ImageGenerationTool dataclass

允许 LLM 生成图片的工具。

Source code in agents/tool.py
@dataclass
class ImageGenerationTool:
    """允许 LLM 生成图片的工具。"""

    tool_config: ImageGeneration
    """工具配置,包含图片生成相关设置。"""

    @property
    def name(self):
        return "image_generation"

tool_config instance-attribute

tool_config: ImageGeneration

工具配置,包含图片生成相关设置。

LocalShellCommandRequest dataclass

在 shell 上执行命令的请求。

Source code in agents/tool.py
@dataclass
class LocalShellCommandRequest:
    """在 shell 上执行命令的请求。"""

    ctx_wrapper: RunContextWrapper[Any]
    """运行上下文。"""

    data: LocalShellCall
    """本地 shell 工具调用的数据。"""

ctx_wrapper instance-attribute

ctx_wrapper: RunContextWrapper[Any]

运行上下文。

data instance-attribute

data: LocalShellCall

本地 shell 工具调用的数据。

LocalShellTool dataclass

允许 LLM 在 shell 上执行命令的工具。

Source code in agents/tool.py
@dataclass
class LocalShellTool:
    """允许 LLM 在 shell 上执行命令的工具。"""

    executor: LocalShellExecutor
    """用于在 shell 上执行命令的函数。"""

    @property
    def name(self):
        return "local_shell"

executor instance-attribute

用于在 shell 上执行命令的函数。

default_tool_error_function

default_tool_error_function(ctx: RunContextWrapper[Any], error: Exception) -> str

默认的工具错误处理函数,仅返回通用错误信息。

Source code in agents/tool.py
def default_tool_error_function(ctx: RunContextWrapper[Any], error: Exception) -> str:
    """默认的工具错误处理函数,仅返回通用错误信息。"""
    return f"An error occurred while running the tool. Please try again. Error: {str(error)}"

function_tool

function_tool(func: ToolFunction[...], *, name_override: str | None = None, description_override: str | None = None, docstring_style: DocstringStyle | None = None, use_docstring_info: bool = True, failure_error_function: ToolErrorFunction | None = None, strict_mode: bool = True) -> FunctionTool
function_tool(*, name_override: str | None = None, description_override: str | None = None, docstring_style: DocstringStyle | None = None, use_docstring_info: bool = True, failure_error_function: ToolErrorFunction | None = None, strict_mode: bool = True) -> Callable[[ToolFunction[...]], FunctionTool]
function_tool(func: ToolFunction[...] | None = None, *, name_override: str | None = None, description_override: str | None = None, docstring_style: DocstringStyle | None = None, use_docstring_info: bool = True, failure_error_function: ToolErrorFunction | None = default_tool_error_function, strict_mode: bool = True) -> FunctionTool | Callable[[ToolFunction[...]], FunctionTool]

装饰器:将一个函数包装为 FunctionTool。默认情况下,我们会: 1. 解析函数签名,为工具参数生成 JSON schema。 2. 使用函数的 docstring 作为工具描述。 3. 使用函数的 docstring 作为参数描述。 docstring 风格会自动检测,但你可以手动指定。

如果函数的第一个参数是 RunContextWrapper,它 必须 与使用该工具的 agent 的上下文类型一致。

参数说明

func: 要包装的函数。 name_override: 如果提供,使用该名称作为工具名,替代函数名。 description_override: 如果提供,使用该描述作为工具描述,替代函数 docstring。 docstring_style: 如果提供,使用该风格解析 docstring。如果未提供,将自动检测风格。 use_docstring_info: 如果为 True,使用函数 docstring 填充工具描述和参数描述。 failure_error_function: 如果提供,当工具调用失败时使用该函数生成错误信息。错误信息会反馈给 LLM。如果传 None,则不会发送错误信息,而是抛出异常。 strict_mode: 是否启用严格模式生成工具的 JSON schema。强烈建议设置为 True,这样更容易获得正确的 JSON 输入。如果为 False,则允许非严格 JSON schema。例如,带默认值的参数会变为可选,允许额外属性等。详见:https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#supported-schemas

Source code in agents/tool.py
def function_tool(
    func: ToolFunction[...] | None = None,
    *,
    name_override: str | None = None,
    description_override: str | None = None,
    docstring_style: DocstringStyle | None = None,
    use_docstring_info: bool = True,
    failure_error_function: ToolErrorFunction | None = default_tool_error_function,
    strict_mode: bool = True,
) -> FunctionTool | Callable[[ToolFunction[...]], FunctionTool]:
    """
    装饰器:将一个函数包装为 FunctionTool。默认情况下,我们会:
    1. 解析函数签名,为工具参数生成 JSON schema。
    2. 使用函数的 docstring 作为工具描述。
    3. 使用函数的 docstring 作为参数描述。
    docstring 风格会自动检测,但你可以手动指定。

    如果函数的第一个参数是 `RunContextWrapper`,它 *必须* 与使用该工具的 agent 的上下文类型一致。

    参数说明:
        func: 要包装的函数。
        name_override: 如果提供,使用该名称作为工具名,替代函数名。
        description_override: 如果提供,使用该描述作为工具描述,替代函数 docstring。
        docstring_style: 如果提供,使用该风格解析 docstring。如果未提供,将自动检测风格。
        use_docstring_info: 如果为 True,使用函数 docstring 填充工具描述和参数描述。
        failure_error_function: 如果提供,当工具调用失败时使用该函数生成错误信息。错误信息会反馈给 LLM。如果传 None,则不会发送错误信息,而是抛出异常。
        strict_mode: 是否启用严格模式生成工具的 JSON schema。**强烈**建议设置为 True,这样更容易获得正确的 JSON 输入。如果为 False,则允许非严格 JSON schema。例如,带默认值的参数会变为可选,允许额外属性等。详见:https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#supported-schemas
    """

    def _create_function_tool(the_func: ToolFunction[...]) -> FunctionTool:
        schema = function_schema(
            func=the_func,
            name_override=name_override,
            description_override=description_override,
            docstring_style=docstring_style,
            use_docstring_info=use_docstring_info,
            strict_json_schema=strict_mode,
        )

        async def _on_invoke_tool_impl(ctx: RunContextWrapper[Any], input: str) -> Any:
            try:
                json_data: dict[str, Any] = json.loads(input) if input else {}
            except Exception as e:
                if _debug.DONT_LOG_TOOL_DATA:
                    logger.debug(f"工具 {schema.name} 的 JSON 输入无效")
                else:
                    logger.debug(f"工具 {schema.name} 的 JSON 输入无效: {input}")
                raise ModelBehaviorError(
                    f"工具 {schema.name} 的 JSON 输入无效: {input}"
                ) from e

            if _debug.DONT_LOG_TOOL_DATA:
                logger.debug(f"调用工具 {schema.name}")
            else:
                logger.debug(f"调用工具 {schema.name},输入为 {input}")

            try:
                parsed = (
                    schema.params_pydantic_model(**json_data)
                    if json_data
                    else schema.params_pydantic_model()
                )
            except ValidationError as e:
                raise ModelBehaviorError(f"工具 {schema.name} 的 JSON 输入无效: {e}") from e

            args, kwargs_dict = schema.to_call_args(parsed)

            if not _debug.DONT_LOG_TOOL_DATA:
                logger.debug(f"工具调用参数: {args}, 关键字参数: {kwargs_dict}")

            if inspect.iscoroutinefunction(the_func):
                if schema.takes_context:
                    result = await the_func(ctx, *args, **kwargs_dict)
                else:
                    result = await the_func(*args, **kwargs_dict)
            else:
                if schema.takes_context:
                    result = the_func(ctx, *args, **kwargs_dict)
                else:
                    result = the_func(*args, **kwargs_dict)

            if _debug.DONT_LOG_TOOL_DATA:
                logger.debug(f"工具 {schema.name} 执行完成。")
            else:
                logger.debug(f"工具 {schema.name} 返回结果: {result}")

            return result

        async def _on_invoke_tool(ctx: RunContextWrapper[Any], input: str) -> Any:
            try:
                return await _on_invoke_tool_impl(ctx, input)
            except Exception as e:
                if failure_error_function is None:
                    raise

                result = failure_error_function(ctx, e)
                if inspect.isawaitable(result):
                    return await result

                _error_tracing.attach_error_to_current_span(
                    SpanError(
                        message="运行工具时出错(非致命)",
                        data={
                            "tool_name": schema.name,
                            "error": str(e),
                        },
                    )
                )
                return result

        return FunctionTool(
            name=schema.name,
            description=schema.description or "",
            params_json_schema=schema.params_json_schema,
            on_invoke_tool=_on_invoke_tool,
            strict_json_schema=strict_mode,
        )

    # 如果 func 是可调用对象,说明用法为 @function_tool(无括号)
    if callable(func):
        return _create_function_tool(func)

    # 否则为 @function_tool(...),返回装饰器
    def decorator(real_func: ToolFunction[...]) -> FunctionTool:
        return _create_function_tool(real_func)

    return decorator