Agent 架构
ReAct、function calling、多步规划。
35 分钟
Agent 架构
Agent 在 LLM 外再包一层 规划 → 行动 → 观察 循环,通过 function calling 连接检索、API、数据库。本课讲 ReAct、工具注册与多步规划——对应 ai-engineer 的 AI Agents 节点。入门直觉见 ai-agents-essentials。
学习目标
- 说清 Agent 循环与单次 Chat 的差异
- 设计 function calling schema 与执行沙箱
- 控制步数、成本与越权风险
ReAct 循环
Thought → Action(tool, args) → Observation → … → Final Answer
MAX_STEPS = 8
def run_agent(goal: str, llm, tools: dict):
context = [{"role": "user", "content": goal}]
for step in range(MAX_STEPS):
msg = llm.chat(context, tools=tool_schemas(tools))
if msg.tool_calls:
for call in msg.tool_calls:
obs = tools[call.name](**call.args) # 鉴权在 executor 内
context.append(tool_result(call.id, obs))
else:
return msg.content # 终止
return escalate_to_human(goal, context)
| 环节 | 工程要点 |
|---|---|
| 规划 | system 写子任务顺序;复杂目标先分解 |
| 行动 | 参数校验;超时;幂等 |
| 观察 | 截断过长 JSON;错误码原样返回 |
| 终止 | max_steps;用户确认;低置信 escalate |
Function Calling
工具定义示例:
SEARCH_DOCS = {
"name": "search_docs",
"description": "检索站内课程讲义,返回 title 与 excerpt",
"parameters": {
"type": "object",
"properties": {"query": {"type": "string"}, "top_k": {"type": "integer"}},
"required": ["query"],
},
}
模型只产出调用意图;真实 HTTP/DB 在 你控制的 executor 里跑。禁止把生产凭据塞进 prompt——见 ai-engineering-essentials 工具白名单。
多步规划模式
- ReAct:每步显式 reasoning(可关以省 token)
- Plan-and-Execute:先出计划 JSON,再逐步执行(适合长流程)
- RAG as tool:
search_docs返回片段,最终回答仍经 LLM 综合
失败模式:工具选错、参数幻觉、无限循环、过早结束。对策:few-shot 工具用法、dry-run、步数上限、关键步 人工批准。