跳过内容

工具

工具让代理采取行动:例如获取数据、运行代码、调用外部 API,甚至使用计算机。Agent SDK 中有三类工具

  • 托管工具:这些在 LLM 服务器上与 AI 模型一起运行。OpenAI 提供检索、网络搜索和计算机使用作为托管工具。
  • 函数调用:这些允许您将任何 Python 函数用作工具。
  • 代理作为工具:这允许您将一个代理用作工具,允许代理调用其他代理而无需将控制权交给它们。

托管工具

OpenAI 在使用 OpenAIResponsesModel 时提供了一些内置工具

  • WebSearchTool 数据类允许代理搜索网络。
  • FileSearchTool 数据类允许从您的 OpenAI 向量存储中检索信息。
  • ComputerTool 数据类允许自动化计算机使用任务。
  • CodeInterpreterTool 数据类允许 LLM 在沙盒环境中执行代码。
  • HostedMCPTool 数据类将远程 MCP 服务器的工具暴露给模型。
  • ImageGenerationTool 数据类根据提示生成图像。
  • LocalShellTool 数据类在您的机器上运行 shell 命令。
from agents import Agent, FileSearchTool, Runner, WebSearchTool

agent = Agent(
    name="Assistant",
    tools=[
        WebSearchTool(),
        FileSearchTool(
            max_num_results=3,
            vector_store_ids=["VECTOR_STORE_ID"],
        ),
    ],
)

async def main():
    result = await Runner.run(agent, "Which coffee shop should I go to, taking into account my preferences and the weather today in SF?")
    print(result.final_output)

函数工具

您可以使用任何 Python 函数作为工具。Agents SDK 将自动设置该工具

  • 工具的名称将是 Python 函数的名称(或者您可以提供一个名称)
  • 工具描述将从函数的文档字符串中获取(或者您可以提供描述)
  • 函数的输入模式将从函数的参数自动创建
  • 每个输入的描述将从函数的文档字符串中获取,除非被禁用

我们使用 Python 的 inspect 模块提取函数签名,以及 griffe 解析文档字符串和 pydantic 用于模式创建。

import json

from typing_extensions import TypedDict, Any

from agents import Agent, FunctionTool, RunContextWrapper, function_tool


class Location(TypedDict):
    lat: float
    long: float

@function_tool  # (1)!
async def fetch_weather(location: Location) -> str:
    # (2)!
    """Fetch the weather for a given location.

    Args:
        location: The location to fetch the weather for.
    """
    # In real life, we'd fetch the weather from a weather API
    return "sunny"


@function_tool(name_override="fetch_data")  # (3)!
def read_file(ctx: RunContextWrapper[Any], path: str, directory: str | None = None) -> str:
    """Read the contents of a file.

    Args:
        path: The path to the file to read.
        directory: The directory to read the file from.
    """
    # In real life, we'd read the file from the file system
    return "<file contents>"


agent = Agent(
    name="Assistant",
    tools=[fetch_weather, read_file],  # (4)!
)

for tool in agent.tools:
    if isinstance(tool, FunctionTool):
        print(tool.name)
        print(tool.description)
        print(json.dumps(tool.params_json_schema, indent=2))
        print()
  1. 您可以将任何 Python 类型作为函数的参数,并且该函数可以是同步的或异步的。
  2. 如果存在文档字符串,则用于捕获描述和参数描述
  3. 函数可以选择接收 context(必须是第一个参数)。您还可以设置覆盖,例如工具的名称、描述、要使用的文档字符串样式等。
  4. 您可以将装饰后的函数传递给工具列表。
展开以查看输出
fetch_weather
Fetch the weather for a given location.
{
"$defs": {
  "Location": {
    "properties": {
      "lat": {
        "title": "Lat",
        "type": "number"
      },
      "long": {
        "title": "Long",
        "type": "number"
      }
    },
    "required": [
      "lat",
      "long"
    ],
    "title": "Location",
    "type": "object"
  }
},
"properties": {
  "location": {
    "$ref": "#/$defs/Location",
    "description": "The location to fetch the weather for."
  }
},
"required": [
  "location"
],
"title": "fetch_weather_args",
"type": "object"
}

fetch_data
Read the contents of a file.
{
"properties": {
  "path": {
    "description": "The path to the file to read.",
    "title": "Path",
    "type": "string"
  },
  "directory": {
    "anyOf": [
      {
        "type": "string"
      },
      {
        "type": "null"
      }
    ],
    "default": null,
    "description": "The directory to read the file from.",
    "title": "Directory"
  }
},
"required": [
  "path"
],
"title": "fetch_data_args",
"type": "object"
}

从函数工具返回图像或文件

