Agent工具生态:打通AI与外部世界
AI · 技术

Agent工具生态:打通AI与外部世界

模块 05:工具生态

AI Agent 的「双手」—— 通过工具调用,Agent 从"只会说"变成"能做事"

1. 为什么需要工具

LLM 本身有明显局限:

无工具的 LLM:
  ✗ 不能获取实时信息(训练数据有截止日期)
  ✗ 不能执行计算(数学推理容易出错)
  ✗ 不能操作外部系统(发邮件、写数据库)
  ✗ 不能访问私有数据(内部文档、用户数据)

有工具的 Agent:
  ✓ 调用搜索工具 → 获取最新信息
  ✓ 调用计算器 → 精确计算
  ✓ 调用 API → 操作外部系统
  ✓ 调用数据库 → 访问私有数据

2. Function Calling 机制

2.1 工作原理

用户:"北京今天天气怎么样?"
        │
        ▼
┌───────────────────┐
│  LLM 分析用户意图   │
│  识别需要调用工具    │
└────────┬──────────┘
         │
         ▼
┌───────────────────┐
│  LLM 输出工具调用   │
│  name: get_weather │
│  args: {city: 北京} │
└────────┬──────────┘
         │
         ▼
┌───────────────────┐
│  Agent 执行工具     │
│  调用天气 API      │
└────────┬──────────┘
         │
         ▼
┌───────────────────┐
│  获取结果并返回     │
│  晴,28°C          │
└────────┬──────────┘
         │
         ▼
┌───────────────────┐
│  LLM 生成最终回答   │
│  "北京今天晴..."    │
└───────────────────┘

2.2 工具定义格式

# OpenAI 格式
tool_definition = {
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "获取指定城市的当前天气信息",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {
                    "type": "string",
                    "description": "城市名称,如'北京'、'上海'"
                },
                "unit": {
                    "type": "string",
                    "enum": ["celsius", "fahrenheit"],
                    "description": "温度单位,默认摄氏度"
                }
            },
            "required": ["city"]
        }
    }
}

# Anthropic 格式
tool_definition = {
    "name": "get_weather",
    "description": "获取指定城市的当前天气信息",
    "input_schema": {
        "type": "object",
        "properties": {
            "city": {
                "type": "string",
                "description": "城市名称"
            },
            "unit": {
                "type": "string",
                "enum": ["celsius", "fahrenheit"]
            }
        },
        "required": ["city"]
    }
}

2.3 工具调用代码

# OpenAI Function Calling
from openai import OpenAI
import json

client = OpenAI()

tools = [tool_definition]

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "北京天气怎么样?"}],
    tools=tools,
    tool_choice="auto"  # auto / none / required
)

message = response.choices[0].message

# 检查是否需要调用工具
if message.tool_calls:
    for call in message.tool_calls:
        func_name = call.function.name
        func_args = json.loads(call.function.arguments)

        # 执行工具
        result = execute_tool(func_name, func_args)

        # 将结果返回给 LLM
        messages.append(message)
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result)
        })

    # 获取最终回答
    final = client.chat.completions.create(
        model="gpt-4o",
        messages=messages,
        tools=tools
    )
    print(final.choices[0].message.content)
# Anthropic Tool Use
import anthropic

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=1024,
    tools=[tool_definition],
    messages=[{"role": "user", "content": "北京天气怎么样?"}]
)

# 检查是否需要调用工具
if message.stop_reason == "tool_use":
    for block in message.content:
        if block.type == "tool_use":
            result = execute_tool(block.name, block.input)

            # 将结果返回
            response = client.messages.create(
                model="claude-sonnet-4-20250514",
                max_tokens=1024,
                tools=[tool_definition],
                messages=[
                    {"role": "user", "content": "北京天气怎么样?"},
                    {"role": "assistant", "content": message.content},
                    {
                        "role": "user",
                        "content": [{
                            "type": "tool_result",
                            "tool_use_id": block.id,
                            "content": json.dumps(result)
                        }]
                    }
                ]
            )
            print(response.content[0].text)

3. 常见工具类型

3.1 信息检索工具

