Agent 架构设计:从 Chatbot 到自主代理 🤖
"Agent 是能自主规划、执行和反思的 AI 系统。"
1. Agent vs Chatbot
1.1 核心区别
| 特性 | Chatbot | Agent |
|---|---|---|
| 交互模式 | 一问一答 | 自主多步执行 |
| 工具使用 | 可选 | 必须 |
| 规划能力 | 无 | 有 |
| 状态管理 | 简单 | 复杂 |
| 自我纠错 | 无 | 有 |
1.2 Agent 核心循环
Perceive (感知) → Plan (规划) → Act (行动) → Reflect (反思) → 循环2. ReAct 模式
2.1 什么是 ReAct
ReAct (Reasoning + Acting) 是最经典的 Agent 模式,让模型交替进行推理和行动。
用户: 帮我重构 UserList 组件,提取 hooks
思考: 我需要先看看 UserList 组件的当前实现
行动: read_file("src/components/UserList.tsx")
观察: [文件内容...]
思考: 可以提取为 useUserList hook
行动: write_file("src/hooks/useUserList.ts", "...")
观察: 文件创建成功
思考: 现在需要修改原组件使用新 hook
行动: edit_file("src/components/UserList.tsx", ...)
观察: 编辑成功
思考: 应该运行测试确保重构没有破坏功能
行动: run_terminal_cmd("npm test UserList")
观察: 所有测试通过
回答: 重构完成!2.2 ReAct Prompt 模板
markdown
你是一个能够使用工具完成任务的 AI 助手。
## 工作流程
对于每个任务,你需要交替进行"思考"和"行动":
1. **思考 (Thought)**: 分析当前情况,决定下一步
2. **行动 (Action)**: 调用工具执行操作
3. **观察 (Observation)**: 查看工具返回结果
4. 重复以上步骤直到任务完成
## 可用工具
- read_file(path): 读取文件
- write_file(path, content): 写入文件
- run_command(cmd): 执行命令
## 输出格式
Thought: [你的思考过程]
Action: [工具名称和参数]2.3 实现 ReAct Agent
javascript
import Anthropic from '@anthropic-ai/sdk';
class ReActAgent {
constructor(tools) {
this.anthropic = new Anthropic();
this.tools = tools;
this.maxIterations = 10;
}
async run(task) {
const messages = [{ role: 'user', content: task }];
for (let i = 0; i < this.maxIterations; i++) {
const response = await this.anthropic.messages.create({
model: 'claude-3-5-sonnet-20241022',
max_tokens: 4096,
messages,
tools: this.tools
});
// 检查是否需要调用工具
const toolUse = response.content.find(b => b.type === 'tool_use');
if (!toolUse) {
// 任务完成
return response.content.find(b => b.type === 'text')?.text;
}
// 执行工具
const result = await this.executeTool(toolUse.name, toolUse.input);
// 继续对话
messages.push({ role: 'assistant', content: response.content });
messages.push({
role: 'user',
content: [{
type: 'tool_result',
tool_use_id: toolUse.id,
content: JSON.stringify(result)
}]
});
}
throw new Error('Max iterations reached');
}
async executeTool(name, input) {
// 实现工具执行逻辑
switch (name) {
case 'read_file':
return await fs.readFile(input.path, 'utf-8');
case 'write_file':
await fs.writeFile(input.path, input.content);
return { success: true };
default:
throw new Error(`Unknown tool: ${name}`);
}
}
}3. Plan-and-Execute 模式
3.1 核心思想
先规划整体方案,再逐步执行。适合复杂、多步骤任务。
用户: 实现用户认证功能
规划阶段:
1. 创建 User 模型和数据库表
2. 实现注册 API
3. 实现登录 API (JWT)
4. 添加认证中间件
5. 编写测试
执行阶段:
[执行步骤 1] → [执行步骤 2] → ... → [完成]3.2 实现
javascript
class PlanAndExecuteAgent {
async run(task) {
// 1. 规划
const plan = await this.createPlan(task);
console.log('Plan:', plan);
// 2. 执行
const results = [];
for (const step of plan.steps) {
const result = await this.executeStep(step);
results.push(result);
// 检查是否需要调整计划
if (result.needsReplanning) {
plan = await this.replan(task, results);
}
}
return results;
}
async createPlan(task) {
const response = await this.llm.chat({
messages: [{
role: 'user',
content: `创建执行计划:\n${task}\n\n返回 JSON 格式: { steps: [{ description, tools }] }`
}]
});
return JSON.parse(response.content);
}
async executeStep(step) {
const response = await this.llm.chat({
messages: [{
role: 'user',
content: `执行步骤: ${step.description}`
}],
tools: step.tools
});
// 执行工具调用...
return { success: true, output: response };
}
}4. Reflexion 模式
4.1 自我反思
Agent 执行任务后,反思结果并改进。
执行 → 评估 → 反思 → 改进 → 重新执行4.2 实现
javascript
class ReflexionAgent {
async run(task, maxAttempts = 3) {
let attempt = 0;
let result = null;
let reflections = [];
while (attempt < maxAttempts) {
// 执行任务
result = await this.execute(task, reflections);
// 评估结果
const evaluation = await this.evaluate(task, result);
if (evaluation.success) {
return result;
}
// 反思
const reflection = await this.reflect(task, result, evaluation);
reflections.push(reflection);
attempt++;
}
throw new Error('Failed after max attempts');
}
async execute(task, reflections) {
const context = reflections.length > 0
? `之前的尝试和反思:\n${reflections.join('\n\n')}`
: '';
const response = await this.llm.chat({
messages: [{
role: 'user',
content: `${context}\n\n任务: ${task}`
}],
tools: this.tools
});
return response;
}
async evaluate(task, result) {
const response = await this.llm.chat({
messages: [{
role: 'user',
content: `评估以下结果是否完成任务:\n任务: ${task}\n结果: ${result}\n\n返回 JSON: { success: boolean, issues: string[] }`
}]
});
return JSON.parse(response.content);
}
async reflect(task, result, evaluation) {
const response = await this.llm.chat({
messages: [{
role: 'user',
content: `反思失败原因并提出改进建议:\n任务: ${task}\n结果: ${result}\n问题: ${evaluation.issues.join(', ')}`
}]
});
return response.content;
}
}5. 多 Agent 协作
5.1 专业化 Agent
javascript
// 研究 Agent
const researchAgent = new Agent({
name: 'Researcher',
instructions: 'You gather information and provide summaries.',
tools: [searchTool, readDocTool]
});
// 编码 Agent
const codingAgent = new Agent({
name: 'Coder',
instructions: 'You write and refactor code.',
tools: [readFileTool, writeFileTool, runTestTool]
});
// 审查 Agent
const reviewAgent = new Agent({
name: 'Reviewer',
instructions: 'You review code for quality and security.',
tools: [readFileTool, lintTool]
});5.2 协调器模式
javascript
class CoordinatorAgent {
constructor(agents) {
this.agents = agents;
}
async run(task) {
// 1. 分析任务,决定需要哪些 Agent
const plan = await this.analyzeTas...[truncated 2653 chars]