跳过内容

工具

MCPToolApprovalFunction module-attribute

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

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

LocalShellExecutor module-attribute

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

一个在 shell 上执行命令的函数。

ShellExecutor module-attribute

ShellExecutor = Callable[
    [ShellCommandRequest],
    MaybeAwaitable[Union[str, ShellResult]],
]

执行 shell 命令序列,并返回文本或结构化输出。

Tool module-attribute

可以在代理中使用的工具。

ToolOutputText

基础: BaseModel

表示应作为文本发送到模型的工具输出。

源代码在 src/agents/tool.py
class ToolOutputText(BaseModel):
    """Represents a tool output that should be sent to the model as text."""

    type: Literal["text"] = "text"
    text: str

ToolOutputTextDict

基础: TypedDict

用于文本工具输出的 TypedDict 变体。

源代码在 src/agents/tool.py
class ToolOutputTextDict(TypedDict, total=False):
    """TypedDict variant for text tool outputs."""

    type: Literal["text"]
    text: str

ToolOutputImage

基础: BaseModel

表示应作为图像发送到模型的工具输出。

您可以提供一个 image_url(URL 或数据 URL)或一个用于先前上传内容的 file_id。可选的 detail 可以控制视觉细节。

源代码在 src/agents/tool.py
class ToolOutputImage(BaseModel):
    """Represents a tool output that should be sent to the model as an image.

    You can provide either an `image_url` (URL or data URL) or a `file_id` for previously uploaded
    content. The optional `detail` can control vision detail.
    """

    type: Literal["image"] = "image"
    image_url: str | None = None
    file_id: str | None = None
    detail: Literal["low", "high", "auto"] | None = None

    @model_validator(mode="after")
    def check_at_least_one_required_field(self) -> ToolOutputImage:
        """Validate that at least one of image_url or file_id is provided."""
        if self.image_url is None and self.file_id is None:
            raise ValueError("At least one of image_url or file_id must be provided")
        return self

check_at_least_one_required_field

check_at_least_one_required_field() -> ToolOutputImage

验证是否提供了 image_url 或 file_id 中的至少一个。

源代码在 src/agents/tool.py
@model_validator(mode="after")
def check_at_least_one_required_field(self) -> ToolOutputImage:
    """Validate that at least one of image_url or file_id is provided."""
    if self.image_url is None and self.file_id is None:
        raise ValueError("At least one of image_url or file_id must be provided")
    return self

ToolOutputImageDict

基础: TypedDict

用于图像工具输出的 TypedDict 变体。

源代码在 src/agents/tool.py
class ToolOutputImageDict(TypedDict, total=False):
    """TypedDict variant for image tool outputs."""

    type: Literal["image"]
    image_url: NotRequired[str]
    file_id: NotRequired[str]
    detail: NotRequired[Literal["low", "high", "auto"]]

ToolOutputFileContent

基础: BaseModel

表示应作为文件发送到模型的工具输出。

提供 file_data(base64)、file_urlfile_id 中的一个。在使用 file_data 时,您还可以提供一个可选的 filename 来提示文件名。

源代码在 src/agents/tool.py
class ToolOutputFileContent(BaseModel):
    """Represents a tool output that should be sent to the model as a file.

    Provide one of `file_data` (base64), `file_url`, or `file_id`. You may also
    provide an optional `filename` when using `file_data` to hint file name.
    """

    type: Literal["file"] = "file"
    file_data: str | None = None
    file_url: str | None = None
    file_id: str | None = None
    filename: str | None = None

    @model_validator(mode="after")
    def check_at_least_one_required_field(self) -> ToolOutputFileContent:
        """Validate that at least one of file_data, file_url, or file_id is provided."""
        if self.file_data is None and self.file_url is None and self.file_id is None:
            raise ValueError("At least one of file_data, file_url, or file_id must be provided")
        return self

check_at_least_one_required_field

check_at_least_one_required_field() -> (
    ToolOutputFileContent
)

