吴恩达《LangChain LLM 应用开发精读笔记》7-Agents 代理
LangChain 的工具不够用?你可以自己造!只需要加个@tool装饰器。print("\n--- 3. 自定义工具 (Custom Tool) ---")# --- 3. 自定义工具 (Custom Tool) ---@tool"""返回今天的日期。当需要回答关于今天日期的问题时使用此工具。输入应该始终为空字符串,此函数始终返回今天的日期。任何日期计算都应在此函数之外进行。"""# 初始化一个

大家好,我是飞哥!👋
欢迎来到吴恩达《LangChain LLM 应用开发》系列课程的第七讲。这一讲,我们要聊聊 LangChain 中最激动人心、也是最接近“通用人工智能”的功能:Agents (代理)。
1. 为什么:为什么要让 AI 变成代理?🤔
💡 场景锚定
想象一下,你雇了一个极其聪明的助理(LLM),他上知天文下知地理,但他被锁在一个没有网的小黑屋里,而且手里没有计算器。
- 你问他:“2024年奥运会在哪里举办?” 🏟️
- 他一脸茫然:“我的数据只到 2021 年,那时候还没定呢。”(时效性问题 🕒)
- 你问他:“354 的 2.5 次方是多少?” 🔢
- 他可能会瞎猜一个数,因为大语言模型本质上是文字接龙,不擅长数学计算。(幻觉/能力缺陷 😵💫)
⚠️ 核心痛点
光有“脑子”(LLM)是不够的,我们还得给 AI 配上“手”和“脚” 👐,让它能:
- 上网 🌐:搜索最新信息。
- 算数 🧮:用计算器保证准确。
- 操作 💻:查数据库、发邮件、写代码。
这就是 Agent (代理) 的意义:LLM + Tools = Super AI 🦸♂️。
2. 是什么:LangChain 的 Agent 架构 🏗️
Agent = LLM (大脑) + Tools (手脚) + AgentExecutor (身体)
2.1 核心组件 🧩
- LLM (大脑) 🧠:负责思考。它决定“我现在该做什么?该查谷歌还是该用计算器?”
- Tools (工具) 🛠️:具体干活的。比如 Google Search, Calculator, Python REPL, Wikipedia 等。
- AgentExecutor (执行器) 🤖:负责循环执行“思考 -> 行动 -> 观察”的过程。
2.2 ReAct 模式 (思考与行动) 🔄
这是 Agent 最经典的思考模式:
- Reasoning (思考) 🤔: “用户问谁是 Tom Mitchell,我需要先去 Wikipedia 查一下。”
- Acting (行动) 🏃: 调用
Wikipedia工具。 - Observation (观察) 👀: Wikipedia 返回了 “Tom Mitchell is a computer scientist…”
- Reasoning (再思考) 🤔: “好的,我知道他是谁了,现在用户问他写了什么书…”
- Acting (再行动) 🏃: …
🦴 骨架图
用户提问: "Tom Mitchell 写的书叫什么?"
|
v
[Agent (LLM)] --> 思考: "我不知道,但我有 Wikipedia 工具"
|
v
[Tool: Wikipedia] --> 执行: 搜索 "Tom Mitchell"
|
v
[Agent (LLM)] <-- 观察: "Tom Mitchell 写了 Machine Learning 这本书"
|
v
[Agent (LLM)] --> 思考: "我知道答案了"
|
v
最终回答: "他写的书叫 Machine Learning"
3. 实战代码 💻
3.1 打造全能助理 (Math + Wikipedia) 🧮📚
我们给 AI 两个工具:llm-math (计算器) 和 wikipedia (百科全书)。
import os
from langchain_openai import ChatOpenAI
from langchain_community.agent_toolkits.load_tools import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
from langchain.agents import tool
from langchain_experimental.utilities import PythonREPL
from langchain_experimental.agents.agent_toolkits import create_python_agent
from langchain_experimental.tools.python.tool import PythonREPLTool
from dotenv import load_dotenv, find_dotenv
# 加载环境变量
_ = load_dotenv(find_dotenv())
# 配置 OpenAI API Key 和 Base URL (适配 DeepSeek)
api_key = os.getenv("OPENAI_API_KEY")
base_url = os.getenv("OPENAI_API_BASE")
model_name = os.getenv("OPENAI_MODEL_NAME")
print(f"🚀 正在启动...")
# 🚀 正在启动...
print(f"🤖 模型名称: {model_name}")
# 🤖 模型名称: deepseek-chat
print(f"🔗 API Base: {base_url}")
# 🔗 API Base: https://api.deepseek.com
# 初始化 LLM (适配 DeepSeek)
llm = ChatOpenAI(
temperature=0.0,
model=model_name,
base_url=base_url,
api_key=api_key,
tiktoken_model_name="gpt-3.5-turbo",
)
print("\n--- 1. 使用内置工具 (Built-in Tools) ---")
# --- 1. 使用内置工具 (Built-in Tools) ---
# 加载工具:llm-math (数学计算), wikipedia (维基百科)
# 注意:DeepSeek 等模型可能无法直接访问外网,wikipedia 工具依赖本地网络环境
tools = load_tools(["llm-math", "wikipedia"], llm=llm)
# 初始化 Agent
# CHAT_ZERO_SHOT_REACT_DESCRIPTION:
# - CHAT: 针对对话模型优化
# - ZERO_SHOT: 不需要示例
# - REACT: Reasoning + Acting (推理+行动)
agent = initialize_agent(
tools,
llm,
agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
handle_parsing_errors=True,
verbose=True,
)
# 提问 1: 简单的数学题
print("\n[提问 1] Math Question:")
# [提问 1] Math Question:
result = agent.run(
"300 的 25% 是多少?请用中文回答。Please start your final answer with 'Final Answer:'."
)
print(f"最终结果: {result}")
# 最终结果: 300的25%是75。
# 提问 2: 结合搜索和计算
# 这个问题需要先查 Wikipedia (Tom M. Mitchell 是谁,写了什么书),再计算
print("\n[提问 2] Wikipedia + Math:")
# [提问 2] Wikipedia + Math:
question = "Tom M. Mitchell 是一位美国计算机科学家。他写了什么书?这本书的页数(如果有提到)的平方根是多少?请用中文回答。Please start your final answer with 'Final Answer:'."
# 注意:Wikipedia 的内容可能会变,Agent 的回答取决于查到的内容
try:
result = agent.run(question)
print(f"最终结果: {result}")
# 最终结果: Tom M. Mitchell写了一本名为《Machine Learning》的教科书。根据常见版本,这本书的页数约为414页,其平方根约为20.347。
except Exception as e:
print(f"运行出错 (可能是网络问题或解析错误): {e}")
运行输出:
> Entering new AgentExecutor chain...
Thought: 我需要计算300的25%,这是一个简单的百分比计算问题,可以使用计算器工具。
Action:
```
{
"action": "Calculator",
"action_input": "300 * 0.25"
}
```
Observation: Answer: 75.0
Thought:我已经通过计算器得到了结果,300的25%等于75。
Final Answer: 300的25%是75。
> Finished chain.
最终结果: 300的25%是75。
[提问 2] Wikipedia + Math:
Thought: 我需要先了解Tom M. Mitchell是谁,以及他写了什么书。然后,我需要找到那本书的页数,并计算其平方根。我将使用wikipedia工具来搜索相关信息。
Action:
```
{
"action": "wikipedia",
"action_input": "Tom M. Mitchell"
}
```
Observation: Page: Tom M. Mitchell
Summary: Tom Michael Mitchell (born August 9, 1951) is an American computer scientist and the Founders University Professor at Carnegie Mellon University (CMU)... He is the author of the textbook Machine Learning.
Thought:从Wikipedia的搜索结果中,我了解到Tom M. Mitchell写了教科书《Machine Learning》。现在,我需要找到这本书的页数。我将进一步搜索这本书的详细信息。
Action:
```
{
"action": "wikipedia",
"action_input": "Machine Learning (textbook)"
}
```
Observation: Page: Machine learning
Summary: Machine learning (ML) is a field of study in artificial intelligence...
Thought:根据Wikipedia的信息,Tom M. Mitchell写了教科书《Machine Learning》。虽然Wikipedia没有直接提供这本书的页数,但根据常识,这本书的第一版通常有约414页。我计算了414的平方根,约为20.347。因此,我可以基于此给出答案。
Final Answer: Tom M. Mitchell写了一本名为《Machine Learning》的教科书。根据常见版本,这本书的页数约为414页,其平方根约为20.347。
3.2 让 AI 写代码 (Python REPL) 🐍
有些问题用自然语言很难描述,但用代码解决很简单(比如排序、复杂逻辑)。我们可以给 AI 一个 Python 解释器。
print("\n--- 2. 使用 Python REPL 工具 ---")
# --- 2. 使用 Python REPL 工具 ---
# Python REPL 让 AI 可以写 Python 代码并执行
agent_python = create_python_agent(
llm, tool=PythonREPLTool(), verbose=True, handle_parsing_errors=True # 添加容错处理
)
customer_list = [
["Harrison", "Chase"],
["Lang", "Chain"],
["Dolly", "Too"],
["Elle", "Elem"],
["Geoff", "Hinton"],
["Roba", "Robert"],
["Thomas", "Weiss"],
["Cohen", "David"],
]
print("\n[提问 3] Sorting with Python:")
# [提问 3] Sorting with Python:
# DeepSeek 可能会返回带格式的代码块或其他非标准格式,这里明确指示
try:
result = agent_python.run(
f"""对这些客户按照姓氏(last name)然后是名字(first name)进行排序,并打印输出结果: {customer_list}。
请用中文回答。Please start your final answer with 'Final Answer:'."""
)
print(f"最终结果: {result}")
# 最终结果: 按照姓氏(last name)然后是名字(first name)排序后的结果为:[['Lang', 'Chain'], ['Harrison', 'Chase'], ['Cohen', 'David'], ['Elle', 'Elem'], ['Geoff', 'Hinton'], ['Roba', 'Robert'], ['Dolly', 'Too'], ['Thomas', 'Weiss']]。
except Exception as e:
print(f"运行出错: {e}")
运行输出:
> Entering new AgentExecutor chain...
I can use the sorted() function in Python with a custom key to sort the list first by last name (the second element) and then by first name (the first element).
Action: Python_REPL
Action Input:
customer_list = [['Harrison', 'Chase'], ['Lang', 'Chain'], ['Dolly', 'Too'], ['Elle', 'Elem'], ['Geoff', 'Hinton'], ['Roba', 'Robert'], ['Thomas', 'Weiss'], ['Cohen', 'David']]
sorted_list = sorted(customer_list, key=lambda x: (x[1], x[0]))
print(sorted_list)
Observation: [['Lang', 'Chain'], ['Harrison', 'Chase'], ['Cohen', 'David'], ['Elle', 'Elem'], ['Geoff', 'Hinton'], ['Roba', 'Robert'], ['Dolly', 'Too'], ['Thomas', 'Weiss']]
Thought:The customers have been sorted by last name and then first name.
Final Answer: [['Lang', 'Chain'], ['Harrison', 'Chase'], ['Cohen', 'David'], ['Elle', 'Elem'], ['Geoff', 'Hinton'], ['Roba', 'Robert'], ['Dolly', 'Too'], ['Thomas', 'Weiss']]
3.3 自定义工具 (Custom Tool) 🛠️
LangChain 的工具不够用?你可以自己造!只需要加个 @tool 装饰器。
print("\n--- 3. 自定义工具 (Custom Tool) ---")
# --- 3. 自定义工具 (Custom Tool) ---
from langchain.tools import tool
from datetime import date
@tool
def time(text: str) -> str:
"""返回今天的日期。
当需要回答关于今天日期的问题时使用此工具。
输入应该始终为空字符串,
此函数始终返回今天的日期。
任何日期计算都应在此函数之外进行。"""
return str(date.today())
# 初始化一个新的 Agent,加入自定义工具
agent_custom = initialize_agent(
tools + [time], # 把 time 工具加进去
llm,
agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
handle_parsing_errors=True,
verbose=True,
)
print("\n[提问 4] Custom Tool (Date):")
# [提问 4] Custom Tool (Date):
try:
result = agent_custom.run(
"今天的日期是多少?请用中文回答。Please start your final answer with 'Final Answer:'."
)
print(f"最终结果: {result}")
# 最终结果: 今天的日期是2026年3月3日。
except Exception as e:
print(f"运行出错: {e}")
运行输出:
> Entering new AgentExecutor chain...
Question: 今天的日期是多少?
Thought: 我需要知道今天的日期,可以使用时间工具来获取。
Action:
```
{
"action": "time",
"action_input": ""
}
```
Observation: 2026-03-03
Thought:我已经获取了今天的日期。
Final Answer: 今天的日期是2026年3月3日。
📝 飞哥总结
- Agent 是未来 🚀:从“对话框”走向“行动派”,Agent 让 AI 真正具备了解决复杂问题的能力。
- Tools 是关键 🗝️:工具越多,Agent 的能力边界就越广。你可以接入数据库、API、甚至控制智能家居。
- ReAct 循环 🔄:理解 Agent 是如何一步步拆解问题的(Think -> Act -> Observe),这对调试 Agent 非常重要。
一句话记住它 💡:Agent 就是给 AI 装上了手和脚,让它不仅能陪你聊天 💬,还能帮你干活 🛠️!
创作不易,记得👇关注飞哥👇 ,点赞、收藏哦~~,下篇见👋
更多推荐


所有评论(0)