agent-handbook 1.6.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_handbook/__init__.py +14 -0
- agent_handbook/_paths.py +45 -0
- agent_handbook/chapters/00-quickstart.md +347 -0
- agent_handbook/chapters/01-fundamentals.md +181 -0
- agent_handbook/chapters/02-reaact-from-scratch.md +454 -0
- agent_handbook/chapters/03-langgraph.md +510 -0
- agent_handbook/chapters/04-crewai.md +527 -0
- agent_handbook/chapters/05-autogen.md +424 -0
- agent_handbook/chapters/06-llamaindex-rag.md +335 -0
- agent_handbook/chapters/07-dify.md +307 -0
- agent_handbook/chapters/08-openai-agents.md +209 -0
- agent_handbook/chapters/09-claude-agents.md +227 -0
- agent_handbook/chapters/10-mastra.md +134 -0
- agent_handbook/chapters/11-mcp.md +488 -0
- agent_handbook/chapters/12-ollama.md +194 -0
- agent_handbook/chapters/13-collaboration-patterns.md +208 -0
- agent_handbook/chapters/14-memory-state.md +213 -0
- agent_handbook/chapters/15-cost-optimization.md +162 -0
- agent_handbook/chapters/16-observability.md +240 -0
- agent_handbook/chapters/17-fullstack-project.md +443 -0
- agent_handbook/chapters/18-selection-guide.md +188 -0
- agent_handbook/chapters/19-agent-toolkit.md +145 -0
- agent_handbook/chapters/20-codex-cli.md +337 -0
- agent_handbook/chapters/21-deepseek-harness.md +597 -0
- agent_handbook/chapters/22-continue-editor.md +193 -0
- agent_handbook/chapters/23-aider-codestory.md +179 -0
- agent_handbook/chapters/24-trae-ide.md +172 -0
- agent_handbook/chapters/25-harness-engineering.md +290 -0
- agent_handbook/chapters/26-agent-skills.md +604 -0
- agent_handbook/chapters/27-context-engineering.md +308 -0
- agent_handbook/chapters/28-trending-2026.md +155 -0
- agent_handbook/chapters/29-agent-economy.md +133 -0
- agent_handbook/chapters/30-agent-evals.md +138 -0
- agent_handbook/chapters/99-glossary.md +215 -0
- agent_handbook/cli.py +199 -0
- agent_handbook/data/stars-history.csv +12 -0
- agent_handbook/data/stars.json +130 -0
- agent_handbook/doctor.py +218 -0
- agent_handbook/scaffold.py +298 -0
- agent_handbook/search.py +118 -0
- agent_handbook-1.6.0.dist-info/METADATA +220 -0
- agent_handbook-1.6.0.dist-info/RECORD +46 -0
- agent_handbook-1.6.0.dist-info/WHEEL +5 -0
- agent_handbook-1.6.0.dist-info/entry_points.txt +2 -0
- agent_handbook-1.6.0.dist-info/licenses/LICENSE +21 -0
- agent_handbook-1.6.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""agent-handbook —— AI Agent 实战手册的命令行工具。
|
|
2
|
+
|
|
3
|
+
把 31 章手册从「读的东西」变成「用的东西」:
|
|
4
|
+
handbook search <关键词> 31 章全文检索,直接给出章节 + 行号 + 片段
|
|
5
|
+
handbook doctor [路径] 按 Harness 五支柱给 Agent 项目做工程体检
|
|
6
|
+
handbook new <项目名> 生成带 Harness 骨架的 Agent 项目
|
|
7
|
+
handbook stars 打印框架热度表(每周自动刷新)
|
|
8
|
+
handbook list 列出全部章节
|
|
9
|
+
handbook open <章节> 给出该章的在线地址 / 本地路径
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
__version__ = "1.6.0"
|
|
13
|
+
__repo__ = "https://github.com/Xwh630/ai-agent-handbook"
|
|
14
|
+
__site__ = "https://xwh630.github.io/ai-agent-handbook/"
|
agent_handbook/_paths.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""数据路径解析:pip 安装后用包内数据,仓库内开发时用仓库数据。"""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
_PKG_DIR = Path(__file__).parent
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def chapters_dir() -> Path:
|
|
10
|
+
"""返回 chapters/ 目录。优先仓库(内容更新),其次包内副本。"""
|
|
11
|
+
# 1) 包内(pip 安装时打包进去)
|
|
12
|
+
bundled = _PKG_DIR / "chapters"
|
|
13
|
+
if bundled.is_dir() and any(bundled.glob("*.md")):
|
|
14
|
+
return bundled
|
|
15
|
+
# 2) 仓库根(开发模式:src/agent_handbook -> 根)
|
|
16
|
+
repo = _PKG_DIR.parent.parent / "chapters"
|
|
17
|
+
if repo.is_dir():
|
|
18
|
+
return repo
|
|
19
|
+
# 3) 当前工作目录下
|
|
20
|
+
cwd = Path.cwd() / "chapters"
|
|
21
|
+
if cwd.is_dir():
|
|
22
|
+
return cwd
|
|
23
|
+
return bundled
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def data_dir() -> Path:
|
|
27
|
+
"""返回 data/ 目录(stars.json 等)。"""
|
|
28
|
+
bundled = _PKG_DIR / "data"
|
|
29
|
+
if bundled.is_dir() and (bundled / "stars.json").exists():
|
|
30
|
+
return bundled
|
|
31
|
+
repo = _PKG_DIR.parent.parent / "data"
|
|
32
|
+
if (repo / "stars.json").exists():
|
|
33
|
+
return repo
|
|
34
|
+
cwd = Path.cwd() / "data"
|
|
35
|
+
if (cwd / "stars.json").exists():
|
|
36
|
+
return cwd
|
|
37
|
+
return bundled
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def repo_root() -> Path:
|
|
41
|
+
"""尽量推断仓库根目录,找不到就返回包目录。"""
|
|
42
|
+
candidate = _PKG_DIR.parent.parent
|
|
43
|
+
if (candidate / "chapters").is_dir() and (candidate / "README.md").exists():
|
|
44
|
+
return candidate
|
|
45
|
+
return Path(os.getcwd())
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
---
|
|
2
|
+
适配框架版本: 通用 N/A
|
|
3
|
+
最后校验: 2026-10-06
|
|
4
|
+
上游变更监控: N/A
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# 🚀 新手快速入门:10 分钟跑通你的第一个 AI Agent
|
|
8
|
+
|
|
9
|
+
> **目标读者**:完全没接触过 AI Agent 的零基础新手
|
|
10
|
+
> **耗时**:约 10 分钟
|
|
11
|
+
> **你需要准备**:一台能上网的电脑 + 一个 API Key(没有的话可以先用免费方案)
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
## 一、先搞懂:AI Agent 到底是什么?
|
|
16
|
+
|
|
17
|
+
### 用生活打个比方 🍳
|
|
18
|
+
|
|
19
|
+
想象你请了一个**全能管家**(AI Agent),他有三样东西:
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
┌─────────────────────────────────────────────────────────────┐
|
|
23
|
+
│ │
|
|
24
|
+
│ 🧠 大脑(大语言模型 LLM) │
|
|
25
|
+
│ → 负责思考:"主人想吃什么?" │
|
|
26
|
+
│ │
|
|
27
|
+
│ ✋ 双手(工具 Tools) │
|
|
28
|
+
│ → 负责做事:查菜谱、打开冰箱、下单买菜 │
|
|
29
|
+
│ │
|
|
30
|
+
│ 📒 记事本(记忆 Memory) │
|
|
31
|
+
│ → 负责记住:"主人不吃香菜""上次吃过火锅了" │
|
|
32
|
+
│ │
|
|
33
|
+
└─────────────────────────────────────────────────────────────┘
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
**所以:AI Agent = 会思考(LLM)+ 会动手(Tools)+ 会记事儿(Memory)**
|
|
37
|
+
|
|
38
|
+
和普通聊天机器人(ChatGPT)的区别就是:**它能自己动手干活**,而不只是动嘴聊天。
|
|
39
|
+
|
|
40
|
+
---
|
|
41
|
+
|
|
42
|
+
### 再看一张流程图
|
|
43
|
+
|
|
44
|
+
```mermaid
|
|
45
|
+
flowchart LR
|
|
46
|
+
A[🙋 你提出需求] --> B[🧠 Agent 思考<br/>需要查天气]
|
|
47
|
+
B --> C[✋ 调用天气工具<br/>get_weather]
|
|
48
|
+
C --> D[📊 拿到天气结果<br/>25°C 晴]
|
|
49
|
+
D --> E[🧠 再次思考<br/>组织回答]
|
|
50
|
+
E --> F[💬 给你最终回答]
|
|
51
|
+
F --> A
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
**一句话总结**:Agent 就是"想一步、做一步、再看结果、再想"的循环,直到把事情办完。
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
## 二、环境准备(2 分钟)
|
|
59
|
+
|
|
60
|
+
### 方案 A:用本地 Python(推荐新手)
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
# 1. 安装 Python 3.10+(官网下载即可,记得勾选 Add to PATH)
|
|
64
|
+
# 下载地址:https://www.python.org/downloads/
|
|
65
|
+
|
|
66
|
+
# 2. 验证安装
|
|
67
|
+
python --version
|
|
68
|
+
|
|
69
|
+
# 3. 安装依赖
|
|
70
|
+
pip install openai python-dotenv
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### 方案 B:用 Docker(不想折腾环境)
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
docker run -it --rm \
|
|
77
|
+
-e OPENAI_API_KEY=你的key \
|
|
78
|
+
-v $(pwd):/workspace \
|
|
79
|
+
-w /workspace \
|
|
80
|
+
python:3.11-slim bash -c "pip install openai python-dotenv && bash"
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### 方案 C:完全免费不花钱(3 分钟)
|
|
84
|
+
|
|
85
|
+
> 使用国内免费可用的模型服务(如 DeepSeek、智谱 GLM、通义千问等,注册送额度)。
|
|
86
|
+
> 只需把下面的 `base_url` 和 `api_key` 换成对应平台的即可。
|
|
87
|
+
|
|
88
|
+
---
|
|
89
|
+
|
|
90
|
+
## 三、写你的第一个 Agent(5 分钟)
|
|
91
|
+
|
|
92
|
+
### 第 1 步:创建项目文件夹
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
mkdir my-first-agent
|
|
96
|
+
cd my-first-agent
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### 第 2 步:创建配置文件 `.env`
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
# 创建一个 .env 文件,填入以下内容
|
|
103
|
+
OPENAI_API_KEY=sk-你的密钥
|
|
104
|
+
OPENAI_BASE_URL=https://api.openai.com/v1
|
|
105
|
+
# 如果你用国产模型,改成对应的地址,例如:
|
|
106
|
+
# OPENAI_BASE_URL=https://api.deepseek.com/v1
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### 第 3 步:创建 `agent.py`(完整代码,直接复制)
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
"""你的第一个 AI Agent - 一个会查天气和算数的智能助手"""
|
|
113
|
+
import os
|
|
114
|
+
import ast
|
|
115
|
+
import json
|
|
116
|
+
import operator
|
|
117
|
+
from dotenv import load_dotenv
|
|
118
|
+
from openai import OpenAI
|
|
119
|
+
|
|
120
|
+
load_dotenv() # 读取 .env 里的配置
|
|
121
|
+
|
|
122
|
+
# ============ 1. 给 Agent 一双"手"(工具) ============
|
|
123
|
+
|
|
124
|
+
def get_weather(city: str) -> str:
|
|
125
|
+
"""查天气工具"""
|
|
126
|
+
# 真实项目这里应该调用天气 API,我们先用模拟数据
|
|
127
|
+
return f"{city}今天天气:晴,气温 25°C,适合出门!"
|
|
128
|
+
|
|
129
|
+
# 安全求值:禁止 eval() 直接执行用户输入!
|
|
130
|
+
# 只用 AST 白名单解析"数字 + 四则运算",恶意表达式(如 __import__)会被拒绝
|
|
131
|
+
_SAFE_OPS = {
|
|
132
|
+
ast.Add: operator.add,
|
|
133
|
+
ast.Sub: operator.sub,
|
|
134
|
+
ast.Mult: operator.mul,
|
|
135
|
+
ast.Div: operator.truediv,
|
|
136
|
+
ast.USub: operator.neg,
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
def _safe_eval(node):
|
|
140
|
+
"""递归解析 AST 节点,只放行数字与四则运算"""
|
|
141
|
+
if isinstance(node, ast.Expression):
|
|
142
|
+
return _safe_eval(node.body)
|
|
143
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
|
|
144
|
+
return node.value
|
|
145
|
+
if isinstance(node, ast.BinOp) and type(node.op) in _SAFE_OPS:
|
|
146
|
+
return _SAFE_OPS[type(node.op)](_safe_eval(node.left), _safe_eval(node.right))
|
|
147
|
+
if isinstance(node, ast.UnaryOp) and type(node.op) in _SAFE_OPS:
|
|
148
|
+
return _SAFE_OPS[type(node.op)](_safe_eval(node.operand))
|
|
149
|
+
raise ValueError(f"不支持的表达式元素: {type(node).__name__}")
|
|
150
|
+
|
|
151
|
+
def calculator(expression: str) -> float:
|
|
152
|
+
"""计算器工具(只支持数字与 + - * / 等基础运算)"""
|
|
153
|
+
return _safe_eval(ast.parse(expression, mode="eval"))
|
|
154
|
+
|
|
155
|
+
# 把工具"告诉"模型,让它知道能用什么
|
|
156
|
+
TOOLS = [
|
|
157
|
+
{
|
|
158
|
+
"type": "function",
|
|
159
|
+
"function": {
|
|
160
|
+
"name": "get_weather",
|
|
161
|
+
"description": "查询指定城市的天气情况",
|
|
162
|
+
"parameters": {
|
|
163
|
+
"type": "object",
|
|
164
|
+
"properties": {"city": {"type": "string"}},
|
|
165
|
+
"required": ["city"],
|
|
166
|
+
},
|
|
167
|
+
},
|
|
168
|
+
},
|
|
169
|
+
{
|
|
170
|
+
"type": "function",
|
|
171
|
+
"function": {
|
|
172
|
+
"name": "calculator",
|
|
173
|
+
"description": "执行数学计算,比如 (1+2)*3",
|
|
174
|
+
"parameters": {
|
|
175
|
+
"type": "object",
|
|
176
|
+
"properties": {"expression": {"type": "string"}},
|
|
177
|
+
"required": ["expression"],
|
|
178
|
+
},
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
]
|
|
182
|
+
|
|
183
|
+
# ============ 2. 给 Agent 一个"大脑"(LLM) ============
|
|
184
|
+
|
|
185
|
+
client = OpenAI() # 会自动读取 .env 里的 key
|
|
186
|
+
|
|
187
|
+
def run_agent(user_input: str) -> str:
|
|
188
|
+
"""运行 Agent:思考 → 调用工具 → 给出答案"""
|
|
189
|
+
messages = [{"role": "user", "content": user_input}]
|
|
190
|
+
|
|
191
|
+
# 第一次调用:让模型决定是否需要工具
|
|
192
|
+
response = client.chat.completions.create(
|
|
193
|
+
model="gpt-4o-mini", # 便宜好用,新手首选
|
|
194
|
+
messages=messages,
|
|
195
|
+
tools=TOOLS,
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
msg = response.choices[0].message
|
|
199
|
+
|
|
200
|
+
# 如果模型想调用工具
|
|
201
|
+
if msg.tool_calls:
|
|
202
|
+
for tool_call in msg.tool_calls:
|
|
203
|
+
name = tool_call.function.name
|
|
204
|
+
args = json.loads(tool_call.function.arguments)
|
|
205
|
+
print(f"🛠️ 正在调用工具: {name}({args})")
|
|
206
|
+
|
|
207
|
+
# 执行对应的工具函数
|
|
208
|
+
if name == "get_weather":
|
|
209
|
+
result = get_weather(args["city"])
|
|
210
|
+
elif name == "calculator":
|
|
211
|
+
result = calculator(args["expression"])
|
|
212
|
+
else:
|
|
213
|
+
result = "未知工具"
|
|
214
|
+
|
|
215
|
+
# 把工具结果返回给模型
|
|
216
|
+
messages.append(msg)
|
|
217
|
+
messages.append({
|
|
218
|
+
"role": "tool",
|
|
219
|
+
"tool_call_id": tool_call.id,
|
|
220
|
+
"content": str(result),
|
|
221
|
+
})
|
|
222
|
+
|
|
223
|
+
# 第二次调用:让模型基于工具结果生成最终回答
|
|
224
|
+
final = client.chat.completions.create(
|
|
225
|
+
model="gpt-4o-mini",
|
|
226
|
+
messages=messages,
|
|
227
|
+
tools=TOOLS,
|
|
228
|
+
)
|
|
229
|
+
return final.choices[0].message.content
|
|
230
|
+
|
|
231
|
+
return msg.content
|
|
232
|
+
|
|
233
|
+
# ============ 3. 跟你的 Agent 聊天吧! ============
|
|
234
|
+
|
|
235
|
+
if __name__ == "__main__":
|
|
236
|
+
print("🤖 你的第一个 AI Agent 已上线!")
|
|
237
|
+
print("=" * 50)
|
|
238
|
+
|
|
239
|
+
test_questions = [
|
|
240
|
+
"北京今天天气怎么样?",
|
|
241
|
+
"帮我算一下 (123 + 456) * 2 等于多少?",
|
|
242
|
+
]
|
|
243
|
+
|
|
244
|
+
for q in test_questions:
|
|
245
|
+
print(f"\n🙋 你问:{q}")
|
|
246
|
+
answer = run_agent(q)
|
|
247
|
+
print(f"🤖 Agent 答:{answer}")
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
### 第 4 步:运行!
|
|
251
|
+
|
|
252
|
+
```bash
|
|
253
|
+
python agent.py
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
### 你会看到类似输出:
|
|
257
|
+
|
|
258
|
+
```
|
|
259
|
+
🤖 你的第一个 AI Agent 已上线!
|
|
260
|
+
==================================================
|
|
261
|
+
|
|
262
|
+
🙋 你问:北京今天天气怎么样?
|
|
263
|
+
🛠️ 正在调用工具: get_weather({'city': '北京'})
|
|
264
|
+
🤖 Agent 答:北京今天天气晴朗,气温 25°C,适合出门!
|
|
265
|
+
|
|
266
|
+
🙋 你问:帮我算一下 (123 + 456) * 2 等于多少?
|
|
267
|
+
🛠️ 正在调用工具: calculator({'expression': '(123 + 456) * 2'})
|
|
268
|
+
🤖 Agent 答:(123 + 456) * 2 = 1158
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
🎉 **恭喜!你已经成功创建了人生第一个 AI Agent!**
|
|
272
|
+
|
|
273
|
+
---
|
|
274
|
+
|
|
275
|
+
## 四、代码逐行拆解(3 分钟看懂)
|
|
276
|
+
|
|
277
|
+
| 代码段 | 通俗解释 |
|
|
278
|
+
|--------|----------|
|
|
279
|
+
| `TOOLS = [...]` | 给 Agent 的"简历",告诉它你有哪些技能 |
|
|
280
|
+
| `get_weather()` | Agent 的"手"之一,具体干活的人 |
|
|
281
|
+
| `client.chat.completions.create(...)` | 让"大脑"思考一次 |
|
|
282
|
+
| `msg.tool_calls` | 大脑说:"我需要用工具!" |
|
|
283
|
+
| `messages.append(...)` | 把对话记录写进"记事本" |
|
|
284
|
+
| 第二次调用 | 拿到工具结果后,大脑组织最终回答 |
|
|
285
|
+
|
|
286
|
+
**核心心法**:Agent 编程 = 定义工具 + 循环调用 LLM + 传递上下文。
|
|
287
|
+
|
|
288
|
+
---
|
|
289
|
+
|
|
290
|
+
## 五、接下来学什么?
|
|
291
|
+
|
|
292
|
+
你已经入门了!推荐按这个顺序继续:
|
|
293
|
+
|
|
294
|
+
```mermaid
|
|
295
|
+
flowchart LR
|
|
296
|
+
A[✅ 本指南<br/>10分钟入门] --> B[📖 第1章<br/>基础概念]
|
|
297
|
+
B --> C[📖 第2章<br/>手写 ReAct]
|
|
298
|
+
C --> D[📖 第3章<br/>LangGraph]
|
|
299
|
+
D --> E[📖 第17章<br/>全栈实战]
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
| 你的目标 | 推荐路线 |
|
|
303
|
+
|----------|----------|
|
|
304
|
+
| 想快速做个产品原型 | 第 7 章 Dify(拖拽就能做,不用写代码) |
|
|
305
|
+
| 想深入了解原理 | 第 2 章 手写 ReAct(从零实现) |
|
|
306
|
+
| 想开发生产级应用 | 第 3 章 LangGraph + 第 17 章实战 |
|
|
307
|
+
| 想本地免费跑模型 | 第 12 章 Ollama |
|
|
308
|
+
| 不知道选哪个框架 | 第 18 章 选型指南 |
|
|
309
|
+
|
|
310
|
+
---
|
|
311
|
+
|
|
312
|
+
## 六、新手常见问题(FAQ)
|
|
313
|
+
|
|
314
|
+
### Q1:没有 OpenAI 的 Key 怎么办?
|
|
315
|
+
答:可以用国产模型(DeepSeek、智谱、通义千问等),注册就送额度,把 `OPENAI_BASE_URL` 换成对应地址即可,代码不用改。详见第 12 章 Ollama 还能完全免费本地运行。
|
|
316
|
+
|
|
317
|
+
### Q2:报错 `ModuleNotFoundError: No module named 'openai'`
|
|
318
|
+
答:说明没装依赖。运行 `pip install openai python-dotenv` 即可。
|
|
319
|
+
|
|
320
|
+
### Q3:报错 `AuthenticationError`
|
|
321
|
+
答:`.env` 里的 API Key 填错了,检查是否有多余空格。
|
|
322
|
+
|
|
323
|
+
### Q4:Agent 一直调用工具停不下来怎么办?
|
|
324
|
+
答:在代码里加个步骤上限。我们在第 2 章手写 ReAct 时会详细讲解如何控制。
|
|
325
|
+
|
|
326
|
+
### Q5:eval 有安全风险吗?
|
|
327
|
+
答:有,而且非常大!`eval` 可以执行任意代码——即使传了 `{"__builtins__": {}}` 也能通过对象链绕过(如 `().__class__.__bases__[0].__subclasses__()` 拿到任意类)。**永远不要对用户输入用 `eval`**。上面示例用的是 AST 白名单方案:只放行数字和四则运算节点,其余一律拒绝,安全且够用。更复杂的场景建议用 `ast.literal_eval`(仅限字面量)或专门的表达式解析库(如 `py_expression_eval`、`asteval`)。详见 docs/最佳实践。
|
|
328
|
+
|
|
329
|
+
---
|
|
330
|
+
|
|
331
|
+
## 七、本指南配套示例
|
|
332
|
+
|
|
333
|
+
本项目的 `examples/01-react-agent/` 就是完整版示例,还带 SQLite 记忆功能:
|
|
334
|
+
|
|
335
|
+
```bash
|
|
336
|
+
cd examples/01-react-agent
|
|
337
|
+
pip install -r requirements.txt
|
|
338
|
+
python main.py
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
---
|
|
342
|
+
|
|
343
|
+
> **下一站**:翻到 [第 1 章:AI Agent 基础概念](01-fundamentals.md),用 15 分钟彻底搞懂 Agent 的底层原理!
|
|
344
|
+
|
|
345
|
+
---
|
|
346
|
+
|
|
347
|
+
*本指南配套英文版:[English Quickstart](../en/chapters/00-quickstart.md)*
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
---
|
|
2
|
+
适配框架版本: 通用 N/A
|
|
3
|
+
最后校验: 2026-10-06
|
|
4
|
+
上游变更监控: N/A
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# 第 1 章:AI Agent 基础概念
|
|
8
|
+
|
|
9
|
+
> 在本章中,我们将理解 AI Agent 是什么、为什么重要,以及它的基本工作原理。
|
|
10
|
+
|
|
11
|
+
---
|
|
12
|
+
|
|
13
|
+
## 1.1 什么是 AI Agent?
|
|
14
|
+
|
|
15
|
+
### 传统 LLM 调用 vs Agent
|
|
16
|
+
|
|
17
|
+
**传统 LLM 调用:**
|
|
18
|
+
```
|
|
19
|
+
用户提问 → LLM 处理 → 返回答案
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
**AI Agent:**
|
|
23
|
+
```
|
|
24
|
+
用户目标 → [感知 → 决策 → 行动 → 观察] 循环 → 完成目标
|
|
25
|
+
↓
|
|
26
|
+
调用工具 / 查询记忆 / 与其他 Agent 协作
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### Agent 的核心组成
|
|
30
|
+
|
|
31
|
+
一个完整的 Agent = **LLM + 角色 + 工具集 + 记忆 + 决策逻辑**
|
|
32
|
+
|
|
33
|
+
| 组件 | 作用 | 类比 |
|
|
34
|
+
|------|------|------|
|
|
35
|
+
| **LLM(大脑)** | 理解、推理、生成 | 人的大脑 |
|
|
36
|
+
| **角色(Persona)** | 定义专业领域和行为模式 | 职业身份 |
|
|
37
|
+
| **工具集(Tools)** | 调用外部能力(搜索、计算、数据库) | 双手和工具 |
|
|
38
|
+
| **记忆(Memory)** | 短期对话历史 + 长期知识库 | 记忆系统 |
|
|
39
|
+
| **决策逻辑** | 决定下一步动作的规则 | 决策中枢 |
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
## 1.2 Agent 的运行循环
|
|
44
|
+
|
|
45
|
+
Agent 的核心是一个 while 循环,不断执行以下步骤:
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
def agent_loop(user_goal: str, tools: dict, max_steps: int = 10):
|
|
49
|
+
messages = [{"role": "system", "content": build_system_prompt(tools)}]
|
|
50
|
+
messages.append({"role": "user", "content": user_goal})
|
|
51
|
+
|
|
52
|
+
for step in range(max_steps):
|
|
53
|
+
# 1. 感知:调用 LLM 获取响应
|
|
54
|
+
response = call_llm(messages)
|
|
55
|
+
messages.append({"role": "assistant", "content": response})
|
|
56
|
+
|
|
57
|
+
# 2. 解析:检查是否需要调用工具
|
|
58
|
+
action = parse_action(response)
|
|
59
|
+
|
|
60
|
+
if action is None:
|
|
61
|
+
# 没有工具调用,返回最终答案
|
|
62
|
+
return response["content"]
|
|
63
|
+
|
|
64
|
+
# 3. 行动:执行工具调用
|
|
65
|
+
tool_result = execute_tool(action.name, action.parameters)
|
|
66
|
+
messages.append({
|
|
67
|
+
"role": "tool",
|
|
68
|
+
"tool_call_id": action.id,
|
|
69
|
+
"content": tool_result
|
|
70
|
+
})
|
|
71
|
+
# 4. 观察:LLM 根据工具结果继续思考
|
|
72
|
+
|
|
73
|
+
return "任务执行超时,请简化请求"
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### ReAct 模式:推理与行动的结合
|
|
77
|
+
|
|
78
|
+
ReAct = **Re**asoning + **Act**ing
|
|
79
|
+
|
|
80
|
+
```
|
|
81
|
+
Thought: 我需要先查询天气,然后再计算旅行预算
|
|
82
|
+
Action: get_weather(city="北京")
|
|
83
|
+
Observation: 北京今天晴,25°C
|
|
84
|
+
Thought: 天气很好,我可以继续规划行程了...
|
|
85
|
+
Action: calculate_budget(days=3, location="北京")
|
|
86
|
+
...
|
|
87
|
+
Final Answer: 北京三日游预算约 5000 元
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## 1.3 为什么需要 Agent?
|
|
93
|
+
|
|
94
|
+
### 单个 LLM 的局限性
|
|
95
|
+
|
|
96
|
+
| 问题 | 示例 |
|
|
97
|
+
|------|------|
|
|
98
|
+
| **知识时效性** | LLM 训练数据有截止日期 |
|
|
99
|
+
| **事实准确性** | 容易产生幻觉(Hallucination) |
|
|
100
|
+
| **复杂任务** | 需要多步推理和工具调用的任务 |
|
|
101
|
+
| **个性化** | 无法记住用户的偏好和历史 |
|
|
102
|
+
|
|
103
|
+
### Agent 带来的价值
|
|
104
|
+
|
|
105
|
+
```
|
|
106
|
+
┌─────────────────────────────────────────────┐
|
|
107
|
+
│ 传统 LLM │
|
|
108
|
+
│ 问答 → 生成 → 结束 │
|
|
109
|
+
└─────────────────────────────────────────────┘
|
|
110
|
+
|
|
111
|
+
┌─────────────────────────────────────────────┐
|
|
112
|
+
│ AI Agent │
|
|
113
|
+
│ 理解目标 → 规划 → 执行 → 验证 → 调整 │
|
|
114
|
+
│ ↑ │
|
|
115
|
+
│ └── 循环优化直至成功 ───────────────────┘
|
|
116
|
+
└─────────────────────────────────────────────┘
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
## 1.4 多智能体系统 vs 单智能体
|
|
122
|
+
|
|
123
|
+
### 单 Agent 架构
|
|
124
|
+
|
|
125
|
+
```
|
|
126
|
+
用户 → [Agent A] → 结果
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
**优点:** 简单、快速、成本低
|
|
130
|
+
**缺点:** 复杂任务难以胜任、容易偏离目标
|
|
131
|
+
|
|
132
|
+
### 多 Agent 架构
|
|
133
|
+
|
|
134
|
+
```
|
|
135
|
+
┌──────────────┐
|
|
136
|
+
│ Supervisor │
|
|
137
|
+
└──────┬───────┘
|
|
138
|
+
│
|
|
139
|
+
┌────────────────┼────────────────┐
|
|
140
|
+
│ │ │
|
|
141
|
+
┌─────▼─────┐ ┌─────▼─────┐ ┌─────▼─────┐
|
|
142
|
+
│ Research │ │ Writer │ │ Reviewer │
|
|
143
|
+
│ Agent │ │ Agent │ │ Agent │
|
|
144
|
+
└───────────┘ └───────────┘ └───────────┘
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
**优点:** 专业化分工、可并行、易于调试
|
|
148
|
+
**缺点:** 协调复杂度高、Token 消耗大
|
|
149
|
+
|
|
150
|
+
---
|
|
151
|
+
|
|
152
|
+
## 1.5 关键术语速查表
|
|
153
|
+
|
|
154
|
+
| 术语 | 定义 |
|
|
155
|
+
|------|------|
|
|
156
|
+
| **Agent** | 具备感知-决策-行动能力的 LLM 实体 |
|
|
157
|
+
| **Tool Calling** | Agent 调用外部工具的能力 |
|
|
158
|
+
| **Function Calling** | 通过函数调用接口与外部工具交互 |
|
|
159
|
+
| **RAG** | Retrieval-Augmented Generation,检索增强生成 |
|
|
160
|
+
| **Orchestration** | 控制多个 Agent 的执行顺序和数据流向 |
|
|
161
|
+
| **Handoff** | 一个 Agent 将控制权移交给另一个 Agent |
|
|
162
|
+
| **MCP** | Model Context Protocol,AI 工具标准化协议 |
|
|
163
|
+
| **A2A** | Agent-to-Agent Protocol,Agent 间通信协议 |
|
|
164
|
+
| **Checkpointer** | 保存 Agent 状态以实现断点续传 |
|
|
165
|
+
| **HITL** | Human-in-the-Loop,人在回路中的审核机制 |
|
|
166
|
+
|
|
167
|
+
---
|
|
168
|
+
|
|
169
|
+
## 1.6 本章小结
|
|
170
|
+
|
|
171
|
+
- Agent 不是简单的 LLM 调用,而是一个有感知-决策-行动循环的智能系统
|
|
172
|
+
- 核心组成:LLM + 角色 + 工具 + 记忆 + 决策
|
|
173
|
+
- ReAct 模式是 Agent 推理和行动的经典模式
|
|
174
|
+
- 多 Agent 系统适合复杂任务,但协调成本高
|
|
175
|
+
- 选型时要考虑任务复杂度、预算和团队技术栈
|
|
176
|
+
|
|
177
|
+
---
|
|
178
|
+
|
|
179
|
+
## 下一章
|
|
180
|
+
|
|
181
|
+
[→ 第 2 章:从零手写 ReAct Agent](./02-reaact-from-scratch.md)
|