验证是否提供了 file_data、file_url 或 file_id 中的至少一个。

源代码在 src/agents/tool.py
@model_validator(mode="after")
def check_at_least_one_required_field(self) -> ToolOutputFileContent:
    """Validate that at least one of file_data, file_url, or file_id is provided."""
    if self.file_data is None and self.file_url is None and self.file_id is None:
        raise ValueError("At least one of file_data, file_url, or file_id must be provided")
    return self

ToolOutputFileContentDict

基础: TypedDict

用于文件内容工具输出的 TypedDict 变体。

源代码在 src/agents/tool.py
class ToolOutputFileContentDict(TypedDict, total=False):
    """TypedDict variant for file content tool outputs."""

    type: Literal["file"]
    file_data: NotRequired[str]
    file_url: NotRequired[str]
    file_id: NotRequired[str]
    filename: NotRequired[str]

ComputerCreate

基类:Protocol[ComputerT_co]

为当前运行上下文初始化计算机。

源代码在 src/agents/tool.py
class ComputerCreate(Protocol[ComputerT_co]):
    """Initializes a computer for the current run context."""

    def __call__(self, *, run_context: RunContextWrapper[Any]) -> MaybeAwaitable[ComputerT_co]: ...

ComputerDispose

基类:Protocol[ComputerT_contra]

清理为运行上下文初始化的计算机。

源代码在 src/agents/tool.py
class ComputerDispose(Protocol[ComputerT_contra]):
    """Cleans up a computer initialized for a run context."""

    def __call__(
        self,
        *,
        run_context: RunContextWrapper[Any],
        computer: ComputerT_contra,
    ) -> MaybeAwaitable[None]: ...

ComputerProvider dataclass

基类:Generic[ComputerT]

配置用于每次运行计算机生命周期管理的创建/销毁钩子。

源代码在 src/agents/tool.py
@dataclass
class ComputerProvider(Generic[ComputerT]):
    """Configures create/dispose hooks for per-run computer lifecycle management."""

    create: ComputerCreate[ComputerT]
    dispose: ComputerDispose[ComputerT] | None = None

FunctionToolResult dataclass

源代码在 src/agents/tool.py
@dataclass
class FunctionToolResult:
    tool: FunctionTool
    """The tool that was run."""

    output: Any
    """The output of the tool."""

    run_item: RunItem
    """The run item that was produced as a result of the tool call."""

tool instance-attribute

运行的工具。

输出 实例属性

output: Any

工具的输出。

run_item instance-attribute

run_item: RunItem

作为工具调用结果产生的运行项。

FunctionTool dataclass

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

源代码在 src/agents/tool.py
@dataclass
class FunctionTool:
    """A tool that wraps a function. In most cases, you should use  the `function_tool` helpers to
    create a FunctionTool, as they let you easily wrap a Python function.
    """

    name: str
    """The name of the tool, as shown to the LLM. Generally the name of the function."""

    description: str
    """A description of the tool, as shown to the LLM."""

    params_json_schema: dict[str, Any]
    """The JSON schema for the tool's parameters."""

    on_invoke_tool: Callable[[ToolContext[Any], str], Awaitable[Any]]
    """A function that invokes the tool with the given context and parameters. The params passed
    are:
    1. The tool run context.
    2. The arguments from the LLM, as a JSON string.

    You must return a one of the structured tool output types (e.g. ToolOutputText, ToolOutputImage,
    ToolOutputFileContent) or a string representation of the tool output, or a list of them,
    or something we can call `str()` on.
    In case of errors, you can either raise an Exception (which will cause the run to fail) or
    return a string error message (which will be sent back to the LLM).
    """

    strict_json_schema: bool = True
    """Whether the JSON schema is in strict mode. We **strongly** recommend setting this to True,
    as it increases the likelihood of correct JSON input."""

    is_enabled: bool | Callable[[RunContextWrapper[Any], AgentBase], MaybeAwaitable[bool]] = True
    """Whether the tool is enabled. Either a bool or a Callable that takes the run context and agent
    and returns whether the tool is enabled. You can use this to dynamically enable/disable a tool
    based on your context/state."""

    # Tool-specific guardrails
    tool_input_guardrails: list[ToolInputGuardrail[Any]] | None = None
    """Optional list of input guardrails to run before invoking this tool."""

    tool_output_guardrails: list[ToolOutputGuardrail[Any]] | None = None
    """Optional list of output guardrails to run after invoking this tool."""

    def __post_init__(self):
        if self.strict_json_schema:
            self.params_json_schema = ensure_strict_json_schema(self.params_json_schema)

