首页 教程 常见问题

13.7 Agent SDK 自定义工具

为 Agent SDK 代理创建自定义工具——让 Claude 能操作你的系统和数据。

工具定义

工具是代理可以调用的函数。每个工具需要定义:

创建工具

Python 示例

tools = [
    {
        "name": "search_database",
        "description": "搜索数据库中的用户记录",
        "input_schema": {
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "搜索关键词"
                },
                "limit": {
                    "type": "integer",
                    "description": "返回结果的最大数量",
                    "default": 10
                }
            },
            "required": ["query"]
        }
    }
]

def execute_tool(tool_name, **kwargs):
    if tool_name == "search_database":
        return search_db(kwargs["query"], kwargs.get("limit", 10))
    # ...其他工具

def search_db(query, limit):
    # 实现数据库搜索
    return f"找到 {limit} 条关于 '{query}' 的记录"

Node.js 示例

const tools = [
  {
    name: "search_database",
    description: "搜索数据库中的用户记录",
    input_schema: {
      type: "object",
      properties: {
        query: {
          type: "string",
          description: "搜索关键词"
        },
        limit: {
          type: "integer",
          description: "返回结果的最大数量",
          default: 10
        }
      },
      required: ["query"]
    }
  }
];

处理工具调用

def handle_tool_calls(content):
    """处理代理返回的工具调用。"""
    results = []
    for item in content:
        if item.type == "tool_use":
            tool_name = item.name
            tool_input = item.input
            tool_id = item.id

            # 执行工具
            result = execute_tool(tool_name, **tool_input)

            results.append({
                "type": "tool_result",
                "tool_use_id": tool_id,
                "content": str(result)
            })

    return results

工具设计原则

示例:文件系统工具

import os
import glob

file_tools = [
    {
        "name": "list_files",
        "description": "列出目录中的文件",
        "input_schema": {
            "type": "object",
            "properties": {
                "path": {"type": "string", "description": "目录路径"},
                "pattern": {"type": "string", "description": "文件匹配模式,如 *.py"}
            },
            "required": ["path"]
        }
    }
]

def execute_file_tool(name, **kwargs):
    if name == "list_files":
        path = kwargs["path"]
        pattern = kwargs.get("pattern", "*")
        files = glob.glob(os.path.join(path, pattern))
        return "\n".join(files)
    return "未知工具"

下一步