LangChain 内置工具全解析(按场景分类)

LangChain 的 langchain.tools(新版已迁移到 langchain_community.tools)提供了大量开箱即用的工具,覆盖日常查询、代码执行、文件操作、网络访问、数据处理等核心场景。

按功能分类整理,附上核心用法。

注意:LangChain v0.1+ 后,大部分内置工具已从 langchain.tools 迁移到 langchain_community.tools,下文示例均采用新版导入方式。


一、核心工具分类与清单

1. 基础通用工具

工具名称 功能 导入路径
CalculatorTool 数学计算(支持加减乘除、幂运算等) langchain_community.tools.calculator.CalculatorTool
PythonREPLTool 执行 Python 代码(支持动态计算、数据处理) langchain_community.tools.python.tool.PythonREPLTool
ShellTool 执行 Shell 命令(Linux/macOS/Windows) langchain_community.tools.shell.tool.ShellTool
FileSystemTool 文件 / 文件夹操作(读写、创建、删除、列出) langchain_community.tools.file_system.tool.FileSystemTool
快速示例(基础工具)
python 复制代码
# 1. 计算器工具
from langchain_community.tools.calculator import CalculatorTool
calculator = CalculatorTool()
print(calculator.run("100*20 + 50"))  # 输出:2050

# 2. Python代码执行工具
from langchain_community.tools.python.tool import PythonREPLTool
python_tool = PythonREPLTool()
# 执行代码计算列表平均值
result = python_tool.run("nums = [1,2,3,4,5]; print(sum(nums)/len(nums))")
print(result)  # 输出:3.0

# 3. 文件操作工具
from langchain_community.tools.file_system.tool import FileSystemTool
file_tool = FileSystemTool(root_dir="./")  # 限定操作目录(安全)
file_tool.run("write_file: ./test.txt, 内容:Hello LangChain")  # 写文件
print(file_tool.run("read_file: ./test.txt"))  # 读文件

2. 网络 / 搜索类工具

工具名称 功能 导入路径 依赖
DuckDuckGoSearchRun 无隐私的网页搜索 langchain_community.tools.duckduckgo_search.tool.DuckDuckGoSearchRun 安装:pip install duckduckgo-search
SerpAPI 谷歌搜索(需 API Key) langchain_community.tools.serpapi.tool.SerpAPI 安装:pip install serpapi + 申请 SerpAPI Key
GoogleSearchAPIWrapper 谷歌搜索(官方 API) langchain_community.utilities.google_search.GoogleSearchAPIWrapper 谷歌 API Key + 自定义搜索引擎 ID
RequestsTool 发送 HTTP 请求(GET/POST,调用 API) langchain_community.tools.requests.tool.RequestsTool 无需额外依赖
WikipediaQueryRun 维基百科查询 langchain_community.tools.wikipedia.tool.WikipediaQueryRun 安装:pip install wikipedia
快速示例(搜索工具)
python 复制代码
# 1. DuckDuckGo搜索(无需API Key)
from langchain_community.tools.duckduckgo_search.tool import DuckDuckGoSearchRun
search = DuckDuckGoSearchRun()
# 搜索2026年北京GDP
result = search.run("2026年北京GDP 官方数据")
print(result[:500])  # 输出前500字符

# 2. 调用HTTP API(比如天气API)
from langchain_community.tools.requests.tool import RequestsTool
requests_tool = RequestsTool()
# 调用免费天气API(示例)
weather = requests_tool.run("get: https://wttr.in/北京?format=3")
print(weather)  # 输出:北京: 晴 22°C

3. 文档 / 数据处理工具