name instance-attribute

name: str

工具的名称,如向 LLM 所示。通常是函数名称。

description instance-attribute

description: str

工具的描述,如向 LLM 所示。

params_json_schema instance-attribute

params_json_schema: dict[str, Any]

工具参数的 JSON 模式。

on_invoke_tool instance-attribute

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

一个函数,它使用给定的上下文和参数调用该工具。传递的参数是:1. 工具运行上下文。2. 来自 LLM 的参数,作为 JSON 字符串。

您必须返回结构化工具输出类型之一(例如 ToolOutputText、ToolOutputImage、ToolOutputFileContent)或工具输出的字符串表示形式,或者它们的列表,或者我们可以调用 str() 的内容。如果发生错误,您可以选择引发异常(这将导致运行失败)或返回字符串错误消息(这将发送回 LLM)。

strict_json_schema 类属性 实例属性

strict_json_schema: bool = True

JSON 模式是否处于严格模式。我们强烈建议将其设置为 True,因为它会增加生成正确 JSON 输入的可能性。

is_enabled class-attribute instance-attribute

is_enabled: (
    bool
    | Callable[
        [RunContextWrapper[Any], AgentBase],
        MaybeAwaitable[bool],
    ]
) = True

工具是否启用。一个布尔值或一个接受运行上下文和代理并返回工具是否启用的 Callable。您可以使用此功能根据您的上下文/状态动态启用/禁用工具。

tool_input_guardrails class-attribute instance-attribute

tool_input_guardrails: (
    list[ToolInputGuardrail[Any]] | None
) = None

可选的输入防护栏列表,在调用此工具之前运行。

tool_output_guardrails class-attribute instance-attribute

tool_output_guardrails: (
    list[ToolOutputGuardrail[Any]] | None
) = None

可选的输出防护栏列表,在调用此工具之后运行。

FileSearchTool dataclass

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

源代码在 src/agents/tool.py
@dataclass
class FileSearchTool:
    """A hosted tool that lets the LLM search through a vector store. Currently only supported with
    OpenAI models, using the Responses API.
    """

    vector_store_ids: list[str]
    """The IDs of the vector stores to search."""

    max_num_results: int | None = None
    """The maximum number of results to return."""

    include_search_results: bool = False
    """Whether to include the search results in the output produced by the LLM."""

    ranking_options: RankingOptions | None = None
    """Ranking options for search."""

    filters: Filters | None = None
    """A filter to apply based on file attributes."""

    @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。

源代码在 src/agents/tool.py
@dataclass
class WebSearchTool:
    """A hosted tool that lets the LLM search the web. Currently only supported with OpenAI models,
    using the Responses API.
    """

    user_location: UserLocation | None = None
    """Optional location for the search. Lets you customize results to be relevant to a location."""

    filters: WebSearchToolFilters | None = None
    """A filter to apply based on file attributes."""

    search_context_size: Literal["low", "medium", "high"] = "medium"
    """The amount of context to use for the search."""

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

user_location class-attribute instance-attribute

user_location: UserLocation | None = None

搜索的可选位置。允许您自定义结果,使其与位置相关。

filters class-attribute instance-attribute

filters: Filters | None = None

应用于文件属性的过滤器。

search_context_size class-attribute instance-attribute

search_context_size: Literal["low", "medium", "high"] = (
    "medium"
)

