LESSON · 06

让 LLM
自己
干活

Agent · 智能体的核心范式与典型框架。

Agent =
LLM
+ 工具

+ 记忆 + 规划 + 循环。

四件套

  • 大脑:LLM 决策与规划
  • 工具:调用外部 API、执行代码、读写文件
  • 记忆:短期对话 + 长期向量化
  • 循环:观察 → 思考 → 行动 → 再观察

🎮 ReAct 循环播放器

Q
T
A
O
T
✓

Tool Use · 工具调用

  • Function Calling:模型输出结构化函数调用
  • JSON Schema:声明工具的入参类型
  • 多工具并行:现代模型支持一次调多个
  • 工具数:建议 ≤ 20,太多会"选困难"

function calling


{
  "name": "search_doc",
  "description": "在公司知识库里检索文档",
  "parameters": {
    "type": "object",
    "properties": {
      "query": { "type": "string", "description": "搜索关键词" },
      "top_k": { "type": "integer", "default": 5 }
    },
    "required": ["query"]
  }
}

function calling 完整代码


from openai import OpenAI
client = OpenAI()

tools = [{"type": "function", "function": {
    "name": "get_weather",
    "description": "查询城市天气",
    "parameters": {"type": "object", "properties": {
        "city": {"type": "string"}
    }, "required": ["city"]}
}}]

resp = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "杭州天气如何?"}],
    tools=tools
)

# 解析 tool_calls
tool_call = resp.choices[0].message.tool_calls[0]
print(f"调用: {tool_call.function.name}({tool_call.function.arguments})")

记忆系统

  • 短期:当前对话窗口(messages 数组)
  • 长期:向量化存储 + 检索(RAG 思路)
  • 结构化:用户 profile / 偏好 / 实体记忆
  • 遗忘:定期摘要、淘汰冷数据

规划
能力

从"边走边想"到"先想再走"。

规划方法

  • Plan-and-Execute:先列计划,再逐步执行
  • Tree of Thoughts:探索多分支,回溯最优
  • ReWOO:先规划全部步骤再执行,省 token
  • Reflection:自我反思修正

多 Agent 协作

  • 角色分工:PM / Coder / Reviewer / Tester
  • 辩论:多方观点提升决策质量
  • 流水线:上一个的输出 = 下一个的输入
  • 层级:Lead Agent 调度 Sub Agent

MCP
协议

Anthropic 推的"Agent 工具的 USB-C"。

MCP 是什么

  • Model Context Protocol
  • 统一 LLM 与外部工具/资源/服务的接口标准
  • 写一次 MCP server,所有支持的客户端都能用
  • 类比:LSP 之于编辑器
  • → 工具生态的基础设施

最小 MCP Server


# pip install mcp
from mcp.server.fastmcp import FastMCP

mcp = FastMCP("demo")

@mcp.tool()
def add(a: int, b: int) -> int:
    """两数相加"""
    return a + b

mcp.run()  # stdio 模式启动

框架选型决策表

  • LangGraph · 状态机驱动,控制力最强 · 复杂流程 · 学习曲线中
  • CrewAI · 多角色协作,分工明确 · 多 Agent · 学习曲线低
  • OpenAI Agents SDK · 官方出品,极简 API · 2025 新,生态建设中
  • Autogen · 微软出品,适合研究探索 · 重量级

失败模式

  • 死循环:相同的工具反复调用
  • 幻觉决策:编造工具名 / 参数
  • 成本失控:单任务 100 美刀的故事很多
  • 过度自信:不该用工具时也用
  • → 必须设:步数上限、成本上限、超时

实战场景

  • 编码 Agent:Cursor / Claude Code / Devin
  • 浏览器 Agent:Manus / Browser Use
  • 数据分析:Code Interpreter
  • 客服:FAQ + RAG + 工具串联

本课收获

ReAct 循环 Function Calling 记忆与规划 MCP 多 Agent 失败模式

下一课 · 微调与训练:什么时候该微调?