工具名称 功能 导入路径 依赖
CSVTool 读取 / 查询 CSV 文件(支持 SQL-like 查询) langchain_community.tools.csv.tool.CSVTool 安装:pip install pandas
JSONTool 解析 / 查询 JSON 数据 langchain_community.tools.json.tool.JSONTool 无需额外依赖
PDFMinerTool 读取 PDF 文件内容 langchain_community.tools.pdf.tool.PDFMinerTool 安装:pip install pdfminer.six
UnstructuredFileTool 解析多格式文件(txt/md/pdf/docx 等) langchain_community.tools.unstructured.tool.UnstructuredFileTool 安装:pip install unstructured
快速示例(CSV 工具)
python 复制代码
from langchain_community.tools.csv.tool import CSVTool
# 假设已有data.csv:name,age\nAlice,25\nBob,30
csv_tool = CSVTool(file_path="./data.csv")
# 查询年龄大于28的用户
result = csv_tool.run("SELECT name FROM data WHERE age > 28")
print(result)  # 输出:Bob

4. 第三方服务集成工具

工具名称 功能 导入路径 依赖 / 备注
OpenWeatherMapTool 查询天气(需 API Key) langchain_community.tools.openweathermap.tool.OpenWeatherMapTool 安装:pip install pyowm + 申请 OpenWeatherMap Key
GitHubTool 操作 GitHub(查仓库、提 PR 等) langchain_community.tools.github.tool.GitHubTool GitHub Token
GmailTool 发送 / 读取 Gmail 邮件 langchain_community.tools.gmail.tool.GmailTool Google Cloud API Key
SlackTool 发送 Slack 消息 langchain_community.tools.slack.tool.SlackTool Slack Token
NotionTool 操作 Notion 数据库 / 页面 langchain_community.tools.notion.tool.NotionTool Notion API Key
快速示例(天气工具)
python 复制代码
import os
from langchain_community.tools.openweathermap.tool import OpenWeatherMapTool

os.environ["OPENWEATHERMAP_API_KEY"] = "你的API Key"
weather_tool = OpenWeatherMapTool()
# 查询北京天气
result = weather_tool.run("北京")
print(result)  # 输出包含温度、天气状况、湿度等

5. 进阶工具(代码 / 开发相关)

工具名称 功能 导入路径 依赖
GitTool 执行 Git 命令(提交、拉取、分支管理) langchain_community.tools.git.tool.GitTool 系统安装 Git
DockerTool 操作 Docker(构建、运行、停止容器) langchain_community.tools.docker.tool.DockerTool 系统安装 Docker + 权限
AWSBoto3Tool 操作 AWS 服务(S3、EC2 等) langchain_community.tools.aws.tool.AWSBoto3Tool 安装:pip install boto3 + AWS 密钥
AzureTool 操作 Azure 服务 langchain_community.tools.azure.tool.AzureTool Azure 密钥

6. 小众但实用的工具

工具名称 功能 导入路径
TavilySearchResults 轻量级隐私搜索(比 DuckDuckGo 更快) langchain_community.tools.tavily_search.tool.TavilySearchResults 安装:pip install tavily-python
YouTubeSearchTool YouTube 视频搜索 langchain_community.tools.youtube.search.tool.YouTubeSearchTool 安装:pip install youtube-search-python
TranslateTool 多语言翻译(基于 Google Translate) langchain_community.tools.translate.tool.TranslateTool 无需额外依赖

二、工具使用的核心技巧

1. 工具的统一调用方式

所有 LangChain 工具都实现了统一的 run() 方法,也可通过 Agent 自动调用:

python 复制代码
# 方式1:直接调用
from langchain_community.tools.calculator import CalculatorTool
tool = CalculatorTool()
result = tool.run("2^10 + 500")
print(result)  # 输出:1524

# 方式2:集成到Agent(自动选择工具)
from langchain_community.chat_models import ChatTongyi
from langchain.agents import initialize_agent, AgentType

llm = ChatTongyi(model_name="qwen-turbo")
tools = [CalculatorTool(), PythonREPLTool()]
# 初始化Agent
agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.CHAT_ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True  # 打印思考过程
)
# 执行复杂任务:先计算再用Python验证
agent.run("计算10的3次方,并用Python代码验证结果是否正确")