用于搜索的上下文量。

ComputerTool dataclass

基类:Generic[ComputerT]

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

源代码在 src/agents/tool.py
@dataclass(eq=False)
class ComputerTool(Generic[ComputerT]):
    """A hosted tool that lets the LLM control a computer."""

    computer: ComputerConfig[ComputerT]
    """The computer implementation, or a factory that produces a computer per run."""

    on_safety_check: Callable[[ComputerToolSafetyCheckData], MaybeAwaitable[bool]] | None = None
    """Optional callback to acknowledge computer tool safety checks."""

    def __post_init__(self) -> None:
        _store_computer_initializer(self)

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

computer instance-attribute

computer: ComputerConfig[ComputerT]

计算机实现,或为每次运行生成计算机的工厂。

on_safety_check class-attribute instance-attribute

on_safety_check: (
    Callable[
        [ComputerToolSafetyCheckData], MaybeAwaitable[bool]
    ]
    | None
) = None

可选的回调函数,用于确认计算机工具的安全检查。

ComputerToolSafetyCheckData dataclass

计算机工具安全检查的信息。

源代码在 src/agents/tool.py
@dataclass
class ComputerToolSafetyCheckData:
    """Information about a computer tool safety check."""

    ctx_wrapper: RunContextWrapper[Any]
    """The run context."""

    agent: Agent[Any]
    """The agent performing the computer action."""

    tool_call: ResponseComputerToolCall
    """The computer tool call."""

    safety_check: PendingSafetyCheck
    """The pending safety check to acknowledge."""

ctx_wrapper instance-attribute

ctx_wrapper: RunContextWrapper[Any]

运行上下文。

agent 实例属性

agent: Agent[Any]

执行计算机操作的代理。

tool_call instance-attribute

tool_call: ResponseComputerToolCall

计算机工具调用。

safety_check instance-attribute

safety_check: PendingSafetyCheck

待确认的安全检查。

MCPToolApprovalRequest dataclass

批准工具调用的请求。

源代码在 src/agents/tool.py
@dataclass
class MCPToolApprovalRequest:
    """A request to approve a tool call."""

    ctx_wrapper: RunContextWrapper[Any]
    """The run context."""

    data: McpApprovalRequest
    """The data from the MCP tool approval request."""

ctx_wrapper instance-attribute

ctx_wrapper: RunContextWrapper[Any]

运行上下文。

data instance-attribute

data: McpApprovalRequest

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

MCPToolApprovalFunctionResult

基础: TypedDict

MCP 工具批准函数的结果。

源代码在 src/agents/tool.py
class MCPToolApprovalFunctionResult(TypedDict):
    """The result of an MCP tool approval function."""

    approve: bool
    """Whether to approve the tool call."""

    reason: NotRequired[str]
    """An optional reason, if rejected."""

approve instance-attribute

approve: bool

是否批准工具调用。

reason instance-attribute

reason: NotRequired[str]

一个可选的原因,如果被拒绝。

HostedMCPTool dataclass

一个允许 LLM 使用远程 MCP 服务器的工具。LLM 将自动列出和调用工具,无需往返您的代码。如果您想通过 stdio 在本地运行 MCP 服务器,在 VPC 或其他非公开可访问的环境中,或者您只是更喜欢在本地运行工具调用,那么您可以改为使用 agents.mcp 中的服务器并将 Agent(mcp_servers=[...]) 传递给代理。

源代码在 src/agents/tool.py
@dataclass
class HostedMCPTool:
    """A tool that allows the LLM to use a remote MCP server. The LLM will automatically list and
    call tools, without requiring a round trip back to your code.
    If you want to run MCP servers locally via stdio, in a VPC or other non-publicly-accessible
    environment, or you just prefer to run tool calls locally, then you can instead use the servers
    in `agents.mcp` and pass `Agent(mcp_servers=[...])` to the agent."""

    tool_config: Mcp
    """The MCP tool config, which includes the server URL and other settings."""

    on_approval_request: MCPToolApprovalFunction | None = None
    """An optional function that will be called if approval is requested for an MCP tool. If not
    provided, you will need to manually add approvals/rejections to the input and call
    `Runner.run(...)` again."""

    @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 在沙盒环境中执行代码的工具。

