为了大幅提升大语言模型应用开发效率,主流框架 LangChain 提供了数百款开箱即用的标准化工具,全面覆盖信息检索、文件操作、数据库处理、网络访问、代码执行、API 集成等核心场景。这些工具统一接口规范,内置完善的错误处理与数据转换逻辑,避免重复开发;同时支持快速封装自定义工具,并能与链、智能体、RAG 等核心组件深度协同。这不仅能帮助开发者快速构建稳定可靠的 AI 应用,还能极大简化流程、缩短上线周期,让开发者聚焦业务逻辑创新与用户体验优化。
动画视频在《24. LangChain内置工具,开发效率提升10倍!》。
🔍 搜索引擎类
|-------------------------|---------------------------------|
| 工具名称 | 功能 |
| DuckDuckGoSearchRun | 使用 DuckDuckGo 搜索 |
| DuckDuckGoSearchResults | 获取 DuckDuckGo 搜索结果 |
| WikipediaQueryRun | 查询 Wikipedia |
| BingSearchRun | 使用 Bing 搜索(需要 API Key) |
| BingSearchResults | 获取 Bing 搜索结果(需要 API Key) |
| BraveSearch | 使用 Brave 搜索(需要 API Key) |
| SearxSearchRun | 使用 Searx 搜索 |
| SearxSearchResults | 获取 Searx 搜索结果 |
| TavilyAnswer | 获取 Tavily 答案(需要 API Key) |
| TavilySearchResults | 获取 Tavily 搜索结果(需要 API Key) |
| GoogleSerperRun | 使用 Google Serper 搜索(需要 API Key) |
| GoogleSerperResults | 获取 Google Serper 结果(需要 API Key) |
| SearchAPIRun | 使用 SearchAPI 搜索(需要 API Key) |
| SearchAPIResults | 获取 SearchAPI 结果(需要 API Key) |
| JinaSearch | 使用 Jina 搜索 |
| MojeekSearch | 使用 Mojeek 搜索 |
| MetaphorSearchResults | 获取 Metaphor 搜索结果 |
| YouSearchTool | 使用 You.com 搜索 |
| AskNewsSearch | 搜索新闻(需要 API Key) |
📱 社交媒体和平台工具类
|---------------------|--------------------------|
| 工具名称 | 功能 |
| RedditSearchRun | 搜索 Reddit |
| RedditSearchSchema | Reddit 搜索模式 |
| YouTubeSearchTool | 搜索 YouTube |
| StackExchangeTool | 查询 Stack Exchange |
| SteamWebAPIQueryRun | 查询 Steam API(需要 API Key) |
| NasaAction | 查询 NASA 数据(需要 API Key) |
| JiraAction | 操作 Jira(需要 API Key) |
📄 文件管理类
|-------------------|--------|
| 工具名称 | 功能 |
| ReadFileTool | 读取文件内容 |
| WriteFileTool | 写入文件内容 |
| CopyFileTool | 复制文件 |
| DeleteFileTool | 删除文件 |
| MoveFileTool | 移动文件 |
| ListDirectoryTool | 列出目录内容 |
| FileSearchTool | 搜索文件 |
💰 金融工具类
|----------------------|-----------------------------|
| 工具名称 | 功能 |
| YahooFinanceNewsTool | 查询 Yahoo 财经新闻 |
| PolygonAggregates | 获取 Polygon 聚合数据(需要 API Key) |
| PolygonFinancials | 获取 Polygon 财务数据(需要 API Key) |
| PolygonLastQuote | 获取 Polygon 最新报价(需要 API Key) |
| PolygonTickerNews | 获取 Polygon 股票新闻(需要 API Key) |
| BalanceSheets | 获取资产负债表 |
| CashFlowStatements | 获取现金流量表 |
| IncomeStatements | 获取利润表 |
🔧 计算和数据类
|----------------------|---------------------------------|
| 工具名称 | 功能 |
| WolframAlphaQueryRun | 使用 Wolfram Alpha 计算(需要 API Key) |
| JsonGetValueTool | 获取 JSON 值 |
| JsonListKeysTool | 列出 JSON 键 |
| SleepTool | 延迟执行 |
| DataheraldTextToSQL | 文本转 SQL(需要 API Key) |
| AIPluginTool | 使用 AI 插件 |
💾 数据库类
|-----------------------------------|-----------------------------|
| 工具名称 | 功能 |
| QuerySQLDatabaseTool | 查询 SQL 数据库 |
| InfoSQLDatabaseTool | 获取 SQL 数据库信息 |
| ListSQLDatabaseTool | 列出 SQL 数据库表 |
| QuerySQLCheckerTool | 检查 SQL 查询 |
| QuerySparkSQLTool | 查询 Spark SQL |
| InfoSparkSQLTool | 获取 Spark SQL 信息 |
| ListSparkSQLTool | 列出 Spark SQL 表 |
| QueryCheckerTool | 检查查询 |
| QueryPowerBITool | 查询 Power BI(需要 API Key) |
| InfoPowerBITool | 获取 Power BI 信息(需要 API Key) |
| ListPowerBITool | 列出 Power BI 数据集(需要 API Key) |
| QueryCassandraDatabaseTool | 查询 Cassandra 数据库 |
| GetSchemaCassandraDatabaseTool | 获取 Cassandra 架构 |
| GetTableDataCassandraDatabaseTool | 获取 Cassandra 表数据 |
📧 邮件和通讯工具类
|------------------------|------------------------------|
| 工具名称 | 功能 |
| GmailCreateDraft | 创建 Gmail 草稿(需要 API Key) |
| GmailGetMessage | 获取 Gmail 消息(需要 API Key) |
| GmailGetThread | 获取 Gmail 会话(需要 API Key) |
| GmailSearch | 搜索 Gmail(需要 API Key) |
| GmailSendMessage | 发送 Gmail 消息(需要 API Key) |
| O365CreateDraftMessage | 创建 Office 365 草稿(需要 API Key) |
| O365SearchEmails | 搜索 Office 365 邮件(需要 API Key) |
| O365SearchEvents | 搜索 Office 365 事件(需要 API Key) |
| O365SendEvent | 发送 Office 365 事件(需要 API Key) |
| O365SendMessage | 发送 Office 365 消息(需要 API Key) |
| SlackGetChannel | 获取 Slack 频道(需要 API Key) |
| SlackGetMessage | 获取 Slack 消息(需要 API Key) |
| SlackScheduleMessage | 定时发送 Slack 消息(需要 API Key) |
| SlackSendMessage | 发送 Slack 消息(需要 API Key) |
🌐 网页访问类
|-----------------------|-------------------|
| 工具名称 | 功能 |
| RequestsGetTool | 发送 HTTP GET 请求 |
| RequestsPostTool | 发送 HTTP POST 请求 |
| RequestsPutTool | 发送 HTTP PUT 请求 |
| RequestsPatchTool | 发送 HTTP PATCH 请求 |
| RequestsDeleteTool | 发送 HTTP DELETE 请求 |
| NavigateTool | 导航到网页 |
| NavigateBackTool | 返回上一页 |
| ClickTool | 点击网页元素 |
| ExtractTextTool | 提取网页文本 |
| ExtractHyperlinksTool | 提取网页链接 |
| GetElementsTool | 获取网页元素 |
| CurrentWebPageTool | 获取当前网页 |
🎨 语音和图像工具类
|-------------------------------------------|--------------------------------|
| 工具名称 | 功能 |
| AzureCogsFormRecognizerTool | Azure 表单识别(需要 API Key) |
| AzureCogsImageAnalysisTool | Azure 图像分析(需要 API Key) |
| AzureCogsSpeech2TextTool | Azure 语音转文本(需要 API Key) |
| AzureCogsText2SpeechTool | Azure 文本转语音(需要 API Key) |
| AzureCogsTextAnalyticsHealthTool | Azure 医疗文本分析(需要 API Key) |
| AzureAiServicesDocumentIntelligenceTool | Azure 文档智能(需要 API Key) |
| AzureAiServicesImageAnalysisTool | Azure AI 图像分析(需要 API Key) |
| AzureAiServicesSpeechToTextTool | Azure AI 语音转文本(需要 API Key) |
| AzureAiServicesTextToSpeechTool | Azure AI 文本转语音(需要 API Key) |
| AzureAiServicesTextAnalyticsForHealthTool | Azure AI 医疗文本分析(需要 API Key) |
| GoogleCloudTextToSpeechTool | Google Cloud 文本转语音(需要 API Key) |
| ElevenLabsText2SpeechTool | ElevenLabs 文本转语音(需要 API Key) |
| SceneXplainTool | 解释图像(需要 API Key) |
| SteamshipImageGenerationTool | 生成图像(需要 API Key) |
🤖AI服务和集成工具类
|--------------------------------|--------------------------|
| 工具名称 | 功能 |
| EdenAiExplicitImageTool | 检测敏感图像(需要 API Key) |
| EdenAiObjectDetectionTool | 对象检测(需要 API Key) |
| EdenAiParsingIDTool | 解析身份证(需要 API Key) |
| EdenAiParsingInvoiceTool | 解析发票(需要 API Key) |
| EdenAiSpeechToTextTool | 语音转文本(需要 API Key) |
| EdenAiTextModerationTool | 文本审核(需要 API Key) |
| EdenAiTextToSpeechTool | 文本转语音(需要 API Key) |
| EdenaiTool | EdenAI 通用工具(需要 API Key) |
| BearlyInterpreterTool | 代码解释器(需要 API Key) |
| E2BDataAnalysisTool | 数据分析(需要 API Key) |
| ZapierNLAListActions | 列出 Zapier 动作(需要 API Key) |
| ZapierNLARunAction | 运行 Zapier 动作(需要 API Key) |
| CogniswitchKnowledgeRequest | 知识请求(需要 API Key) |
| CogniswitchKnowledgeSourceFile | 知识源文件(需要 API Key) |
| CogniswitchKnowledgeSourceURL | 知识源 URL(需要 API Key) |
| CogniswitchKnowledgeStatus | 知识状态(需要 API Key) |
| ZenGuardTool | ZenGuard 工具(需要 API Key) |
| Detector | 检测器(需要 API Key) |
| ZenGuardInput | ZenGuard 输入(需要 API Key) |
🛠️其他工具类
|------------------------------|-----------------------------------|
| 工具名称 | 功能 |
| HumanInputRun | 获取用户输入 |
| StdInInquireTool | 标准输入询问 |
| ShellTool | 执行 Shell 命令 |
| MerriamWebsterQueryRun | 查询 Merriam-Webster 词典(需要 API Key) |
| OpenWeatherMapQueryRun | 查询天气(需要 API Key) |
| VectorStoreQATool | 向量存储问答 |
| VectorStoreQAWithSourcesTool | 带来源的向量存储问答 |
| BaseGraphQLTool | GraphQL 查询 |
| BaseRequestsTool | HTTP 请求基础工具 |
| BaseSQLDatabaseTool | SQL 数据库基础工具 |
| BaseSparkSQLTool | Spark SQL 基础工具 |
| YahooFinanceNewsTool | Yahoo 财经新闻 |
🎓学术搜索类
|---------------------|-----------------|
| 工具名称 | 功能 |
| ArxivQueryRun | 查询 Arxiv 论文 |
| PubmedQueryRun | 查询 PubMed 医学文献 |
| GoogleBooksQueryRun | 查询 Google Books |
LangChain的工具在langchain-community开发包中,使用前需要先进行安装。
pip install langchain-community
这些工具类采用了继承BaseTool类的方式,相较于@tool装饰器的简洁实现,提供了更精细的控制能力,支持自定义args_schema、详细的name和description属性,以及完整的_run和_arun方法实现,更适合复杂的工具开发场景。
定义完成之后,通过实例化使用,可以直接将实例传递给Agent或Chain进行调用,使用起来既灵活又高效。
import os
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain.chat_models import init_chat_model
from langchain_core.tools import tool, BaseTool
from langchain_community.tools import WriteFileTool, ReadFileTool, ListDirectoryTool
load_dotenv()
prefix = "QWEN"
model = init_chat_model(
model_provider="openai",
configurable_fields=["model", "api_key", "base_url"],
config_prefix=prefix
).with_config({
"configurable": {
f"{prefix}_model": os.getenv(f"{prefix}_MODEL"),
f"{prefix}_api_key": os.getenv(f"{prefix}_API_KEY"),
f"{prefix}_base_url": os.getenv(f"{prefix}_BASE_URL")
}
})
class CalculateTool(BaseTool):
name: str = "calculate"
description: str = "计算数学表达式的值"
def _run(self, expression: str) -> str:
try:
return f"计算结果: {eval(expression)}"
except Exception as e:
return f"计算错误: {str(e)}"
async def _arun(self, expression: str) -> str:
return self._run(expression)
# ========== 初始化工具 ==========
calculate = CalculateTool()
write_file = WriteFileTool()
read_file = ReadFileTool()
list_dir = ListDirectoryTool()
agent = create_agent(
model=model,
tools=[calculate, write_file, read_file, list_dir],
system_prompt="你是一个助手,会用工具计算、读写文件、列出目录。",
debug=True
)
queries = [
"计算 2024*12+500,然后把结果保存到 result.txt",
"读取 result.txt 的内容",
"列出当前目录文件"
]
for q in queries:
print(f"\n问:{q}")
result = agent.invoke({"messages": [{"role": "user", "content": q}]})
print(f"答:{result['messages'][-1].content}")