2. 工具的安全限制

  • ShellTool/PythonREPLTool 有执行风险,建议限定操作目录 / 禁用危险函数:

    python 复制代码
    from langchain_community.tools.shell.tool import ShellTool
    # 禁用rm、sudo等危险命令
    shell_tool = ShellTool(allowed_commands=["ls", "pwd", "cat"])
    # 或限定工作目录
    shell_tool = ShellTool(root_dir="./safe_dir")
  • FileSystemTool 建议通过 root_dir 限定操作范围,避免越权访问。

3. 自定义工具的扩展

如果内置工具不满足需求,可基于 BaseTool 自定义:

python 复制代码
from langchain_core.tools import BaseTool, Tool
from typing import Optional

# 方式1:快速定义
def custom_weather_tool(city: str) -> str:
    """自定义天气工具(模拟)"""
    return f"{city}今天晴,25℃"

weather_tool = Tool(
    name="CustomWeatherTool",
    func=custom_weather_tool,
    description="获取指定城市的天气信息,参数为城市名(中文)"
)

# 方式2:类继承(更灵活)
class MyWeatherTool(BaseTool):
    name = "MyWeatherTool"
    description = "获取城市天气"
    
    def _run(self, city: str) -> str:
        return f"{city}天气:晴 25℃"
    
    async def _arun(self, city: str) -> str:
        # 异步实现(可选)
        return self._run(city)

# 使用自定义工具
print(weather_tool.run("上海"))  # 输出:上海今天晴,25℃

三、工具安装与版本注意事项

1. 核心依赖安装

python 复制代码
# 基础工具依赖
pip install langchain-community

# 按工具类型安装额外依赖
pip install duckduckgo-search  # 搜索工具
pip install pandas csvkit     # CSV工具
pip install wikipedia         # 维基百科工具
pip install pdfminer.six      # PDF工具
pip install unstructured      # 多格式文件工具

2. 版本兼容

  • LangChain v0.1.x 后,工具从 langchain.tools 迁移到 langchain_community.tools,旧代码需修改导入路径;
  • 部分工具(如 SerpAPI)需要申请第三方 API Key,建议先查看官方文档获取密钥。

总结

  1. 核心分类 :LangChain 内置工具覆盖基础计算、网络搜索、文件处理、第三方服务、开发工具五大类,满足 80% 的通用场景;
  2. 使用原则 :简单场景直接调用 run() 方法,复杂场景集成到 Agent 自动选择工具;
  3. 安全要点:执行代码 / Shell / 文件操作的工具需做权限限制,避免安全风险;
  4. 扩展思路 :内置工具不满足时,基于 BaseTool/Tool 快速自定义。

你如果是做 Agent 开发,优先用 CalculatorTool/DuckDuckGoSearchRun/PythonREPLTool 这些高频工具,再根据需求扩展第三方服务工具(如天气、邮件)。

相关推荐
youyoulg2 小时前
有监督学习中的分类方法
学习·分类·数据挖掘
babe小鑫2 小时前
2026大专商务英语专业学习数据分析的价值分析
学习·数据挖掘·数据分析
hans汉斯3 小时前
【数据挖掘】基于轻量化GE-GRU-VAE模型的多维时间序列异常检测
人工智能·深度学习·机器学习·数据挖掘·gru·汉斯出版社
STLearner3 小时前
ICLR 2026 | 时空数据(Spatial-Temporal)论文总结[上](交通与城市科学:交通预测,轨迹挖掘,自动驾驶等)
大数据·论文阅读·人工智能·深度学习·机器学习·数据挖掘·自动驾驶
YangYang9YangYan3 小时前
2026大专电子商务专业学习数据分析的价值分析
学习·数据挖掘·数据分析
babe小鑫3 小时前
2026大专财富管理学数据分析价值分析
数据挖掘·数据分析
marsh02063 小时前
2 为什么选择OpenClaw?深入分析其技术优势与商业价值
人工智能·ai·数据挖掘·编程·技术
wayz113 小时前
Pandas 从入门到精通:完整数据分析指南
数据挖掘·数据分析·pandas