Agent 开发实战案例与 Demo
本文提供完整的可运行代码示例,帮助开发者快速掌握 Agent 开发的实际应用。涵盖小说创作、问答系统、多 Agent 协作等多个实战场景。
目录
- 引言
- 一、实战案例一:小说创作 Agent(ReAct 模式)
- 二、实战案例二:问答 Agent(CoT 模式)
- 三、实战案例三:多 Agent 协作(Swarm)
- 四、实战案例四:简单 ReAct Agent(可立即运行)
- 总结与对比
引言
在掌握了 Agent 开发的理论框架和推理模式后,最重要的就是动手实践。本文提供 4 个完整的实战案例,从简单的问答系统到复杂的小说创作 Agent,帮助读者深入理解 Agent 的实际应用。
每个案例都包含:
- ✅ 完整的源代码
- ✅ 详细的使用说明
- ✅ 实际运行输出示例
- ✅ 关键技术点解析
一、实战案例一:小说创作 Agent(ReAct 模式)
1.1 项目概述
这是一个完整的小说创作 Agent,使用 ReAct 模式结合 Reflexion 自我反思,能够自主完成从世界观构建到角色设计再到章节撰写的全流程。
技术栈:
- 框架:OpenClaw
- 模式:ReAct + Reflexion
- 语言:JavaScript (Node.js)
功能特点:
- 🎬 自动构建世界观
- 👥 智能角色设计
- 📝 章节自动撰写
- 🔄 自我反思与改进
- 💾 自动保存和导出
1.2 项目结构
novel-agent/
├── config/
│ └── settings.json # 配置文件
├── src/
│ ├── agent.js # 主 Agent
│ ├── tools/
│ │ ├── world-builder.js # 世界观构建工具
│ │ ├── character.js # 角色创建工具
│ │ └── chapter.js # 章节撰写工具
│ └── memory.js # 记忆管理
└── package.json
1.3 完整代码
1.3.1 配置文件 (config/settings.json)
{
"agent": {
"name": "NovelWriter",
"role": "专业小说作家",
"genre": "武侠",
"target_words": 100000
},
"llm": {
"model": "zai/glm-4.7",
"temperature": 0.8,
"max_tokens": 4000
},
"reAct": {
"max_iterations": 10,
"verbose": true
}
}
配置说明:
genre:小说类型(武侠、玄幻、科幻等)target_words:目标字数temperature:创意度(0-1,越高越随机)max_iterations:最大迭代次数
1.3.2 主 Agent (src/agent.js)
const { sessions_spawn, sessions_send, memory_search } = require('openclaw-sdk');
const fs = require('fs').promises;
const config = require('../config/settings.json');
class NovelWriterAgent {
constructor() {
this.config = config;
this.iterations = 0;
this.maxIterations = config.reAct.max_iterations;
}
async run(topic) {
console.log(`🎬 开始创作小说:${topic}\n`);
console.log(`📊 目标字数:${this.config.agent.target_words} 字\n`);
// ReAct 主循环
while (this.iterations < this.maxIterations) {
this.iterations++;
// 1. Thought:思考下一步行动
const thought = await this.think(topic);
console.log(`\n💭 Thought (${this.iterations}): ${thought}\n`);
// 2. 解析 Action
const action = this.parseAction(thought);
console.log(`🎯 Action: ${action.type}`);
// 3. 执行 Action
const observation = await this.executeAction(action);
console.log(`👁️ Observation: ${observation}\n`);
// 4. 检查是否完成
if (observation.includes('完成')) {
break;
}
}
console.log(`✅ 小说创作完成!`);
return await this.exportNovel();
}
async think(topic) {
const prompt = `你是一个专业小说作家,正在创作一部${this.config.agent.genre}小说。
当前进度:
${await this.getProgress()}
请思考下一步应该做什么。按照以下格式回复:
- 如果需要构建世界观:Action: create_world [世界观描述]
- 如果需要创建角色:Action: create_character [角色描述]
- 如果需要撰写章节:Action: write_chapter [章节大纲]
- 如果需要修改内容:Action: revise [修改要求]
- 如果已完成:Action: complete
你的思考:`;
const response = await this.callLLM(prompt);
return response;
}
parseAction(thought) {
// 解析 "Action: type [params]"
const match = thought.match(/Action:\s*(\w+)\s*(.*)/);
if (match) {
return {
type: match[1],
params: match[2].trim()
};
}
return { type: 'unknown', params: '' };
}
async executeAction(action) {
switch (action.type) {
case 'create_world':
return await this.createWorld(action.params);
case 'create_character':
return await this.createCharacter(action.params);
case 'write_chapter':
return await this.writeChapter(action.params);
case 'revise':
return await this.revise(action.params);
case 'complete':
return '小说创作完成!';
default:
return '未知操作,请重新思考';
}
}
async createWorld(description) {
// 调用世界观构建工具
const worldBuilder = require('./tools/world-builder');
const world = await worldBuilder.build(description, this.config.llm);
// 保存到记忆
await this.saveToMemory('world', world);
return `世界观已创建:${world.name},背景:${world.background}`;
}
async createCharacter(description) {
const character = require('./tools/character');
const char = await character.create(description, this.config.llm);
await this.saveToMemory('character', char);
return `角色已创建:${char.name},性格:${char.personality}`;
}
async writeChapter(outline) {
const chapter = require('./tools/chapter');
const world = await this.getFromMemory('world');
const characters = await this.getFromMemory('characters');
const content = await chapter.write(outline, world, characters, this.config.llm);
// Reflexion:自我反思
const feedback = await this.reflect(content);
if (feedback.needsRevision) {
return `章节需要修改:${feedback.feedback}`;
}
await this.saveChapter(content);
return `章节已撰写,字数:${content.length}`;
}
async reflect(content) {
const prompt = `请审查以下章节内容,给出反馈:
${content.substring(0, 500)}...
请从以下方面评估:
1. 情节是否连贯?
2. 角色性格是否一致?
3. 语言是否自然?
如果需要修改,请说明具体要求。按JSON格式回复:
{
"needsRevision": true/false,
"feedback": "具体反馈"
}`;
const response = await this.callLLM(prompt);
return JSON.parse(response);
}
async getProgress() {
const world = await this.getFromMemory('world');
const characters = await this.getFromMemory('characters');
const chapters = await this.getChapters();
return `
世界观:${world ? world.name : '未创建'}
角色数:${characters ? characters.length : 0}
已写章节:${chapters.length}
累计字数:${chapters.reduce((sum, c) => sum + c.length, 0)}
`;
}
async saveToMemory(key, data) {
const memory = require('./memory');
await memory.save(key, data);
}
async getFromMemory(key) {
const memory = require('./memory');
return await memory.get(key);
}
async saveChapter(content) {
const chapterNum = (await this.getChapters()).length + 1;
await fs.writeFile(`output/chapter_${chapterNum}.md`, content, 'utf-8');
}
async getChapters() {
try {
const files = await fs.readdir('output');
const chapters = [];
for (const file of files) {
if (file.startsWith('chapter_')) {
const content = await fs.readFile(`output/${file}`, 'utf-8');
chapters.push(content);
}
}
return chapters;
} catch {
return [];
}
}
async callLLM(prompt) {
// 这里调用 OpenClaw 的 LLM 接口
// 实际实现取决于你的配置
return await sessions_send({
sessionKey: 'llm-service',
message: prompt
});
}
async exportNovel() {
const chapters = await this.getChapters();
const world = await this.getFromMemory('world');
const novel = `# ${world ? world.name : '未命名小说'}
世界观:${world ? world.background : ''}
---
${chapters.map((c, i) => `## 第${i + 1}章\n\n${c}`).join('\n\n---\n\n')}
`;
await fs.writeFile('output/novel.md', novel, 'utf-8');
return 'output/novel.md';
}
}
// 使用示例
async function main() {
const agent = new NovelWriterAgent();
const novelPath = await agent.run('一个剑客在乱世中寻找武道真谛的故事');
console.log(`\n📚 小说已导出至:${novelPath}`);
}
main();
1.3.3 世界观构建工具 (src/tools/world-builder.js)
const fs = require('fs').promises;
module.exports = {
async build(description, llmConfig) {
const prompt = `请根据以下描述构建一个武侠小说的世界观:
${description}
请生成:
1. 世界名称
2. 时代背景
3. 武力体系
4. 地理格局
5. 门派势力
按JSON格式回复:`;
const response = await this.callLLM(prompt);
const world = JSON.parse(response);
// 保存世界观
await fs.mkdir('output', { recursive: true });
await fs.writeFile('output/world.json', JSON.stringify(world, null, 2), 'utf-8');
return world;
}
};
1.4 运行示例
安装依赖
npm install openclaw-sdk
运行 Agent
node src/agent.js
输出示例
🎬 开始创作小说:一个剑客在乱世中寻找武道真谛的故事
📊 目标字数:100000 字
💭 Thought (1): 我需要先构建世界观,确定故事的时代背景和武力体系。
🎯 Action: create_world 武侠乱世,朝廷衰弱,群雄并起
👁️ Observation: 世界观已创建:乱世江湖,背景:大明朝末年...
💭 Thought (2): 世界观已创建,现在需要创建主角角色。
🎯 Action: create_character 男主角,20岁,剑客,性格孤僻但正义
👁️ Observation: 角色已创建:叶孤云,性格:外冷内热...
💭 Thought (3): 角色已创建,现在开始撰写第一章。
🎯 Action: write_chapter 第一章:叶孤云初入江湖,在客栈遭遇恶霸
👁️ Observation: 章节已撰写,字数:2034
...
✅ 小说创作完成!
📚 小说已导出至:output/novel.md
1.5 技术要点解析
ReAct 循环实现
// ReAct 核心:思考-行动-观察 循环
while (this.iterations < this.maxIterations) {
// 1. Thought
const thought = await this.think(topic);
// 2. Action
const action = this.parseAction(thought);
// 3. Observation
const observation = await this.executeAction(action);
// 检查是否完成
if (observation.includes('完成')) break;
}
Reflexion 自我反思
// 反思章节质量
async reflect(content) {
const prompt = `请审查以下章节内容...`;
const response = await this.callLLM(prompt);
const feedback = JSON.parse(response);
if (feedback.needsRevision) {
// 需要修改,返回反馈
return feedback;
}
// 无需修改,通过审查
return { needsRevision: false };
}
记忆管理
// 保存到记忆
await this.saveToMemory('world', world);
// 从记忆读取
const world = await this.getFromMemory('world');
// 获取进度信息
const progress = await this.getProgress();
二、实战案例二:问答 Agent(CoT 模式)
2.1 项目概述
这是一个基于 CoT(Chain of Thought)模式的问答系统,擅长数学计算和逻辑推理问题。
技术栈:
- 框架:原生 OpenAI API
- 模式:CoT(思维链)
- 语言:Python
功能特点:
- 🧮 数学计算推理
- 🔗 逻辑关系推导
- 📝 详细的推理步骤展示
- 💡 清晰的答案输出
2.2 完整代码
from openai import OpenAI
import json
class CoTQAAgent:
def __init__(self, api_key, model="gpt-4"):
self.client = OpenAI(api_key=api_key)
self.model = model
def answer(self, question, context=None):
"""使用 CoT 模式回答问题"""
prompt = self._build_prompt(question, context)
response = self.client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": "你是一个智能助手,善于逐步推理。"},
{"role": "user", "content": prompt}
],
temperature=0.3
)
return self._parse_response(response.choices[0].message.content)
def _build_prompt(self, question, context):
"""构建 CoT Prompt"""
if context:
prompt = f"""
参考信息:
{context}
问题:{question}
请逐步推理并给出详细解答:
步骤 1:
"""
else:
prompt = f"""
问题:{question}
请逐步推理并给出详细解答:
步骤 1:
"""
return prompt
def _parse_response(self, response):
"""解析响应,提取推理步骤和答案"""
parts = response.split("最终答案:")
if len(parts) == 2:
return {
"reasoning": parts[0].strip(),
"answer": parts[1].strip()
}
return {
"reasoning": response,
"answer": "无法确定"
}
# 使用示例
if __name__ == "__main__":
agent = CoTQAAgent(api_key="your-api-key")
# 示例 1:数学推理
result1 = agent.answer("一家商店有苹果和橘子。苹果 5 元/斤,橘子 3 元/斤。如果买 3 斤苹果和 2 斤橘子,一共多少钱?")
print("问题 1:")
print("推理过程:", result1["reasoning"])
print("答案:", result1["answer"])
print()
# 示例 2:逻辑推理
context = """
小说中的角色关系:
- 李明是张三的朋友
- 张三是王四的弟弟
- 王四是赵五的同事
"""
result2 = agent.answer("李明和王四是什么关系?", context)
print("问题 2:")
print("推理过程:", result2["reasoning"])
print("答案:", result2["answer"])
2.3 运行示例
安装依赖
pip install openai
设置 API Key
export OPENAI_API_KEY="your-api-key-here"
运行程序
python cot_qa_agent.py
输出示例
问题 1:
推理过程:
步骤 1:计算苹果的价格。苹果 5 元/斤,买 3 斤,所以苹果总价 = 5 × 3 = 15 元。
步骤 2:计算橘子的价格。橘子 3 元/斤,买 2 斤,所以橘子总价 = 3 × 2 = 6 元。
步骤 3:计算总价格。总价格 = 苹果总价 + 橘子总价 = 15 + 6 = 21 元。
最终答案:一共 21 元。
答案: 一共 21 元。
问题 2:
推理过程:
步骤 1:分析李明和张三的关系。已知李明是张三的朋友,所以李明 = 朋友(张三)。
步骤 2:分析张三和王四的关系。已知张三是王四的弟弟,所以张三 = 弟弟(王四)。
步骤 3:综合分析。李明是张三的朋友,张三是王四的弟弟,因此李明是王四的弟弟的朋友。
步骤 4:确定关系。虽然李明和王四没有直接关系描述,但通过张三这个中间人,可以说他们是"朋友的朋友"关系。
最终答案:李明是王四的弟弟的朋友,即朋友的朋友关系。
答案: 李明是王四的弟弟的朋友,即朋友的朋友关系。
2.4 技术要点解析
CoT Prompt 设计
def _build_prompt(self, question, context):
"""构建 CoT Prompt"""
prompt = f"""
问题:{question}
请逐步推理并给出详细解答:
步骤 1: # 引导模型开始第一步推理
"""
return prompt
关键技巧:
- 使用"步骤 1:"引导模型开始推理
- 逐步分解问题
- 明确要求"详细解答"
响应解析
def _parse_response(self, response):
"""提取推理步骤和答案"""
parts = response.split("最终答案:")
return {
"reasoning": parts[0].strip(),
"answer": parts[1].strip()
}
三、实战案例三:多 Agent 协作(Swarm)
3.1 项目概述
这是一个使用 OpenAI Swarm 框架的多 Agent 协作系统,演示了如何通过多个专门的 Agents 完成复杂的自动化任务。
技术栈:
- 框架:OpenAI Swarm
- 模式:ReAct(多 Agent 版)
- 语言:Python
功能特点:
- 👥 多 Agent 协作
- 🔄 工作流自动化
- 💾 结果自动保存
- 📊 分阶段处理
3.2 完整代码
from swarm import Agent
import json
# 定义多个 Agents
researcher = Agent(
name="Researcher",
instructions="""
你是研究员,负责搜集和分析信息。
你的职责:
1. 搜索相关资料
2. 提取关键数据
3. 整理研究结果
""",
functions=["search", "scrape", "extract_data"]
)
analyst = Agent(
name="Analyst",
instructions="""
你是分析师,负责数据分析和可视化。
你的职责:
1. 分析收集的数据
2. 发现趋势和规律
3. 生成分析报告
""",
functions=["calculate", "chart", "report"]
)
writer = Agent(
name="Writer",
instructions="""
你是写手,负责撰写文章。
你的职责:
1. 根据分析和研究结果撰写文章
2. 确保内容清晰易懂
3. 格式规范
""",
functions=["write_article", "format_document"]
)
class MultiAgentWorkflow:
def __init__(self):
self.agents = {
"researcher": researcher,
"analyst": analyst,
"writer": writer
}
self.context = {}
def run(self, topic):
"""运行多 Agent 协作流程"""
print(f"🚀 开始处理主题:{topic}\n")
# Stage 1: 研究
print("📚 Stage 1: 研究")
research_result = self.agents["researcher"].run(
f"研究主题:{topic}\n请搜集最新的相关资料和数据。"
)
self.context["research"] = research_result
print(f"✅ 研究完成,收集了 {len(research_result)} 条资料\n")
# Stage 2: 分析
print("📊 Stage 2: 分析")
analysis_result = self.agents["analyst"].run(
f"基于以下研究结果进行分析:\n{research_result}\n"
f"请发现趋势、规律,并生成分析报告。"
)
self.context["analysis"] = analysis_result
print(f"✅ 分析完成\n")
# Stage 3: 撰写
print("✍️ Stage 3: 撰写")
article_result = self.agents["writer"].run(
f"基于研究和分析结果撰写文章:\n"
f"研究资料:{research_result}\n"
f"分析报告:{analysis_result}\n"
f"主题:{topic}"
)
self.context["article"] = article_result
print(f"✅ 文章撰写完成\n")
# 保存结果
self.save_results()
return article_result
def save_results(self):
"""保存所有阶段的结果"""
output_dir = "output"
import os
os.makedirs(output_dir, exist_ok=True)
with open(f"{output_dir}/research.json", "w", encoding="utf-8") as f:
json.dump(self.context["research"], f, ensure_ascii=False, indent=2)
with open(f"{output_dir}/analysis.txt", "w", encoding="utf-8") as f:
f.write(self.context["analysis"])
with open(f"{output_dir}/article.md", "w", encoding="utf-8") as f:
f.write(self.context["article"])
print(f"💾 所有结果已保存到 {output_dir}/ 目录\n")
# 使用示例
if __name__ == "__main__":
workflow = MultiAgentWorkflow()
article = workflow.run("2024 年 AI 技术发展趋势")
print("=" * 50)
print("最终文章预览:")
print("=" * 50)
print(article[:500] + "...")
3.3 运行示例
安装依赖
pip install swarm-sdk
运行程序
python multi_agent_workflow.py
输出示例
🚀 开始处理主题:2024 年 AI 技术发展趋势
📚 Stage 1: 研究
✅ 研究完成,收集了 15 条资料
📊 Stage 2: 分析
✅ 分析完成
✍️ Stage 3: 撰写
✅ 文章撰写完成
💾 所有结果已保存到 output/ 目录
==================================================
最终文章预览:
==================================================
# 2024 年 AI 技术发展趋势
## 概述
2024 年,人工智能技术继续以惊人的速度发展。本文基于最新的研究资料和数据,分析当前 AI 领域的主要趋势。
## 主要趋势
### 1. 大语言模型的进化
2024 年见证了新一代大语言模型的问世。相比之前的模型,新模型在以下几个方面取得了突破:
- **上下文窗口**:从 32K 扩展到 200K+
- **多模态能力**:原生支持图像、视频理解
- **推理能力**:在复杂任务上表现显著提升
### 2. AI Agent 的兴起
...
3.4 技术要点解析
Agent 定义
researcher = Agent(
name="Researcher", # Agent 名称
instructions="...", # 角色指令
functions=["search", "scrape", ...] # 可用工具
)
工作流编排
def run(self, topic):
# 阶段 1:研究
research = self.agents["researcher"].run(...)
# 阶段 2:分析(基于研究结果)
analysis = self.agents["analyst"].run(research)
# 阶段 3:撰写(基于研究和分析)
article = self.agents["writer"].run(research, analysis)
上下文传递
self.context = {
"research": research_result, # 保存研究结果
"analysis": analysis_result, # 保存分析结果
"article": article_result # 保存最终文章
}
四、实战案例四:简单 ReAct Agent(可立即运行)
4.1 项目概述
这是一个最小化的 ReAct Agent 实现,约 100 行代码,可以立即运行。适合作为学习和快速原型开发的参考。
技术栈:
- 框架:原生 OpenAI API
- 模式:ReAct
- 语言:Python
功能特点:
- 🧮 数学计算工具
- 🔍 信息搜索工具
- 💭 思考-行动-观察循环
- ⚡ 快速原型
4.2 完整代码
import re
from openai import OpenAI
class SimpleReActAgent:
def __init__(self, api_key, model="gpt-4"):
self.client = OpenAI(api_key=api_key)
self.model = model
self.max_iterations = 5
def run(self, question):
"""运行 ReAct 循环"""
print(f"🤔 问题:{question}\n")
messages = [
{"role": "system", "content": self._get_system_prompt()}
]
for iteration in range(self.max_iterations):
# 生成 Thought 和 Action
messages.append({"role": "user", "content": question})
response = self.client.chat.completions.create(
model=self.model,
messages=messages
)
output = response.choices[0].message.content
messages.append({"role": "assistant", "content": output})
print(f"💭 Thought {iteration + 1}: {output}")
# 解析 Action
action_match = re.search(r'Action:\s*(.+)', output)
if not action_match:
continue
action = action_match.group(1).strip()
# 执行 Action
observation = self._execute_action(action)
print(f"👁️ Observation: {observation}\n")
messages.append({"role": "user", "content": f"Observation: {observation}"})
# 检查是否完成
if "Answer:" in output:
answer_match = re.search(r'Answer:\s*(.+)', output)
if answer_match:
return answer_match.group(1).strip()
return "未能完成推理"
def _get_system_prompt(self):
return """
你是一个 ReAct Agent,按照以下格式回答:
Question: {问题}
Thought: {你的思考过程}
Action: {调用的工具和参数}
Observation: {工具返回的结果}
...(循环直到得到最终答案)
Answer: {最终答案}
可用工具:
- calculator: 计算数学表达式,格式:calculator[表达式]
- search: 搜索信息,格式:search[关键词]
"""
def _execute_action(self, action):
"""执行操作"""
try:
if action.startswith("calculator["):
expr = action[len("calculator["):-1]
result = eval(expr) # 注意:生产环境不要用 eval
return f"计算结果:{result}"
elif action.startswith("search["):
query = action[len("search["):-1]
# 这里应该调用真实的搜索 API
return f"搜索结果(模拟):关于'{query}'的信息是..."
else:
return f"未知操作:{action}"
except Exception as e:
return f"执行失败:{str(e)}"
# 使用示例
if __name__ == "__main__":
# 需要设置环境变量 OPENAI_API_KEY
import os
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
print("请设置环境变量 OPENAI_API_KEY")
exit(1)
agent = SimpleReActAgent(api_key)
# 示例问题
question1 = "计算 (15 + 23) * 7 等于多少?"
answer1 = agent.run(question1)
print(f"✅ 答案:{answer1}\n")
print("=" * 50 + "\n")
question2 = "如果我有 100 元,买 3 本书每本 15 元,还剩多少钱?"
answer2 = agent.run(question2)
print(f"✅ 答案:{answer2}\n")
4.3 运行示例
安装依赖
pip install openai
设置 API Key
export OPENAI_API_KEY="your-api-key-here"
运行程序
python simple_react_agent.py
输出示例
🤔 问题:计算 (15 + 23) * 7 等于多少?
💭 Thought 1: 我需要先计算括号内的加法,然后计算乘法。
Action: calculator[(15 + 23) * 7]
👁️ Observation: 计算结果:266
Answer: 266
✅ 答案:266
==================================================
🤔 问题:如果我有 100 元,买 3 本书每本 15 元,还剩多少钱?
💭 Thought 1: 我需要先计算买书花费的总金额。
Action: calculator[3 * 15]
👁️ Observation: 计算结果:45
💭 Thought 2: 现在我知道买书花费 45 元,从 100 元中减去就是剩余金额。
Action: calculator[100 - 45]
👁️ Observation: 计算结果:55
Answer: 55
✅ 答案:55
4.4 技术要点解析
ReAct System Prompt
def _get_system_prompt(self):
return """
你是一个 ReAct Agent,按照以下格式回答:
Question: {问题}
Thought: {你的思考过程}
Action: {调用的工具和参数}
Observation: {工具返回的结果}
Answer: {最终答案}
"""
关键点:
- 明确的输出格式
- 清晰的工具使用说明
- 循环终止条件
Action 解析
# 使用正则表达式解析 Action
action_match = re.search(r'Action:\s*(.+)', output)
action = action_match.group(1).strip()
工具执行
def _execute_action(self, action):
if action.startswith("calculator["):
expr = action[len("calculator["):-1]
result = eval(expr)
return f"计算结果:{result}"
elif action.startswith("search["):
# 执行搜索
...
总结与对比
案例对比表
| 案例 | 模式 | 框架 | 语言 | 复杂度 | 代码量 | 适用场景 |
|------|------|------|------|--------|--------|----------|
| 小说创作 Agent | ReAct + Reflexion | OpenClaw | JavaScript | ⭐⭐⭐⭐ | ~250 行 | 创意写作 |
| 问答 Agent | CoT | 原生 OpenAI API | Python | ⭐⭐ | ~80 行 | 逻辑推理 |
| 多 Agent 协作 | ReAct | Swarm | Python | ⭐⭐⭐ | ~150 行 | 流程自动化 |
| 简单 ReAct Agent | ReAct | 原生 OpenAI API | Python | ⭐⭐ | ~100 行 | 快速原型 |
学习路径建议
初学者
-
从 简单 ReAct Agent 开始
- 理解基本的思考-行动-观察循环
- 掌握 Prompt 设计
-
尝试 问答 Agent
- 学习 CoT 推理
- 理解逐步推理的重要性
进阶者
-
学习 多 Agent 协作
- 掌握 Agent 间通信
- 理解工作流编排
-
挑战 小说创作 Agent
- 综合运用 ReAct + Reflexion
- 理解记忆管理和状态维护
常见问题
Q1: 如何选择合适的模式?
- 多步骤任务 → ReAct
- 逻辑推理 → CoT
- 创意探索 → ToT
- 持续优化 → Reflexion
Q2: 如何选择合适的框架?
- Python 生态 → LangChain / Swarm
- Node.js 生态 → OpenClaw
- 快速原型 → 原生 API
Q3: 如何控制成本?
- 减少迭代次数
- 使用更小的模型
- 优化 Prompt 长度
- 缓存常用结果
扩展建议
基于这些案例,你可以:
-
扩展工具集
- 添加数据库工具
- 集成搜索引擎
- 接入外部 API
-
优化性能
- 实现并行处理
- 添加结果缓存
- 优化 Prompt
-
增强功能
- 添加可视化界面
- 实现用户交互
- 支持多模态输入