🌟 LangChain 30 天保姆级教程 · Day 11|内置 Tools 大揭秘!5 行代码让 Agent 会搜索、查百科、跑 Python!

3 阅读4分钟

系列目标:30 天从 LangChain 入门到企业级部署
今日任务:掌握 LangChain 官方内置 Tools → 构建多功能 Agent → 安全调用外部能力!


🧰 一、为什么用内置 Tools?

在 Day 10 中,我们手动写了 Calculator 工具。但 LangChain 社区已封装了数十种常用工具,开箱即用:

表格

工具功能适用场景
DuckDuckGoSearchRun免费网络搜索查实时新闻、股价、事件
WikipediaQueryRun查询维基百科获取权威知识
PythonREPLTool执行 Python 代码数据分析、数学计算
ArxivQueryRun搜索学术论文科研辅助
YouTubeSearchTool搜索 YouTube 视频教程推荐

✅ 今天,我们就用这些“官方轮子”,5 分钟打造一个全能型 AI 助手!


⚠️ 二、安全警告:谨慎使用 PythonREPL!

PythonREPLTool 可执行任意 Python 代码,存在严重安全风险
仅限本地开发/可信环境使用,生产环境务必:

  • 禁用危险模块(如 ossubprocess
  • 使用沙箱(如 RestrictedPython
  • 或完全禁用

🔒 本文仅用于学习,请勿在公网服务中直接暴露!


🛠️ 三、动手实践:构建“搜索 + 百科 + 计算”三合一 Agent

步骤 1:安装依赖

# 核心
pip install langchain-ollama

# 内置 Tools 所需
pip install langchain-community \
            duckduckgo-search \
            wikipedia \
            arxiv

💡 langchain-community 包含所有第三方集成工具。


步骤 2:导入并初始化 Tools

# day11_builtin_tools.py
from langchain_ollama import ChatOllama
from langchain.agents import Tool, AgentExecutor, create_react_agent
from langchain_community.tools import (
    DuckDuckGoSearchRun,
    WikipediaQueryRun,
    ArxivQueryRun
)
from langchain_community.utilities import WikipediaAPIWrapper, ArxivAPIWrapper

# 初始化 LLM
llm = ChatOllama(model="qwen:7b", temperature=0)

# 1. 网络搜索(DuckDuckGo)
search = DuckDuckGoSearchRun()

# 2. 维基百科
wikipedia = WikipediaQueryRun(api_wrapper=WikipediaAPIWrapper())

# 3. 学术论文(Arxiv)
arxiv = ArxivQueryRun(api_wrapper=ArxivAPIWrapper())

# 注册 Tools
tools = [
    Tool(name="Search", func=search.run, description="用于搜索最新网络信息"),
    Tool(name="Wikipedia", func=wikipedia.run, description="用于查询维基百科知识"),
    Tool(name="Arxiv", func=arxiv.run, description="用于搜索学术论文")
]

🌐 所有工具均无需 API Key(DuckDuckGo 和 Wikipedia 免费开放)!


步骤 3:创建 ReAct Agent

# 使用默认 ReAct Prompt
prompt = create_react_agent.get_default_prompt()

agent = create_react_agent(llm=llm, tools=tools, prompt=prompt)

agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,
    handle_parsing_errors=True,
    max_iterations=5  # 防止死循环
)

步骤 4:测试多场景问题

test_questions = [
    "杭州2023年GDP是多少?",           # → 调用 Search
    "爱因斯坦的相对论是什么?",        # → 调用 Wikipedia
    "最近有哪些关于大语言模型的论文?", # → 调用 Arxiv
    "Python 如何读取 CSV 文件?"       # → 可能直接回答(无工具调用)
]

for q in test_questions:
    print(f"\n👤 用户:{q}")
    try:
        response = agent_executor.invoke({"input": q})
        print(f"🤖 AI:{response['output']}")
    except Exception as e:
        print(f"❌ 错误:{e}")

▶️ 输出示例(verbose 模式):

Thought: 这是一个关于城市经济的问题,我需要搜索最新数据。
Action: Search
Action Input: 杭州 2023 GDP
Observation: 杭州市2023年GDP为2.2万亿元...
Thought: 我现在知道答案了。
Final Answer: 杭州2023年GDP约为2.2万亿元人民币。

👤 用户:杭州2023年GDP是多少?
🤖 AI:杭州2023年GDP约为2.2万亿元人民币。

✅ Agent 自动选择最合适的工具,无需人工干预!


🐍 四、(可选)加入 PythonREPL(仅限本地实验!)

from langchain_community.tools import PythonREPLTool

# 警告:仅用于本地学习!
python_tool = PythonREPLTool()
tools.append(
    Tool(
        name="Python",
        func=python_tool.run,
        description="用于执行 Python 代码,例如数据分析、绘图等"
    )
)

🔥 测试问题:
“计算 1 到 100 的和,并画出 y=x² 的图像”
→ Agent 会生成代码并执行(需安装 matplotlib


⚠️ 五、常见问题 & 优化建议

表格

问题解决方案
本地模型不遵循 ReAct 格式在 prompt 中强化指令;或改用 create_tool_calling_agent(需 GPT-4/ Claude 3)
搜索结果不相关在 DuckDuckGoSearchRun 中设置 max_results=3 提高精度
Wikipedia 返回空尝试英文关键词(如 "Albert Einstein")
工具调用太慢限制 max_iterations;或缓存结果
中文搜索效果差可结合百度/微信搜索自定义 Tool(Day 20 讲)

💡 提示:Qwen 对中文 ReAct 格式支持较好,但仍建议 temperature=0 提高稳定性。


📦 六、配套代码结构

langchain-30-days/
└── day11/
    ├── builtin_tools_agent.py      # 搜索+百科+论文 Agent
    └── python_repl_demo.py         # (可选)Python 执行演示

📝 七、今日小结

  • ✅ 了解了 LangChain 官方内置 Tools 生态
  • ✅ 学会了使用 DuckDuckGoSearchWikipediaArxiv 三大工具
  • ✅ 构建了能自动选择工具的多功能 Agent
  • ✅ 知道了 PythonREPLTool 的强大与风险
  • ✅ 掌握了工具调用的安全边界

🎯 明日预告:Day 12 —— 自定义 Tool 实战!教你把公司内部 API、数据库、脚本封装成 Agent 可调用工具!