# Web Search
class WebSearchTool:
    name = "web_search"
    description = "搜索互联网获取最新信息"

    async def execute(self, query: str, max_results: int = 5) -> str:
        # 使用搜索 API
        results = await search_api(query, max_results)
        return format_results(results)

# Database Query
class DatabaseQueryTool:
    name = "query_database"
    description = "查询数据库获取数据"

    async def execute(self, sql: str) -> str:
        # 安全检查:只允许 SELECT
        if not sql.strip().upper().startswith("SELECT"):
            return "Error: 只允许 SELECT 查询"
        results = await db.execute(sql)
        return format_as_table(results)

# File Read
class FileReadTool:
    name = "read_file"
    description = "读取文件内容"

    async def execute(self, file_path: str) -> str:
        # 路径安全检查
        if not is_safe_path(file_path):
            return "Error: 不允许访问该路径"
        with open(file_path) as f:
            return f.read()

3.2 计算工具

# Calculator
class CalculatorTool:
    name = "calculate"
    description = "执行数学计算"

    async def execute(self, expression: str) -> str:
        try:
            # 安全的数学计算(不使用 eval)
            result = safe_eval(expression)
            return str(result)
        except Exception as e:
            return f"计算错误: {e}"

# Python Code Execution
class PythonExecutorTool:
    name = "run_python"
    description = "执行 Python 代码并返回结果"

    async def execute(self, code: str) -> str:
        # 在沙箱中执行
        result = await sandbox_execute(code, timeout=30)
        return result.stdout + result.stderr

3.3 外部 API 工具

# Email Sender
class SendEmailTool:
    name = "send_email"
    description = "发送邮件"

    async def execute(self, to: str, subject: str, body: str) -> str:
        await email_client.send(to=to, subject=subject, body=body)
        return f"邮件已发送至 {to}"

# HTTP Request
class HttpRequestTool:
    name = "http_request"
    description = "发送 HTTP 请求"

    async def execute(self, url: str, method: str = "GET", body: str = None) -> str:
        async with httpx.AsyncClient() as client:
            response = await client.request(method, url, content=body)
            return response.text[:2000]  # 限制返回长度

3.4 文件操作工具

# File Write
class FileWriteTool:
    name = "write_file"
    description = "写入文件"

    async def execute(self, file_path: str, content: str) -> str:
        if not is_safe_path(file_path):
            return "Error: 不允许写入该路径"
        with open(file_path, 'w') as f:
            f.write(content)
        return f"文件已写入: {file_path}"

# File List
class FileListTool:
    name = "list_files"
    description = "列出目录中的文件"

    async def execute(self, directory: str = ".") -> str:
        files = os.listdir(directory)
        return "\n".join(files)

4. MCP(Model Context Protocol)

4.1 什么是 MCP

MCP 是 Anthropic 提出的开放标准,为 LLM 提供统一的工具和数据源接入协议。

传统方式(每个工具单独集成):
  LLM ←→ 工具A(自定义接口)
  LLM ←→ 工具B(自定义接口)
  LLM ←→ 工具C(自定义接口)

MCP 方式(统一协议):
  LLM ←→ MCP Client ←→ MCP Server A(工具A)
                      ←→ MCP Server B(工具B)
                      ←→ MCP Server C(工具C)

4.2 MCP 核心能力

MCP Server
├── Tools(工具)
│   ├── 可调用的函数
│   ├── 带参数 Schema
│   └── 返回结构化结果
│
├── Resources(资源)
│   ├── URI 寻址的数据源
│   ├── 文件、数据库、API
│   └── 动态资源列表
│
├── Prompts(提示模板)
│   ├── 预定义的提示模板
│   ├── 参数化
│   └── 可复用的提示
│
└── Sampling(采样)
    ├── Server 请求 LLM 推理
    └── Human-in-the-loop 审批

4.3 MCP Server 开发(Python)

from mcp.server import Server
from mcp.types import Tool, TextContent
import mcp.server.stdio

server = Server("my-agent-tools")

# 定义工具
@server.tool()
async def get_weather(city: str) -> str:
    """获取指定城市的天气信息"""
    result = await weather_api.get(city)
    return f"{city}今天{result.condition},气温{result.temp}°C"

@server.tool()
async def search_web(query: str, max_results: int = 5) -> str:
    """搜索互联网"""
    results = await search_api(query, max_results)
    return format_results(results)