除了返回文本输出外,您还可以将一个或多个图像或文件作为函数工具的输出返回。为此,您可以返回以下任何内容

自定义函数工具

有时,您不想将 Python 函数用作工具。如果您愿意,可以直接创建一个 FunctionTool。您需要提供

  • name
  • description
  • params_json_schema,即参数的 JSON 模式
  • on_invoke_tool,这是一个异步函数,它接收一个 ToolContext 和参数作为 JSON 字符串,并且必须将工具输出作为字符串返回。
from typing import Any

from pydantic import BaseModel

from agents import RunContextWrapper, FunctionTool



def do_some_work(data: str) -> str:
    return "done"


class FunctionArgs(BaseModel):
    username: str
    age: int


async def run_function(ctx: RunContextWrapper[Any], args: str) -> str:
    parsed = FunctionArgs.model_validate_json(args)
    return do_some_work(data=f"{parsed.username} is {parsed.age} years old")


tool = FunctionTool(
    name="process_user",
    description="Processes extracted user data",
    params_json_schema=FunctionArgs.model_json_schema(),
    on_invoke_tool=run_function,
)

自动参数和文档字符串解析

如前所述,我们自动解析函数签名以提取工具的模式,并解析文档字符串以提取工具和单个参数的描述。关于这一点的一些说明

  1. 签名解析通过 inspect 模块完成。我们使用类型注释来理解参数的类型,并动态构建一个 Pydantic 模型来表示整体模式。它支持大多数类型,包括 Python 原始类型、Pydantic 模型、TypedDict 等。
  2. 我们使用 griffe 解析文档字符串。支持的文档字符串格式为 googlesphinxnumpy。我们尝试自动检测文档字符串格式,但这只是尽力而为,您可以显式设置它,并在调用 function_tool 时设置它。您还可以通过将 use_docstring_info 设置为 False 来禁用文档字符串解析。

模式提取的代码位于 agents.function_schema 中。

代理作为工具

在某些工作流程中,您可能希望一个中心代理来协调一个专门代理的网络,而不是将控制权交给它们。您可以通过将代理建模为工具来做到这一点。

from agents import Agent, Runner
import asyncio

spanish_agent = Agent(
    name="Spanish agent",
    instructions="You translate the user's message to Spanish",
)

french_agent = Agent(
    name="French agent",
    instructions="You translate the user's message to French",
)

orchestrator_agent = Agent(
    name="orchestrator_agent",
    instructions=(
        "You are a translation agent. You use the tools given to you to translate."
        "If asked for multiple translations, you call the relevant tools."
    ),
    tools=[
        spanish_agent.as_tool(
            tool_name="translate_to_spanish",
            tool_description="Translate the user's message to Spanish",
        ),
        french_agent.as_tool(
            tool_name="translate_to_french",
            tool_description="Translate the user's message to French",
        ),
    ],
)

async def main():
    result = await Runner.run(orchestrator_agent, input="Say 'Hello, how are you?' in Spanish.")
    print(result.final_output)

自定义工具-代理

agent.as_tool 函数是一个方便的方法,可以轻松地将代理转换为工具。它不支持所有配置;例如,您无法设置 max_turns。对于高级用例,请直接在您的工具实现中使用 Runner.run

@function_tool
async def run_my_agent() -> str:
    """A tool that runs the agent with custom configs"""

    agent = Agent(name="My agent", instructions="...")

    result = await Runner.run(
        agent,
        input="...",
        max_turns=5,
        run_config=...
    )

    return str(result.final_output)

自定义输出提取

在某些情况下,您可能希望在将其返回给中心代理之前修改工具-代理的输出。这可能很有用,如果您想

  • 从子代理的聊天记录中提取特定信息(例如,JSON 有效负载)。
  • 转换或重新格式化代理的最终答案(例如,将 Markdown 转换为纯文本或 CSV)。
  • 验证输出或在代理的响应缺失或格式错误时提供回退值。

您可以通过将 custom_output_extractor 参数传递给 as_tool 方法来做到这一点

async def extract_json_payload(run_result: RunResult) -> str:
    # Scan the agent’s outputs in reverse order until we find a JSON-like message from a tool call.
    for item in reversed(run_result.new_items):
        if isinstance(item, ToolCallOutputItem) and item.output.strip().startswith("{"):
            return item.output.strip()
    # Fallback to an empty JSON object if nothing was found
    return "{}"


json_tool = data_agent.as_tool(
    tool_name="get_data_json",
    tool_description="Run the data agent and return only its JSON payload",
    custom_output_extractor=extract_json_payload,
)

流式嵌套代理运行

on_stream 回调传递给 as_tool 以侦听嵌套代理发出的流式事件,同时在流完成时返回其最终输出。

