![[智能体-135]:LangChain 预定义工具:概述、分类、详解与完整使用指南](http://pic.xiahunao.cn/yaotu/[智能体-135]:LangChain 预定义工具:概述、分类、详解与完整使用指南)
一、工具整体概述1. 核心概念在 LangChain 体系中Tool工具是扩展大模型能力的核心组件。大模型本身仅擅长文本生成、逻辑推理无法联网、计算、读写文件、调用接口、执行代码而预定义工具是 LangChain 官方 / 社区封装好、开箱即用的能力单元统一继承基类BaseTool。所有工具具备标准化接口同步执行run(args)异步执行arun(args)自带名称、功能描述Agent 可自动识别、选择、调用2. 两大加载方式手动实例化直接导入工具类创建对象支持精细参数配置适合定制化开发。load_tools快捷加载通过工具别名批量加载一行代码引入多个工具适合快速原型、标准场景。3. 三种使用形态独立调用把工具当普通函数直接执行不依赖 Agent。集成到 AgentAgent 根据用户问题自动判断是否调用、调用哪个工具最主流用法。结合 Toolkit工具集Toolkit一组关联工具打包面向数据库、云服务等复杂场景。4. 前置依赖bash运行pip install langchain langchain-community python-dotenv部分搜索、第三方接口工具需额外配置API Key与环境变量。二、工具通用结构统一规范每个标准工具包含 4 个核心字段也是 Agent 决策的依据name工具唯一名称description工具功能描述决定 Agent 会不会正确调用描述必须精准args_schema入参格式校验_run()同步业务逻辑_arun()异步业务逻辑核心原则工具描述越清晰Agent调用准确率越高。三、分类详解 代码示例主流预定义工具按功能划分为计算类、代码 / 终端类、文件管理类、联网搜索类、知识百科类、HTTP 接口类、数据库工具、人机交互、专业工具集。一数学计算类工具1. Calculator 通用计算器功能解析数学表达式完成四则运算、括号、小数、乘方运算弥补大模型计算精度差的问题。别名llm-math路径langchain_community.tools.calculator.CalculatorTool1.1 独立调用python运行from langchain_community.tools.calculator import CalculatorTool calc CalculatorTool() result calc.run((18 7) * 12 / 4) print(result)1.2 load_tools 加载 Agent 自动调用python运行from langchain_openai import ChatOpenAI from langchain_community.agent_toolkits import load_tools from langchain.agents import AgentExecutor, create_tool_calling_agent from langchain_core.prompts import ChatPromptTemplate from dotenv import load_dotenv load_dotenv() llm ChatOpenAI(temperature0) # 加载计算器工具 tools load_tools([llm-math], llmllm) # 构造提示词与Agent prompt ChatPromptTemplate.from_messages([ (system, 你可以使用计算器完成数学运算), (user, {input}), (placeholder, {agent_scratchpad}) ]) agent create_tool_calling_agent(llm, tools, prompt) agent_executor AgentExecutor(agentagent, toolstools, verboseTrue) # 自动调用工具 agent_executor.invoke({input: 计算 125 * 8 360 / 9})2. WolframAlpha 专业数理工具功能支持高数、微积分、矩阵、物理、化学、单位换算、函数绘图面向专业学术 / 工程计算。路径langchain_community.tools.wolfram_alpha.WolframAlphaQueryRun前置前往官网申请WOLFRAM_ALPHA_APPID示例python运行import os from langchain_community.tools.wolfram_alpha import WolframAlphaQueryRun os.environ[WOLFRAM_ALPHA_APPID] 你的APPID wolf_tool WolframAlphaQueryRun() res wolf_tool.run(求解方程 x² - 5x 6 0) print(res)二代码 终端工具高危生产慎用1. PythonREPL 代码执行器功能内置 Python 交互式环境执行代码、数据处理、批量运算、简单脚本。别名python_repl路径langchain_community.tools.python.tool.PythonREPLTool示例python运行from langchain_community.tools.python import PythonREPLTool py_tool PythonREPLTool() code nums [10,20,30,40] print(sum(nums)) res py_tool.run(code) print(res)⚠️ 安全警告存在代码注入风险线上公开服务必须加沙箱、输入过滤禁止直接暴露。2. Shell 终端命令工具功能执行系统命令查看进程、文件、网络、运维操作。别名terminal路径langchain_community.tools.shell.tool.ShellTool示例python运行from langchain_community.tools.shell import ShellTool shell ShellTool() # Linux/Mac res shell.run(ls -l) # Windows 使用 res shell.run(dir) print(res)⚠️ 高危工具可删除文件、篡改系统生产环境严格禁用。三文件管理工具集统一路径langchain_community.tools.file_management包含读、写、遍历目录、删除、复制、移动文件共 6 个工具。表格工具类功能ReadFileTool读取本地文件WriteFileTool新建 / 覆盖写入文件ListDirectoryTool列出目录内容DeleteFileTool删除文件完整示例python运行from langchain_community.tools.file_management import ( ReadFileTool, WriteFileTool, ListDirectoryTool ) # 1. 写入文件 write_tool WriteFileTool() write_tool.run(file_pathdemo.txt, textLangChain 文件工具测试内容) # 2. 读取文件 read_tool ReadFileTool() content read_tool.run(file_pathdemo.txt) print(文件内容, content) # 3. 遍历当前目录 list_tool ListDirectoryTool() files list_tool.run(directory.) print(目录列表, files)适用场景文档解析、日志读取、AI 生成内容落地存本地。四联网搜索工具最常用信息检索1. DuckDuckGoSearch 免费搜索推荐中文场景特点无需 API Key、完全免费通用网页搜索开箱即用。别名duckduckgo_search路径langchain_community.tools.duckduckgo_search.DuckDuckGoSearchRun示例python运行from langchain_community.tools.duckduckgo_search import DuckDuckGoSearchRun search DuckDuckGoSearchRun() res search.run(LangChain 工具使用教程) print(res)2. TavilySearch AI 优化搜索特点专为大模型优化摘要精准、相关性高有免费额度企业场景首选。路径langchain_community.tools.tavily_search.TavilySearchResults前置配置TAVILY_API_KEY示例python运行import os from langchain_community.tools.tavily_search import TavilySearchResults os.environ[TAVILY_API_KEY] 你的Tavily密钥 # max_results控制返回条数 tavily TavilySearchResults(max_results3) res tavily.run(艾莫迅 AMX-MT043 HMI 参数) print(res)3. SerpAPI / Google 搜索对接谷歌、百度等搜索引擎需付费 Key。别名serpapi五百科 学术知识工具1. Wikipedia 维基百科功能查询名词、概念、历史、技术释义支持多语言。别名wikipedia路径langchain_community.tools.wikipedia.WikipediaQueryRun示例python运行from langchain_community.tools.wikipedia import WikipediaQueryRun from langchain_community.utilities import WikipediaAPIWrapper # 设置中文 api_wrapper WikipediaAPIWrapper(top_k_results1, langzh) wiki WikipediaQueryRun(api_wrapperapi_wrapper) res wiki.run(大语言模型) print(res)2. Arxiv 学术论文搜索功能检索 arXiv 预印本论文、摘要、作者、分类科研场景常用。别名arxivpython运行from langchain_community.tools.arxiv import ArxivQueryRun arxiv ArxivQueryRun() res arxiv.run(large language model agent) print(res)六HTTP 请求工具功能发送标准 HTTPGET/POST/PUT/DELETE请求调用第三方 REST API。路径langchain_community.tools.requests.tool示例GET 请求python运行from langchain_community.tools.requests.tool import RequestsGetTool get_tool RequestsGetTool() res get_tool.run(urlhttps://httpbin.org/get) print(res)七人机交互工具HumanInputRun 人工问询工具功能Agent 运行中暂停向终端用户提问、获取人工输入实现人机协同。别名humanpython运行from langchain_community.tools.human import HumanInputRun human HumanInputRun() res human.run(请输入你的需求) print(用户输入, res)八工具批量加载load_tools 综合示例一次性加载多个常用工具快速构建多功能 Agentpython运行from dotenv import load_dotenv from langchain_openai import ChatOpenAI from langchain_community.agent_toolkits import load_tools from langchain.agents import AgentExecutor, create_tool_calling_agent from langchain_core.prompts import ChatPromptTemplate load_dotenv() llm ChatOpenAI(temperature0) # 批量加载计算器、搜索、Python代码、维基百科 tool_list [llm-math, duckduckgo_search, python_repl, wikipedia] tools load_tools(tool_list, llmllm) prompt ChatPromptTemplate.from_messages([ (system, 根据问题选择合适工具完成任务), (user, {input}), (placeholder, {agent_scratchpad}) ]) agent create_tool_calling_agent(llm, tools, prompt) agent_executor AgentExecutor(agentagent, toolstools, verboseTrue) # 综合任务搜索计算 agent_executor.invoke({input: 搜索LangChain介绍并计算 45 * 28})四、Toolkit 工具集组合式工具Toolkit 是一组关联工具的集合面向复杂场景典型代表1. SQLDatabaseToolkit打包了「查询表结构、执行 SQL、检查表语法」等工具用于数据库问答。python运行from langchain_community.utilities import SQLDatabase from langchain_community.agent_toolkits import SQLDatabaseToolkit # 连接数据库 db SQLDatabase.from_uri(sqlite:///test.db) toolkit SQLDatabaseToolkit(dbdb, llmllm) tools toolkit.get_tools()2. 其他常用 ToolkitSlack Toolkit消息、群组、文件操作GitHub Toolkit代码仓库、Issue、提交查询Notion Toolkit文档读写、页面管理五、使用规范、安全与选型建议1. 选型原则纯计算 →llm-math专业数理 / 公式 →WolframAlpha数据处理、批量逻辑 →python_repl查资料、新闻、常识 →DuckDuckGo / Tavily概念释义 →Wikipedia本地文档操作 → 文件管理工具对接第三方接口 →Requests工具2. 安全红线生产必看高危工具PythonREPL、Shell、文件删除 / 写入公网服务必须限制。密钥管理搜索、第三方工具的 API Key 统一放入.env禁止硬编码。输入过滤对工具入参做清洗防止注入攻击。权限隔离文件、终端工具最小权限运行。3. 调优技巧工具description写得越具体Agent 调用准确率越高。控制搜索类工具max_results避免返回内容过长溢出上下文。工具过多时拆分 Agent 或使用路由分发减少决策混乱。六、总结LangChain 预定义工具是大模型能力的外延补齐模型无法联网、运算、操作本地资源的短板。用法分为独立调用、批量加载、Agent 自动调用三种日常优先使用load_tools快速开发。按场景分类选择工具高危工具严格管控权限是工程落地的关键。复杂业务优先使用Toolkit工具集简化多工具协同开发。