源代码在 src/agents/tool.py
@dataclass
class CodeInterpreterTool:
    """A tool that allows the LLM to execute code in a sandboxed environment."""

    tool_config: CodeInterpreter
    """The tool config, which includes the container and other settings."""

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

tool_config instance-attribute

tool_config: CodeInterpreter

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

ImageGenerationTool dataclass

一个允许 LLM 生成图像的工具。

源代码在 src/agents/tool.py
@dataclass
class ImageGenerationTool:
    """A tool that allows the LLM to generate images."""

    tool_config: ImageGeneration
    """The tool config, which image generation settings."""

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

tool_config instance-attribute

tool_config: ImageGeneration

工具配置,包括图像生成设置。

LocalShellCommandRequest dataclass

一个在 shell 上执行命令的请求。

源代码在 src/agents/tool.py
@dataclass
class LocalShellCommandRequest:
    """A request to execute a command on a shell."""

    ctx_wrapper: RunContextWrapper[Any]
    """The run context."""

    data: LocalShellCall
    """The data from the local shell tool call."""

ctx_wrapper instance-attribute

ctx_wrapper: RunContextWrapper[Any]

运行上下文。

data instance-attribute

data: LocalShellCall

来自本地 shell 工具调用的数据。

LocalShellTool dataclass

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

有关详细信息,请参阅:https://platform.openai.com/docs/guides/tools-local-shell

源代码在 src/agents/tool.py
@dataclass
class LocalShellTool:
    """A tool that allows the LLM to execute commands on a shell.

    For more details, see:
    https://platform.openai.com/docs/guides/tools-local-shell
    """

    executor: LocalShellExecutor
    """A function that executes a command on a shell."""

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

executor instance-attribute

一个在 shell 上执行命令的函数。

ShellCallOutcome dataclass

描述 shell 命令的终端状态。

源代码在 src/agents/tool.py
@dataclass
class ShellCallOutcome:
    """Describes the terminal condition of a shell command."""

    type: Literal["exit", "timeout"]
    exit_code: int | None = None

ShellCommandOutput dataclass

单个 shell 命令执行的结构化输出。

源代码在 src/agents/tool.py
@dataclass
class ShellCommandOutput:
    """Structured output for a single shell command execution."""

    stdout: str = ""
    stderr: str = ""
    outcome: ShellCallOutcome = field(default_factory=_default_shell_outcome)
    command: str | None = None
    provider_data: dict[str, Any] | None = None

    @property
    def exit_code(self) -> int | None:
        return self.outcome.exit_code

    @property
    def status(self) -> Literal["completed", "timeout"]:
        return "timeout" if self.outcome.type == "timeout" else "completed"

ShellResult dataclass

shell 执行器返回的结果。

源代码在 src/agents/tool.py
@dataclass
class ShellResult:
    """Result returned by a shell executor."""

    output: list[ShellCommandOutput]
    max_output_length: int | None = None
    provider_data: dict[str, Any] | None = None

ShellActionRequest dataclass

下一代 shell 调用的操作负载。

源代码在 src/agents/tool.py
@dataclass
class ShellActionRequest:
    """Action payload for a next-generation shell call."""

    commands: list[str]
    timeout_ms: int | None = None
    max_output_length: int | None = None

ShellCallData dataclass

提供给 shell 执行器的标准化 shell 调用数据。

源代码在 src/agents/tool.py
@dataclass
class ShellCallData:
    """Normalized shell call data provided to shell executors."""

    call_id: str
    action: ShellActionRequest
    status: Literal["in_progress", "completed"] | None = None
    raw: Any | None = None

ShellCommandRequest dataclass

一个执行现代 shell 调用的请求。

