跳至内容

工具

工具让代理能够执行操作:比如获取数据、运行代码、调用外部API,甚至使用计算机。Agent SDK中有三类工具:

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

托管工具

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

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. 如果存在文档字符串(Docstrings),则用于捕获描述和参数说明
  3. 函数可以选择性地接收context参数(必须是第一个参数)。您还可以设置覆盖项,比如工具名称、描述、使用哪种文档字符串风格等。
  4. 您可以将装饰后的函数传递给工具列表。
Expand to see output
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,这是一个异步函数,接收上下文和参数作为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模型、TypedDicts等。
  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)

处理函数工具中的错误

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

  • 默认情况下(即不传递任何参数时),它会运行一个default_tool_error_function函数,该函数会告知LLM发生了错误。
  • 如果您传递自定义的错误处理函数,系统将运行该函数而非默认处理,并将响应发送给LLM。
  • 如果您显式传递None,那么任何工具调用错误都将被重新抛出供您处理。这可能是模型生成无效JSON时产生的ModelBehaviorError,或是您的代码崩溃时产生的UserError等。

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