Agent与工具调用
LLM 的能力不止于对话——通过 Agent 架构和工具调用,LLM 可以执行搜索、写代码、操作数据库,成为真正的"智能助手"。
Agent 架构概览
graph TB
A[用户请求] --> B[LLM Agent]
B --> C{需要工具?}
C -->|是| D[选择工具]
D --> E[执行工具]
E --> F[返回结果]
F --> B
C -->|否| G[直接回答]
D --> D1[搜索]
D --> D2[计算]
D --> D3[代码执行]
D --> D4[API 调用]
style B fill:#e3f2fd,stroke:#1565c0,stroke-width:2px
style D fill:#fff9c4,stroke:#f9a825,stroke-width:2px
工具调用框架
from dataclasses import dataclass, field
from typing import Any
@dataclass
class Tool:
"""工具定义"""
name: str
description: str
parameters: dict[str, str] # 参数名 → 类型描述
def to_schema(self) -> dict:
"""转换为 OpenAI Function Calling 格式"""
return {
"type": "function",
"function": {
"name": self.name,
"description": self.description,
"parameters": {
"type": "object",
"properties": {
name: {"type": ptype, "description": name}
for name, ptype in self.parameters.items()
},
"required": list(self.parameters.keys()),
},
},
}
@dataclass
class ToolResult:
tool_name: str
success: bool
result: Any
error: str = ""
class SimpleAgent:
"""简易 Agent 框架"""
def __init__(self):
self.tools: dict[str, Tool] = {}
self.tool_handlers: dict[str, callable] = {}
self.history: list[dict] = []
def register_tool(
self, tool: Tool, handler: callable
) -> None:
self.tools[tool.name] = tool
self.tool_handlers[tool.name] = handler
def execute_tool(
self, tool_name: str, **kwargs
) -> ToolResult:
"""执行工具调用"""
if tool_name not in self.tool_handlers:
return ToolResult(tool_name, False, None, f"工具 {tool_name} 不存在")
try:
result = self.tool_handlers[tool_name](**kwargs)
return ToolResult(tool_name, True, result)
except Exception as e:
return ToolResult(tool_name, False, None, str(e))
def get_tool_schemas(self) -> list[dict]:
"""获取所有工具的 schema(传给 LLM)"""
return [t.to_schema() for t in self.tools.values()]
def think_and_act(self, user_input: str) -> str:
"""Agent 循环:思考 → 行动 → 观察"""
self.history.append({"role": "user", "content": user_input})
# 简化模拟:基于关键词选择工具
tool_name = self._select_tool(user_input)
if tool_name:
result = self.execute_tool(tool_name, query=user_input)
self.history.append({
"role": "tool",
"tool": tool_name,
"result": str(result.result),
})
return f"[调用 {tool_name}] {result.result}"
return f"[直接回答] 处理: {user_input}"
def _select_tool(self, query: str) -> str | None:
"""简单的工具选择逻辑"""
keywords = {
"calculate": "计算",
"search": "搜索",
"weather": "天气",
}
for tool_name, keyword in keywords.items():
if keyword in query or tool_name in query.lower():
if tool_name in self.tools:
return tool_name
return None
# 注册工具
agent = SimpleAgent()
# 计算工具
calc_tool = Tool(
"calculate", "执行数学计算",
{"expression": "string"}
)
agent.register_tool(calc_tool, lambda query: f"计算结果模拟: {query}")
# 搜索工具
search_tool = Tool(
"search", "搜索互联网信息",
{"query": "string"}
)
agent.register_tool(search_tool, lambda query: f"搜索结果模拟: {query}")
# 测试
print(agent.think_and_act("帮我计算 15 × 28"))
print(agent.think_and_act("搜索今天的新闻"))
print(agent.think_and_act("你好"))
Agent 框架对比
| 框架 | 语言 | 特点 | 适合场景 | 学习曲线 |
|---|---|---|---|---|
| LangChain | Python | 生态丰富,链式组合 | 通用 Agent | 中 |
| LlamaIndex | Python | 数据连接强 | RAG + Agent | 中 |
| AutoGen | Python | 多 Agent 协作 | 复杂推理 | 高 |
| CrewAI | Python | 角色扮演 Agent | 团队协作模拟 | 低 |
| Semantic Kernel | C#/Python | 微软生态 | 企业集成 | 中 |
ReAct 模式
graph LR
A[思考 Reason] --> B[行动 Act]
B --> C[观察 Observe]
C --> A
A1["我需要查找天气信息"] --> A
B1["调用 weather API"] --> B
C1["返回: 晴天 28°C"] --> C
style A fill:#e3f2fd,stroke:#1565c0,stroke-width:2px
style B fill:#fff9c4,stroke:#f9a825,stroke-width:2px
style C fill:#c8e6c9,stroke:#43a047,stroke-width:2px
| Agent 范式 | 核心思路 | 优点 | 缺点 |
|---|---|---|---|
| ReAct | 思考-行动-观察循环 | 可解释性强 | 步骤多,延迟高 |
| Function Calling | LLM 输出结构化工具调用 | 简单直接 | 依赖模型能力 |
| Plan & Execute | 先规划再执行 | 复杂任务好 | 规划可能出错 |
| Multi-Agent | 多个 Agent 协作 | 分工明确 | 通信成本高 |
本章小结
- Agent = LLM + 工具 + 循环——不止是对话,可以执行真实操作
- Function Calling 是基础——OpenAI 格式已成为事实标准
- ReAct 最常用——思考→行动→观察,循环直到完成
- 框架选型——简单用 LangChain,RAG 用 LlamaIndex,多 Agent 用 AutoGen
- 安全第一——Agent 有执行能力,必须限制权限范围
下一章:RAG 入门