# 定义资源
@server.resource("file://documents/{path}")
async def get_document(path: str) -> str:
    """读取文档内容"""
    with open(f"documents/{path}") as f:
        return f.read()

# 运行
async def main():
    async with mcp.server.stdio.stdio_server() as (read, write):
        await server.run(read, write, server.create_initialization_options())

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

4.4 MCP Server 开发(TypeScript)

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

const server = new Server(
  { name: "my-tools", version: "1.0.0" },
  { capabilities: { tools: {}, resources: {} } }
);

// 定义工具列表
server.setRequestHandler("tools/list", async () => ({
  tools: [
    {
      name: "get_weather",
      description: "获取天气信息",
      inputSchema: {
        type: "object",
        properties: {
          city: { type: "string", description: "城市名称" }
        },
        required: ["city"]
      }
    }
  ]
}));

// 处理工具调用
server.setRequestHandler("tools/call", async (request) => {
  const { name, arguments: args } = request.params;

  if (name === "get_weather") {
    const result = await getWeather(args.city);
    return { content: [{ type: "text", text: result }] };
  }

  throw new Error(`Unknown tool: ${name}`);
});

// 启动
const transport = new StdioServerTransport();
await server.connect(transport);

4.5 MCP 配置

// claude_desktop_config.json
{
  "mcpServers": {
    "weather": {
      "command": "python",
      "args": ["mcp_servers/weather_server.py"],
      "env": { "WEATHER_API_KEY": "xxx" }
    },
    "database": {
      "command": "node",
      "args": ["mcp_servers/db_server.js"],
      "env": { "DB_URL": "postgresql://..." }
    }
  }
}

5. 工具设计最佳实践

5.1 工具描述要清晰

# 差的描述
{
    "name": "search",
    "description": "搜索",
    "parameters": {
        "properties": {"q": {"type": "string"}}
    }
}

# 好的描述
{
    "name": "web_search",
    "description": "在互联网上搜索信息,返回与查询相关的网页摘要。适用于获取最新信息、查找事实、研究特定主题。不适用于内部数据查询或需要登录的网站。",
    "parameters": {
        "properties": {
            "query": {
                "type": "string",
                "description": "搜索关键词,建议使用简洁明确的关键词"
            },
            "max_results": {
                "type": "integer",
                "description": "返回结果数量,默认5,最大20",
                "default": 5
            }
        },
        "required": ["query"]
    }
}

5.2 参数设计原则

# 1. 使用清晰的参数名
"city"          # 好
"c"             # 差

# 2. 提供默认值
"max_results": {"type": "integer", "default": 5}

# 3. 使用枚举限制取值范围
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}

# 4. 添加参数验证
"email": {"type": "string", "format": "email"}
"age": {"type": "integer", "minimum": 0, "maximum": 150}

# 5. 限制输入长度
"query": {"type": "string", "maxLength": 500}

5.3 错误处理

class Tool:
    async def safe_execute(self, **kwargs) -> str:
        """安全执行工具,带完整错误处理"""
        try:
            # 1. 参数验证
            validated = self.validate_params(kwargs)

            # 2. 权限检查
            if not self.check_permission(validated):
                return "Error: 没有权限执行此操作"

            # 3. 执行(带超时)
            result = await asyncio.wait_for(
                self.execute(**validated),
                timeout=30
            )

            # 4. 结果验证
            if not self.validate_output(result):
                return "Error: 工具返回了无效结果"

            return result

        except asyncio.TimeoutError:
            return f"Error: 工具 {self.name} 执行超时"
        except ValidationError as e:
            return f"Error: 参数验证失败 - {e}"
        except Exception as e:
            return f"Error: 工具执行失败 - {str(e)}"

5.4 安全原则

1. 最小权限:工具只暴露必要的能力
2. 输入验证:严格验证所有参数
3. 输出过滤:检查返回内容是否安全
4. 沙箱执行:危险操作在隔离环境中执行
5. 审计日志:记录所有工具调用
6. 速率限制:防止工具被滥用
7. 确认机制:敏感操作需要用户确认

6. 工具注册与发现

6.1 装饰器模式

