- 按 Python 课件的章节式结构重组为 9 个部分、24 章 - 新增 ReAct 模块:原理与手写实现、LangGraph 实现、create_agent、5 个案例 - 补齐 RAG、LangGraph 工作流、多智能体、任务调度 - 新增 3 个项目实战与部署评估章节 - 统一 '学习目标 / 概念 / 代码 / 小结 / 练习' 结构
267 lines
8.4 KiB
Markdown
267 lines
8.4 KiB
Markdown
# create_agent 标准实现
|
||
|
||
> **本章目标**:用 LangChain 1.x 的 `create_agent` 写出生产可用的 ReAct 智能体,并知道它替你做了什么。
|
||
> **前置知识**:第 4.2 章。
|
||
> **预计用时**:80 分钟。
|
||
|
||
## 1. create_agent 是什么
|
||
|
||
`create_agent` 是 LangChain 1.x 推荐的智能体构建入口。它返回的不是「一个函数」,而是一个**编译好的状态图**——内部就是你上一章手画的那张图:
|
||
|
||
```text
|
||
START → model ⇄ tools → END
|
||
```
|
||
|
||
也就是说:
|
||
|
||
> **create_agent = 官方实现的 ReAct 循环 + 一堆工程化默认值。**
|
||
|
||
这些默认值包括:工具执行、错误捕获、消息合并、步数保护、流式输出、检查点、结构化输出。
|
||
|
||
## 2. 最小可用版本
|
||
|
||
```python
|
||
# %%
|
||
from dotenv import load_dotenv
|
||
from langchain_openai import ChatOpenAI
|
||
from langchain.agents import create_agent
|
||
from langchain.tools import tool
|
||
|
||
load_dotenv()
|
||
|
||
@tool
|
||
def query_weather(city: str) -> str:
|
||
"""查询城市天气。
|
||
|
||
参数:
|
||
city: 城市中文名,如 "北京"
|
||
"""
|
||
data = {"北京": "晴 25°C", "上海": "多云 28°C", "广州": "小雨 30°C"}
|
||
return data.get(city.strip(), f"没有 {city} 的天气数据")
|
||
|
||
@tool
|
||
def calculator(expression: str) -> str:
|
||
"""计算数学表达式,支持 + - * / ( )。
|
||
|
||
参数:
|
||
expression: 例如 "(25-28)"
|
||
"""
|
||
import re
|
||
if not re.fullmatch(r"[0-9+\-*/().\s]+", expression):
|
||
return "错误:表达式只能包含数字和 + - * / ( )"
|
||
return str(eval(expression, {"__builtins__": {}}, {}))
|
||
|
||
llm = ChatOpenAI(model="qwen3.6-35b-A3b", temperature=0)
|
||
|
||
agent = create_agent(
|
||
model=llm,
|
||
tools=[query_weather, calculator],
|
||
system_prompt=(
|
||
"你是一个严谨的助手。需要实时数据或精确计算时必须调用工具,不要猜测。"
|
||
"工具报错时调整参数重试,不要用相同参数重复调用。"
|
||
),
|
||
)
|
||
|
||
result = agent.invoke({
|
||
"messages": [{"role": "user", "content": "北京和上海的气温相差多少度?"}]
|
||
})
|
||
|
||
print(result["messages"][-1].content)
|
||
```
|
||
|
||
就这么多。没有手写循环、没有 `ToolMessage` 配对、没有条件边。
|
||
|
||
## 3. 它到底替你做了什么
|
||
|
||
| 你上一章手写的 | create_agent 的处理 |
|
||
| --- | --- |
|
||
| `call_model` 节点 | 内置,自动拼 system prompt |
|
||
| `call_tools` 节点 | 内置,自动配对 `tool_call_id` |
|
||
| `should_continue` | 内置,自动判断 |
|
||
| `MAX_STEPS` | 内置递归限制(可配) |
|
||
| 消息 reducer | 内置 `add_messages` |
|
||
| 工具异常 | 自动转成错误消息回传给模型 |
|
||
|
||
你可以直接看它的结构:
|
||
|
||
```python
|
||
# %%
|
||
print(agent.get_graph().draw_mermaid())
|
||
```
|
||
|
||
输出会是 `model` 与 `tools` 两个节点互相连接,和你上一章画的一模一样。
|
||
|
||
## 4. 参数速查
|
||
|
||
```python
|
||
agent = create_agent(
|
||
model=llm, # 必填:模型或模型名
|
||
tools=[...], # 工具列表
|
||
system_prompt="...", # 系统提示词
|
||
checkpointer=memory, # 记忆(见第 6 节)
|
||
response_format=MySchema, # 结构化输出(见第 7 节)
|
||
interrupt_before=["tools"], # 执行工具前暂停(人工审批)
|
||
debug=False, # 打印内部事件
|
||
)
|
||
```
|
||
|
||
| 参数 | 什么时候用 |
|
||
| --- | --- |
|
||
| `tools` | 需要外部能力 |
|
||
| `system_prompt` | 约束行为、规定输出风格 |
|
||
| `checkpointer` | 多轮对话、恢复执行 |
|
||
| `response_format` | 下游要解析结构化结果 |
|
||
| `interrupt_before` | 高风险工具需要人工确认 |
|
||
| `middleware` | 需要摘要、限流、审计等横切逻辑 |
|
||
|
||
## 5. 看清每一步执行
|
||
|
||
生产调试最有用的是流式观察:
|
||
|
||
```python
|
||
# %%
|
||
for chunk in agent.stream(
|
||
{"messages": [{"role": "user", "content": "杭州今天适合跑步吗?"}]},
|
||
stream_mode="updates",
|
||
):
|
||
for node, update in chunk.items():
|
||
print(f"\n--- {node} ---")
|
||
for m in update.get("messages", []):
|
||
m.pretty_print()
|
||
```
|
||
|
||
典型输出:
|
||
|
||
```text
|
||
--- model ---
|
||
AIMessage(tool_calls=[{'name': 'query_weather', 'args': {'city': '杭州'}}])
|
||
|
||
--- tools ---
|
||
ToolMessage('小雨 18°C')
|
||
|
||
--- model ---
|
||
AIMessage('杭州今天小雨 18°C,不适合户外跑步,建议室内运动。')
|
||
```
|
||
|
||
`updates` 模式是排查「模型为什么没用工具」的最佳工具:如果第一步 `model` 就没有 `tool_calls`,问题一定在提示词或工具描述。
|
||
|
||
## 6. 多轮记忆
|
||
|
||
```python
|
||
# %%
|
||
from langgraph.checkpoint.memory import InMemorySaver
|
||
|
||
memory = InMemorySaver()
|
||
|
||
agent_mem = create_agent(
|
||
model=llm,
|
||
tools=[query_weather, calculator],
|
||
system_prompt="你是一个严谨的助手。",
|
||
checkpointer=memory,
|
||
)
|
||
|
||
config = {"configurable": {"thread_id": "user_001"}}
|
||
|
||
r1 = agent_mem.invoke(
|
||
{"messages": [{"role": "user", "content": "我叫小明,在北京"}]},
|
||
config=config,
|
||
)
|
||
print("第 1 轮:", r1["messages"][-1].content)
|
||
|
||
r2 = agent_mem.invoke(
|
||
{"messages": [{"role": "user", "content": "我这里天气怎么样?"}]},
|
||
config=config,
|
||
)
|
||
print("第 2 轮:", r2["messages"][-1].content)
|
||
```
|
||
|
||
关键点:
|
||
|
||
- `thread_id` 是会话 ID,同一个 ID 共享历史;
|
||
- `InMemorySaver` 存在内存里,进程重启就没了;
|
||
- 生产环境换 `SqliteSaver` / `PostgresSaver`;
|
||
- 不传 `config` 时每次都是新会话。
|
||
|
||
## 7. 结构化输出
|
||
|
||
如果下游要程序解析,而不是给人看,用 `response_format`:
|
||
|
||
```python
|
||
# %%
|
||
from pydantic import BaseModel, Field
|
||
|
||
class WeatherAnswer(BaseModel):
|
||
city: str = Field(description="城市")
|
||
temperature: int = Field(description="摄氏温度")
|
||
advice: str = Field(description="出行建议")
|
||
|
||
agent_struct = create_agent(
|
||
model=llm,
|
||
tools=[query_weather, calculator],
|
||
system_prompt="你是一个严谨的助手。",
|
||
response_format=WeatherAnswer,
|
||
)
|
||
|
||
out = agent_struct.invoke({
|
||
"messages": [{"role": "user", "content": "杭州现在多少度?该穿什么?"}]
|
||
})
|
||
|
||
print(out["structured_response"])
|
||
# city='杭州' temperature=18 advice='小雨,建议穿薄外套并带伞'
|
||
```
|
||
|
||
注意:`response_format` 要求模型支持结构化输出;不支持时 LangChain 会退化为「提示词 + 解析」,稳定性会下降。
|
||
|
||
## 8. 什么时候不用 create_agent
|
||
|
||
`create_agent` 很好,但它把循环「包起来」了。以下情况建议自己画图:
|
||
|
||
| 需求 | 建议 |
|
||
| --- | --- |
|
||
| 标准「模型 ⇄ 工具」循环 | 用 `create_agent` |
|
||
| 循环里要插入审核、改写、摘要节点 | 自己画图 |
|
||
| 多智能体交接 | 自己画图或 supervisor 模式 |
|
||
| 需要精确控制步数、分支、回滚 | 自己画图 |
|
||
| 需要自定义状态字段 | 自己画图(`state_schema`) |
|
||
|
||
一句话:**原型用 create_agent,复杂流程用 LangGraph 手画。**
|
||
|
||
## 9. 和 ReAct 的对应关系
|
||
|
||
| ReAct 概念 | create_agent 中的体现 |
|
||
| --- | --- |
|
||
| Thought | 模型内部的推理(不总是显式输出) |
|
||
| Action | `AIMessage.tool_calls` |
|
||
| Observation | `ToolMessage` |
|
||
| 循环 | `model → tools → model` |
|
||
| 终止 | 模型不再返回 `tool_calls` |
|
||
| 轨迹 | `result["messages"]` 全量保留 |
|
||
|
||
所以你可以理直气壮地说:**create_agent 就是一个 ReAct 智能体**,只是「思考」被折叠进了模型内部,没有打印成 `Thought:` 文本。
|
||
|
||
## 10. 常见错误
|
||
|
||
| 现象 | 原因 | 解决 |
|
||
| --- | --- | --- |
|
||
| 不调用工具 | 提示词没要求 / 描述太弱 | 改 system prompt + 工具 docstring |
|
||
| `recursion_limit` 报错 | 循环太多 | 提高限制或修提示词 |
|
||
| 多轮记不住 | 没传 `checkpointer` 或 `thread_id` | 两者都要 |
|
||
| `structured_response` 为空 | 模型不支持 / Schema 太复杂 | 简化字段或改用手动解析 |
|
||
| 工具参数缺失 | 注解不完整 | 补类型与默认值 |
|
||
|
||
## 11. 本章小结
|
||
|
||
- `create_agent` 返回一个编译好的 ReAct 状态图;
|
||
- 它替你处理了工具执行、消息配对、异常、步数保护;
|
||
- `stream_mode="updates"` 是观察执行过程的最佳方式;
|
||
- `checkpointer + thread_id` 实现多轮记忆;
|
||
- `response_format` 输出结构化结果;
|
||
- 复杂流程仍然建议自己用 LangGraph 画。
|
||
|
||
## 12. 练习
|
||
|
||
1. 把第 3 章的电商工具集接入 `create_agent`,问一个需要连续调用 3 个工具的问题;
|
||
2. 用 `stream_mode="updates"` 打印每一步,数一数一共几轮;
|
||
3. 给智能体加 `response_format`,输出 `{answer, tools_used, confidence}`;
|
||
4. 对比手写版、LangGraph 版、`create_agent` 版的代码行数与可调试性,写一段结论。
|