源代码在 src/agents/tool.py
@dataclass
class ShellCommandRequest:
    """A request to execute a modern shell call."""

    ctx_wrapper: RunContextWrapper[Any]
    data: ShellCallData

ShellTool dataclass

下一代 shell 工具。LocalShellTool 将被弃用,转而使用此工具。

源代码在 src/agents/tool.py
@dataclass
class ShellTool:
    """Next-generation shell tool. LocalShellTool will be deprecated in favor of this."""

    executor: ShellExecutor
    name: str = "shell"

    @property
    def type(self) -> str:
        return "shell"

ApplyPatchTool dataclass

托管 apply_patch 工具。允许模型通过统一的 diff 请求文件修改。

源代码在 src/agents/tool.py
@dataclass
class ApplyPatchTool:
    """Hosted apply_patch tool. Lets the model request file mutations via unified diffs."""

    editor: ApplyPatchEditor
    name: str = "apply_patch"

    @property
    def type(self) -> str:
        return "apply_patch"

resolve_computer async

resolve_computer(
    *,
    tool: ComputerTool[Any],
    run_context: RunContextWrapper[Any],
) -> ComputerLike

解析给定运行上下文的计算机,如果需要则初始化它。

源代码在 src/agents/tool.py
async def resolve_computer(
    *, tool: ComputerTool[Any], run_context: RunContextWrapper[Any]
) -> ComputerLike:
    """Resolve a computer for a given run context, initializing it if needed."""
    per_context = _computer_cache.get(tool)
    if per_context is None:
        per_context = weakref.WeakKeyDictionary()
        _computer_cache[tool] = per_context

    cached = per_context.get(run_context)
    if cached is not None:
        _track_resolved_computer(tool=tool, run_context=run_context, resolved=cached)
        return cached.computer

    initializer_config = _get_computer_initializer(tool)
    lifecycle: ComputerProvider[Any] | None = (
        cast(ComputerProvider[Any], initializer_config)
        if _is_computer_provider(initializer_config)
        else None
    )
    initializer: ComputerCreate[Any] | None = None
    disposer: ComputerDispose[Any] | None = lifecycle.dispose if lifecycle else None

    if lifecycle is not None:
        initializer = lifecycle.create
    elif callable(initializer_config):
        initializer = initializer_config
    elif _is_computer_provider(tool.computer):
        lifecycle_provider = cast(ComputerProvider[Any], tool.computer)
        initializer = lifecycle_provider.create
        disposer = lifecycle_provider.dispose

    if initializer:
        computer_candidate = initializer(run_context=run_context)
        computer = (
            await computer_candidate
            if inspect.isawaitable(computer_candidate)
            else computer_candidate
        )
    else:
        computer = cast(ComputerLike, tool.computer)

    if not isinstance(computer, (Computer, AsyncComputer)):
        raise UserError("The computer tool did not provide a computer instance.")

    resolved = _ResolvedComputer(computer=computer, dispose=disposer)
    per_context[run_context] = resolved
    _track_resolved_computer(tool=tool, run_context=run_context, resolved=resolved)
    tool.computer = computer
    return computer

dispose_resolved_computers async

dispose_resolved_computers(
    *, run_context: RunContextWrapper[Any]
) -> None

销毁为提供的运行上下文创建的任何计算机实例。

源代码在 src/agents/tool.py
async def dispose_resolved_computers(*, run_context: RunContextWrapper[Any]) -> None:
    """Dispose any computer instances created for the provided run context."""
    resolved_by_tool = _computers_by_run_context.pop(run_context, None)
    if not resolved_by_tool:
        return

    disposers: list[tuple[ComputerDispose[ComputerLike], ComputerLike]] = []

    for tool, _resolved in resolved_by_tool.items():
        per_context = _computer_cache.get(tool)
        if per_context is not None:
            per_context.pop(run_context, None)

        initializer = _get_computer_initializer(tool)
        if initializer is not None:
            tool.computer = initializer

        if _resolved.dispose is not None:
            disposers.append((_resolved.dispose, _resolved.computer))

    for dispose, computer in disposers:
        try:
            result = dispose(run_context=run_context, computer=computer)
            if inspect.isawaitable(result):
                await result
        except Exception as exc:
            logger.warning("Failed to dispose computer for run context: %s", exc)