# 使用装饰器注册工具
from functools import wraps

def tool(name: str, description: str):
    """工具注册装饰器"""
    def decorator(func):
        @wraps(func)
        async def wrapper(*args, **kwargs):
            return await func(*args, **kwargs)

        wrapper._tool_meta = {
            "name": name,
            "description": description,
            "parameters": generate_schema(func)
        }
        return wrapper
    return decorator

@tool("get_weather", "获取天气信息")
async def get_weather(city: str) -> str:
    return await weather_api.get(city)

@tool("calculate", "计算数学表达式")
async def calculate(expression: str) -> str:
    return str(safe_eval(expression))

# 自动收集所有注册的工具
def collect_tools() -> list[dict]:
    tools = []
    for name, obj in globals().items():
        if hasattr(obj, "_tool_meta"):
            tools.append(obj._tool_meta)
    return tools

6.2 工具目录

class ToolRegistry:
    """工具注册中心"""

    def __init__(self):
        self.tools: dict[str, Tool] = {}

    def register(self, tool: Tool):
        self.tools[tool.name] = tool

    def get(self, name: str) -> Tool | None:
        return self.tools.get(name)

    def list_tools(self) -> list[dict]:
        return [
            {
                "name": t.name,
                "description": t.description,
                "parameters": t.parameters
            }
            for t in self.tools.values()
        ]

    def get_tools_for_llm(self) -> list[dict]:
        """获取 LLM 格式的工具定义"""
        return [t.to_llm_format() for t in self.tools.values()]

7. 并行工具调用

async def execute_tools_parallel(tool_calls: list[dict]) -> list[str]:
    """并行执行多个工具调用"""
    tasks = []
    for call in tool_calls:
        tool = registry.get(call["name"])
        if tool:
            tasks.append(tool.safe_execute(**call["arguments"]))

    # 并行执行所有工具
    results = await asyncio.gather(*tasks, return_exceptions=True)

    # 处理异常
    formatted = []
    for i, result in enumerate(results):
        if isinstance(result, Exception):
            formatted.append(f"Error: {str(result)}")
        else:
            formatted.append(result)

    return formatted

8. 常见工具集成

8.1 搜索引擎

# Tavily Search(专为 AI Agent 设计)
from tavily import TavilyClient

client = TavilyClient(api_key="tvly-...")

async def search(query: str) -> str:
    result = client.search(query, max_results=5)
    return "\n".join(
        f"- {r['title']}: {r['content'][:200]}"
        for r in result["results"]
    )

# SerpAPI
from serpapi import GoogleSearch

async def search_google(query: str) -> str:
    params = {"q": query, "api_key": "your-key"}
    results = GoogleSearch(params).get_dict()
    return format_results(results["organic_results"])

8.2 浏览器控制

# Playwright
from playwright.async_api import async_playwright

class BrowserTool:
    async def navigate(self, url: str) -> str:
        async with async_playwright() as p:
            browser = await p.chromium.launch()
            page = await browser.new_page()
            await page.goto(url)
            content = await page.content()
            await browser.close()
            return content[:5000]

    async def screenshot(self, url: str) -> bytes:
        async with async_playwright() as p:
            browser = await p.chromium.launch()
            page = await browser.new_page()
            await page.goto(url)
            screenshot = await page.screenshot()
            await browser.close()
            return screenshot

8.3 代码执行

# 安全的代码执行沙箱
import subprocess
import tempfile

class CodeExecutionTool:
    async def execute_python(self, code: str, timeout: int = 30) -> str:
        """在沙箱中执行 Python 代码"""
        with tempfile.NamedTemporaryFile(suffix=".py", mode="w") as f:
            f.write(code)
            f.flush()

            try:
                result = subprocess.run(
                    ["python", f.name],
                    capture_output=True,
                    text=True,
                    timeout=timeout,
                    cwd="/tmp"  # 限制工作目录
                )
                return result.stdout + result.stderr
            except subprocess.TimeoutExpired:
                return "Error: 代码执行超时"

9. 延伸阅读


小码提示: 工具是 Agent 能力的边界。好的工具设计应该:描述清晰、参数简洁、错误明确、安全可控。先从 3-5 个核心工具开始,验证 Agent 调用效果后再逐步扩展。

