从源码拆解AI Agent与普通聊天机器人的本质区别
AI Agent实战系列·第1篇 从源码拆解Agent与普通聊天机器人的本质区别
写在前面
本文你将收获:
-
• ✅ 5分钟理解AI Agent到底是什么 -
• ✅ 看懂Agent与ChatGPT的3个核心区别 -
• ✅ 用100行代码实现一个能干活的AI -
• ✅ 运行你的第一个Agent程序
一、一个真实的场景
想象一下,你现在需要完成这样一个任务:
“帮我分析一下昨天的销售数据,计算总营收,找出销量最高的3个产品,然后给老板发个邮件汇报。”
用ChatGPT怎么做?
你可能需要这样操作:
-
1. 手动打开Excel,导出数据 -
2. 复制数据到ChatGPT,让它分析 -
3. ChatGPT给你结果 -
4. 你再手动整理格式 -
5. 打开邮箱,粘贴内容 -
6. 检查格式,发送邮件
整个过程需要人工参与6个步骤。
用AI Agent怎么做?
1你:帮我分析昨天的销售数据并发邮件给老板
2
3Agent:收到!让我来处理
4 → 正在读取数据库...
5 → 正在分析数据...
6 → 计算完成:总营收 ¥125,340
7 → 销量Top3:产品A、产品B、产品C
8 → 正在生成邮件...
9 → 邮件已发送!
10
整个过程全自动,你只需要一句话。
这就是AI Agent的魔力 —— 它不仅会”想”,还会”做”。
二、什么是AI Agent?
2.1 一句话定义
AI Agent = 大语言模型的”大脑” + 工具的”手脚” + 自主决策的能力
让我们拆解一下:
|
|
|
|
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
2.2 用代码理解
一个最简单的Agent长这样:
1defsimple_agent(task):
2whilenot task_completed:
3# 1. 思考:下一步做什么?
4 thought = llm.think(task)
5
6# 2. 行动:使用工具执行
7 result = use_tool(thought.action)
8
9# 3. 反馈:根据结果继续思考
10 task = update_task(result)
11
12return final_result
核心是这个循环:想 → 做 → 看结果 → 再想 → 再做…
这和人类解决问题的方式一模一样!
三、Agent vs ChatGPT:三个本质区别
很多人会困惑:ChatGPT不就是AI吗?Agent和它有什么不同?
区别1️⃣:被动 vs 主动
ChatGPT(被动响应):
1你:帮我查一下明天的天气
2ChatGPT:抱歉,我无法访问实时信息...
3
Agent(主动执行):
1你:帮我查一下明天的天气
2Agent:
3 → 调用天气API...
4 → 明天北京:晴,15-25℃
5 → 建议穿薄外套
6
区别2️⃣:单轮 vs 多轮推理
ChatGPT: 一问一答,每次对话相对独立
Agent: 像下棋一样,会提前规划多步:
1任务:订一张去上海的机票
2
3Agent的思考过程:
4第1步:先查我的日程,看什么时候有空
5第2步:搜索那天的航班信息
6第3步:比较价格和时间
7第4步:选择最优方案
8第5步:调用订票API
9第6步:发送确认邮件
10
区别3️⃣:纯文本 vs 真实世界交互
|
|
|
|
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
💡 关键洞察: ChatGPT是”大脑”,Agent是”大脑+身体”。
四、Agent的工作原理:感知-决策-执行循环
所有的AI Agent,无论多复杂,都遵循这个基本循环:
1┌─────────────────────────────────────┐
2│ │
3│ 1. 感知 (Perception) │
4│ ↓ │
5│ 2. 决策 (Decision) │
6│ ↓ │
7│ 3. 执行 (Action) │
8│ ↓ │
9│ 4. 观察结果 (Observation) │
10│ ↓ │
11└─────┘ (循环回到第1步) │
12
实际例子解析
任务: “帮我计算 (123 + 456) × 789”
1━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
2【第1轮】
3━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
4
5💭 Agent思考:
6 "我需要先计算123+456,然后再乘以789"
7
8🔧 Agent行动:
9 使用计算器工具
10 calculator(123 + 456)
11
12👀 观察结果:
13 "计算结果是 579"
14
15━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
16【第2轮】
17━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
18
19💭 Agent思考:
20 "现在我需要用579乘以789"
21
22🔧 Agent行动:
23 calculator(579 × 789)
24
25👀 观察结果:
26 "计算结果是 456,831"
27
28✅ 任务完成!最终答案:456,831
29
看到了吗?Agent会自己拆解任务,一步步执行,直到完成目标。
五、动手实践:100行代码实现你的第一个Agent
理论说再多不如实际跑一遍。现在我们来实现一个真正能用的Agent。
5.1 准备工作
1# 安装依赖
2pipinstallopenai
1# 设置API Key
2importopenai
3openai.api_key ="你的OpenAI密钥"
5.2 完整代码
1"""
2一个100行的最小Agent实现
3功能:可以使用计算器和搜索工具
4"""
5
6importopenai
7importre
8
9classMinimalAgent:
10def__init__(self, tools):
11self.tools = {t["name"]: t["func"] for t in tools}
12self.history = []
13
14defrun(self, task, max_steps=10):
15"""执行任务"""
16print(f"\n{'='*50}")
17print(f"🎯 任务: {task}")
18print(f"{'='*50}\n")
19
20# 初始化对话
21self.history = [
22 {"role": "system", "content": self._system_prompt()},
23 {"role": "user", "content": task}
24 ]
25
26# 主循环
27for step inrange(1, max_steps +1):
28print(f"【第{step}轮】")
29
30# 1. 让LLM思考
31 response =self._call_llm()
32print(f"💭 思考: {response}\n")
33
34# 2. 检查是否完成
35if"FINISH:"in response:
36 answer = response.split("FINISH:")[1].strip()
37print(f"✅ 完成!答案: {answer}")
38return answer
39
40# 3. 解析并执行工具
41 tool_name, args =self._parse_action(response)
42if tool_name:
43 result =self._execute_tool(tool_name, args)
44print(f"🔧 使用工具: {tool_name}({args})")
45print(f"📊 结果: {result}\n")
46
47# 4. 将结果反馈给LLM
48self.history.append({"role": "assistant", "content": response})
49self.history.append({"role": "user", "content": f"观察: {result}"})
50
51return"任务未完成"
52
53def_call_llm(self):
54"""调用大语言模型"""
55 response = openai.ChatCompletion.create(
56 model="gpt-3.5-turbo",
57 messages=self.history,
58 temperature=0
59 )
60return response.choices[0].message.content
61
62def_parse_action(self, response):
63"""解析工具调用"""
64# 匹配格式: USE_TOOL: tool_name(arguments)
65 match = re.search(r"USE_TOOL:\s*(\w+)\((.*?)\)", response)
66if match:
67return match.group(1), match.group(2)
68returnNone, None
69
70def_execute_tool(self, tool_name, args):
71"""执行工具"""
72if tool_name inself.tools:
73returnself.tools[tool_name](args)
74returnf"错误: 工具 {tool_name} 不存在"
75
76def_system_prompt(self):
77"""系统提示词"""
78 tool_desc ="\n".join([
79f"- {name}"for name inself.tools.keys()
80 ])
81
82returnf"""你是一个AI助手,可以使用以下工具:
83{tool_desc}
84
85使用工具的格式:
86USE_TOOL: tool_name(arguments)
87
88完成任务后的格式:
89FINISH: 你的最终答案
90
91一步步思考,清晰说明你的推理过程。"""
92
93# ========== 定义工具 ==========
94
95defcalculator(expression):
96"""计算器工具"""
97try:
98 result =eval(expression)
99returnstr(result)
100except:
101return"计算错误"
102
103defsearch(query):
104"""搜索工具(模拟)"""
105# 实际应该调用搜索API
106returnf"关于'{query}'的搜索结果:[模拟数据]"
107
108# ========== 使用示例 ==========
109
110if__name__=="__main__":
111# 创建Agent
112 agent = MinimalAgent(tools=[
113 {"name": "calculator", "func": calculator},
114 {"name": "search", "func": search}
115 ])
116
117# 执行任务
118 result = agent.run("计算 (25 + 75) × 4 的结果")
119
120print(f"\n{'='*50}")
121print(f"最终结果: {result}")
122print(f"{'='*50}")
5.3 运行效果
1==================================================
2🎯 任务: 计算 (25 + 75) × 4 的结果
3==================================================
4
5【第1轮】
6💭 思考: 我需要先计算 25 + 75,然后将结果乘以 4
7
8🔧 使用工具: calculator(25 + 75)
9📊 结果: 100
10
11【第2轮】
12💭 思考: 现在我需要将 100 乘以 4
13
14🔧 使用工具: calculator(100 * 4)
15📊 结果: 400
16
17【第3轮】
18💭 思考: 计算完成
19FINISH: 400
20
21✅ 完成!答案: 400
22
23==================================================
24最终结果: 400
25==================================================
26
六、代码解析:Agent的4个关键部分
1. 系统提示词(System Prompt)
1def_system_prompt(self):
2returnf"""你是一个AI助手,可以使用以下工具:
3{tool_desc}
4
5使用工具的格式:
6USE_TOOL: tool_name(arguments)
7"""
💡 这是Agent的”使用说明书”,告诉LLM它有什么能力、怎么使用。
2. 主循环
1for step inrange(1, max_steps +1):
2 response =self._call_llm() # 思考
3 tool_name, args =self._parse_action(response) # 解析
4 result =self._execute_tool(tool_name, args) # 执行
5# 反馈给LLM继续思考
💡 这是Agent的”心跳”,不断循环直到任务完成。
3. 工具解析
1def_parse_action(self, response):
2 match = re.search(r"USE_TOOL:\s*(\w+)\((.*?)\)", response)
3if match:
4return match.group(1), match.group(2)
💡 这是Agent的”翻译器”,把LLM的想法转换成实际操作。
4. 历史记录
1self.history.append({"role": "assistant", "content": response})
2self.history.append({"role": "user", "content": f"观察: {result}"})
💡 这是Agent的”记忆”,记住之前做了什么、结果如何。
七、试试更复杂的任务
现在我们让Agent处理一个更实际的问题:
1agent.run("""
2今天是2026年1月15日,请帮我:
3
41. 计算距离春节(2月17日)还有多少天
5
62. 搜索一下春节旅游推荐
7""")
Agent会这样工作:
1【第1轮】
2💭 思考: 需要计算1月15日到2月17日的天数
3 1月剩余:31-15=16天
4 2月到17日:17天
5 总计:16+17=32天
6
7🔧 使用工具: calculator(31 - 15 + 17)
8📊 结果: 32
9
10【第2轮】
11💭 思考: 现在搜索春节旅游推荐
12
13🔧 使用工具: search(2026春节旅游推荐)
14📊 结果: 关于2026春节旅游推荐 的搜索结果...
15
16【第3轮】
17💭 思考: 已经完成两个任务
18FINISH:
19 距离春节还有32天
20 春节旅游推荐:[搜索结果]
21
看到了吗?Agent自己拆解任务、分步执行、整合结果。
八、现在你可以做什么?
💪 立即尝试
-
1. 复制上面的代码,在本地运行 -
2. 修改任务,看Agent怎么处理 -
3. 添加新工具,比如:python def read_file(filename): with open(filename) as f: return f.read()
🎯 练习题
尝试让你的Agent完成这些任务:
-
1. ✅ 简单:计算一个复杂的数学表达式 -
2. ✅ 中等:读取一个文本文件并统计字数 -
3. ✅ 困难:分析CSV文件并生成报表
📚 下期预告
下一篇我们将深入探讨:
-
• ReAct模式的论文原理 -
• LangChain、AutoGPT如何实现ReAct -
• 更强大的Prompt工程技巧 -
• 处理复杂任务的策略
总结
✅ AI Agent = 大脑(LLM)+ 手脚(工具)+ 循环(反馈)
✅ 核心工作流程:感知 → 决策 → 执行 → 观察 → 循环
✅ 100行代码就能实现一个可用的Agent
✅ Prompt是Agent的”操作系统”
💡 核心洞察: Agent的强大不在于模型本身,而在于”思考-行动-反馈”的循环机制。
如果这篇文章对你有帮助:
-
• 👍 点个赞,让更多人看到 -
• 🔖 收藏起来,方便随时查阅 -
• 📤 转发给需要的朋友
留言区见! 你在学习AI Agent过程中遇到了什么问题?欢迎留言讨论!
夜雨聆风