from agents import AgentToolStreamEvent


async def handle_stream(event: AgentToolStreamEvent) -> None:
    # Inspect the underlying StreamEvent along with agent metadata.
    print(f"[stream] {event['agent']['name']} :: {event['event'].type}")


billing_agent_tool = billing_agent.as_tool(
    tool_name="billing_helper",
    tool_description="Answer billing questions.",
    on_stream=handle_stream,  # Can be sync or async.
)

预期

  • 事件类型镜像 StreamEvent["type"]raw_response_eventrun_item_stream_eventagent_updated_stream_event
  • 提供 on_stream 会自动以流式模式运行嵌套代理,并在返回最终输出之前耗尽流。
  • 处理程序可以是同步的或异步的;每个事件都会按到达顺序传递。
  • 当工具通过模型工具调用被调用时,存在 tool_call_id;直接调用可能会将其留空 None
  • 有关完整的可运行示例,请参阅 examples/agent_patterns/agents_as_tools_streaming.py

条件工具启用

您可以使用 is_enabled 参数在运行时有条件地启用或禁用代理工具。这允许您根据上下文、用户偏好或运行时条件动态地过滤哪些工具可供 LLM 使用。

import asyncio
from agents import Agent, AgentBase, Runner, RunContextWrapper
from pydantic import BaseModel

class LanguageContext(BaseModel):
    language_preference: str = "french_spanish"

def french_enabled(ctx: RunContextWrapper[LanguageContext], agent: AgentBase) -> bool:
    """Enable French for French+Spanish preference."""
    return ctx.context.language_preference == "french_spanish"

# Create specialized agents
spanish_agent = Agent(
    name="spanish_agent",
    instructions="You respond in Spanish. Always reply to the user's question in Spanish.",
)

french_agent = Agent(
    name="french_agent",
    instructions="You respond in French. Always reply to the user's question in French.",
)

# Create orchestrator with conditional tools
orchestrator = Agent(
    name="orchestrator",
    instructions=(
        "You are a multilingual assistant. You use the tools given to you to respond to users. "
        "You must call ALL available tools to provide responses in different languages. "
        "You never respond in languages yourself, you always use the provided tools."
    ),
    tools=[
        spanish_agent.as_tool(
            tool_name="respond_spanish",
            tool_description="Respond to the user's question in Spanish",
            is_enabled=True,  # Always enabled
        ),
        french_agent.as_tool(
            tool_name="respond_french",
            tool_description="Respond to the user's question in French",
            is_enabled=french_enabled,
        ),
    ],
)

async def main():
    context = RunContextWrapper(LanguageContext(language_preference="french_spanish"))
    result = await Runner.run(orchestrator, "How are you?", context=context.context)
    print(result.final_output)

asyncio.run(main())

is_enabled 参数接受

  • 布尔值True(始终启用)或 False(始终禁用)
  • 可调用函数:接受 (context, agent) 并返回布尔值的函数
  • 异步函数:用于复杂条件逻辑的异步函数

禁用的工具在运行时完全隐藏在 LLM 之外,这使其适用于

  • 基于用户权限的功能门控
  • 特定于环境的工具可用性(开发与生产)
  • 不同工具配置的 A/B 测试
  • 基于运行时状态的动态工具过滤

处理函数工具中的错误

当您通过 @function_tool 创建函数工具时,您可以传递一个 failure_error_function。这是一个函数,它在工具调用崩溃时向 LLM 提供错误响应。

  • 默认情况下(即,如果您不传递任何内容),它会运行一个 default_tool_error_function,它会告诉 LLM 发生了错误。
  • 如果您传递自己的错误函数,它将运行该函数,并将响应发送给 LLM。
  • 如果您显式传递 None,那么任何工具调用错误都将被重新引发,供您处理。这可能是 ModelBehaviorError(如果模型生成了无效的 JSON),或者 UserError(如果您的代码崩溃),等等。
from agents import function_tool, RunContextWrapper
from typing import Any

def my_custom_error_function(context: RunContextWrapper[Any], error: Exception) -> str:
    """A custom function to provide a user-friendly error message."""
    print(f"A tool call failed with the following error: {error}")
    return "An internal server error occurred. Please try again later."

@function_tool(failure_error_function=my_custom_error_function)
def get_user_profile(user_id: str) -> str:
    """Fetches a user profile from a mock API.
     This function demonstrates a 'flaky' or failing API call.
    """
    if user_id == "user_123":
        return "User profile for user_123 successfully retrieved."
    else:
        raise ValueError(f"Could not retrieve profile for user_id: {user_id}. API returned an error.")

如果您手动创建 FunctionTool 对象,则必须在 on_invoke_tool 函数中处理错误。