default_tool_error_function

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

默认工具错误函数,它只是返回一个通用错误消息。

源代码在 src/agents/tool.py
def default_tool_error_function(ctx: RunContextWrapper[Any], error: Exception) -> str:
    """The default tool error function, which just returns a generic error message."""
    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,
    is_enabled: bool
    | Callable[
        [RunContextWrapper[Any], AgentBase],
        MaybeAwaitable[bool],
    ] = True,
    tool_input_guardrails: list[ToolInputGuardrail[Any]]
    | None = None,
    tool_output_guardrails: list[ToolOutputGuardrail[Any]]
    | None = None,
) -> 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,
    is_enabled: bool
    | Callable[
        [RunContextWrapper[Any], AgentBase],
        MaybeAwaitable[bool],
    ] = True,
    tool_input_guardrails: list[ToolInputGuardrail[Any]]
    | None = None,
    tool_output_guardrails: list[ToolOutputGuardrail[Any]]
    | None = None,
) -> 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,
    is_enabled: bool
    | Callable[
        [RunContextWrapper[Any], AgentBase],
        MaybeAwaitable[bool],
    ] = True,
    tool_input_guardrails: list[ToolInputGuardrail[Any]]
    | None = None,
    tool_output_guardrails: list[ToolOutputGuardrail[Any]]
    | None = None,
) -> (
    FunctionTool
    | Callable[[ToolFunction[...]], FunctionTool]
)

装饰器,用于从函数创建 FunctionTool。默认情况下,我们将:1. 解析函数签名以创建工具参数的 JSON schema。 2. 使用函数的文档字符串填充工具的描述。 3. 使用函数的文档字符串填充参数描述。 文档字符串的风格会自动检测,但您可以覆盖它。

如果函数将 RunContextWrapper 作为第一个参数,它必须与使用该工具的代理的上下文类型匹配。

参数

名称 类型 描述 默认
func ToolFunction[...] | None

要包装的函数。

None
name_override str | None

如果提供,则使用此名称作为工具的名称,而不是函数的名称。

None
description_override str | None

如果提供,则使用此描述作为工具的描述,而不是函数的文档字符串。

None
docstring_style DocstringStyle | None

如果提供,则使用此风格作为工具的文档字符串。 如果未提供,我们将尝试自动检测风格。

None
use_docstring_info bool

如果为 True,则使用函数的文档字符串填充工具的描述和参数描述。

True
failure_error_function ToolErrorFunction | None

如果提供,则使用此函数生成工具调用失败时的错误消息。 错误消息将发送给 LLM。 如果传递 None,则不会发送错误消息,而是会引发异常。

default_tool_error_function
strict_mode bool

是否为工具的 JSON schema 启用严格模式。 我们强烈建议将其设置为 True,因为它增加了正确 JSON 输入的可能性。 如果为 False,则允许非严格的 JSON schema。 例如,如果参数具有默认值,它将是可选的,允许其他属性等。 更多信息请参见:https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#supported-schemas

True
is_enabled bool | Callable[[RunContextWrapper[Any], AgentBase], MaybeAwaitable[bool]]

工具是否启用。 可以是 bool 或一个可调用对象,它接收运行上下文和代理,并返回工具是否启用。 禁用的工具在运行时对 LLM 隐藏。

True
tool_input_guardrails list[ToolInputGuardrail[Any]] | None

在调用工具之前运行的 guardrail 的可选列表。

None
tool_output_guardrails list[ToolOutputGuardrail[Any]] | None

在工具返回后运行的 guardrail 的可选列表。