10. 动态工具加载

10.1 概念

静态工具注册在启动时固定,动态工具加载允许运行时按需加载/卸载工具。

class DynamicToolRegistry:
    """动态工具注册中心"""

    def __init__(self):
        self.tools: dict[str, Tool] = {}
        self.tool_sources: dict[str, callable] = {}  # 工具来源(懒加载)

    def register_source(self, source_name: str, loader: callable):
        """注册工具来源(不立即加载)"""
        self.tool_sources[source_name] = loader

    async def load_tools_for_query(self, query: str, llm) -> list[dict]:
        """根据查询动态加载相关工具"""
        # 1. 让 LLM 判断需要哪些工具来源
        available_sources = list(self.tool_sources.keys())
        prompt = f"根据问题选择需要的工具来源:{available_sources}\n问题:{query}"
        selected = await llm.chat(prompt)

        # 2. 懒加载选中的工具来源
        for source in parse_list(selected):
            if source not in self.tools:
                tools = await self.tool_sources[source]()
                for tool in tools:
                    self.tools[tool.name] = tool

        # 3. 返回可用工具列表
        return [t.to_llm_format() for t in self.tools.values()]

10.2 MCP 动态发现

class MCPDynamicLoader:
    """从 MCP Server 动态发现工具"""

    async def discover_tools(self, server_url: str) -> list[dict]:
        """连接 MCP Server 并发现可用工具"""
        async with MCPClient(server_url) as client:
            tools = await client.list_tools()
            return [
                {
                    "name": t.name,
                    "description": t.description,
                    "parameters": t.inputSchema,
                    "source": server_url
                }
                for t in tools
            ]

11. A2A(Agent-to-Agent)协议

11.1 什么是 A2A

A2A 是 Google 在 2025 年提出的开放协议,用于不同 Agent 之间的互操作。

MCP:Agent ↔ 工具/数据源(垂直集成)
A2A:Agent ↔ Agent(水平协作)

区别:
  MCP 解决的是"Agent 如何使用工具"
  A2A 解决的是"Agent 如何发现和协作其他 Agent"

11.2 A2A 核心概念

# Agent Card:描述 Agent 能力的元数据
agent_card = {
    "name": "research-agent",
    "description": "擅长信息检索和分析",
    "capabilities": ["web_search", "paper_analysis", "summarization"],
    "endpoint": "https://research-agent.example.com/a2a",
    "authentication": {"type": "api_key"},
    "pricing": {"model": "per_task", "cost": 0.01}
}

# Task:Agent 间传递的任务
task = {
    "id": "task-123",
    "input": {"query": "AI Agent 最新进展"},
    "context": {"caller": "main-agent"},
    "expected_output": {"format": "markdown"}
}

# A2A 通信流程
# 1. 发现:Agent A 通过 Agent Card 发现 Agent B
# 2. 委派:Agent A 向 Agent B 发送 Task
# 3. 执行:Agent B 执行任务
# 4. 返回:Agent B 返回结果给 Agent A

11.3 A2A vs MCP

维度 MCP A2A
目的 Agent 使用工具 Agent 间协作
通信 请求-响应 任务委派
发现 配置文件 Agent Card
标准化 Anthropic 主导 Google 主导
成熟度 已广泛使用 早期阶段

12. 工具版本管理

class VersionedToolRegistry:
    """支持版本管理的工具注册中心"""

    def __init__(self):
        self.tools: dict[str, dict[str, Tool]] = {}  # name -> {version -> Tool}

    def register(self, tool: Tool, version: str = "latest"):
        if tool.name not in self.tools:
            self.tools[tool.name] = {}
        self.tools[tool.name][version] = tool

    def get(self, name: str, version: str = "latest") -> Tool:
        versions = self.tools.get(name, {})
        if version == "latest":
            return list(versions.values())[-1]  # 最新版本
        return versions.get(version)

    def list_versions(self, name: str) -> list[str]:
        return list(self.tools.get(name, {}).keys())

    def deprecate(self, name: str, version: str):
        """标记工具版本为已废弃"""
        tool = self.tools[name][version]
        tool.deprecated = True
        tool.deprecation_message = f"请使用 {name} 的最新版本"