None
源代码在 src/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,
    is_enabled: bool | Callable[[RunContextWrapper[Any], AgentBase], MaybeAwaitable[bool]] = True,
    tool_input_guardrails: list[ToolInputGuardrail[Any]] | None = None,
    tool_output_guardrails: list[ToolOutputGuardrail[Any]] | None = None,
) -> FunctionTool | Callable[[ToolFunction[...]], FunctionTool]:
    """
    Decorator to create a FunctionTool from a function. By default, we will:
    1. Parse the function signature to create a JSON schema for the tool's parameters.
    2. Use the function's docstring to populate the tool's description.
    3. Use the function's docstring to populate argument descriptions.
    The docstring style is detected automatically, but you can override it.

    If the function takes a `RunContextWrapper` as the first argument, it *must* match the
    context type of the agent that uses the tool.

    Args:
        func: The function to wrap.
        name_override: If provided, use this name for the tool instead of the function's name.
        description_override: If provided, use this description for the tool instead of the
            function's docstring.
        docstring_style: If provided, use this style for the tool's docstring. If not provided,
            we will attempt to auto-detect the style.
        use_docstring_info: If True, use the function's docstring to populate the tool's
            description and argument descriptions.
        failure_error_function: If provided, use this function to generate an error message when
            the tool call fails. The error message is sent to the LLM. If you pass None, then no
            error message will be sent and instead an Exception will be raised.
        strict_mode: Whether to enable strict mode for the tool's JSON schema. We *strongly*
            recommend setting this to True, as it increases the likelihood of correct JSON input.
            If False, it allows non-strict JSON schemas. For example, if a parameter has a default
            value, it will be optional, additional properties are allowed, etc. See here for more:
            https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#supported-schemas
        is_enabled: Whether the tool is enabled. Can be a bool or a callable that takes the run
            context and agent and returns whether the tool is enabled. Disabled tools are hidden
            from the LLM at runtime.
        tool_input_guardrails: Optional list of guardrails to run before invoking the tool.
        tool_output_guardrails: Optional list of guardrails to run after the tool returns.
    """

    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: ToolContext[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"Invalid JSON input for tool {schema.name}")
                else:
                    logger.debug(f"Invalid JSON input for tool {schema.name}: {input}")
                raise ModelBehaviorError(
                    f"Invalid JSON input for tool {schema.name}: {input}"
                ) from e

            if _debug.DONT_LOG_TOOL_DATA:
                logger.debug(f"Invoking tool {schema.name}")
            else:
                logger.debug(f"Invoking tool {schema.name} with input {input}")

            try:
                parsed = (
                    schema.params_pydantic_model(**json_data)
                    if json_data
                    else schema.params_pydantic_model()
                )
            except ValidationError as e:
                raise ModelBehaviorError(f"Invalid JSON input for tool {schema.name}: {e}") from e

            args, kwargs_dict = schema.to_call_args(parsed)

            if not _debug.DONT_LOG_TOOL_DATA:
                logger.debug(f"Tool call args: {args}, kwargs: {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"Tool {schema.name} completed.")
            else:
                logger.debug(f"Tool {schema.name} returned {result}")

            return result

        async def _on_invoke_tool(ctx: ToolContext[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="Error running tool (non-fatal)",
                        data={
                            "tool_name": schema.name,
                            "error": str(e),
                        },
                    )
                )
                if _debug.DONT_LOG_TOOL_DATA:
                    logger.debug(f"Tool {schema.name} failed")
                else:
                    logger.error(
                        f"Tool {schema.name} failed: {input} {e}",
                        exc_info=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,
            is_enabled=is_enabled,
            tool_input_guardrails=tool_input_guardrails,
            tool_output_guardrails=tool_output_guardrails,
        )

    # If func is actually a callable, we were used as @function_tool with no parentheses
    if callable(func):
        return _create_function_tool(func)

    # Otherwise, we were used as @function_tool(...), so return a decorator
    def decorator(real_func: ToolFunction[...]) -> FunctionTool:
        return _create_function_tool(real_func)

    return decorator