必须通过自定义工具实现ai智能体调用内部系统,需安装dify插件cli、初始化工具项目、编写继承tool类的逻辑与参数定义、打包上传并启用,最后在agent中添加配置与测试。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 多模态理解力帮你轻松跨越从0到1的创作门槛☜☜☜

要在 Dify 中让 AI 智能体具备调用内部系统、执行数据库查询或触发业务流程的能力,必须通过自定义工具(Tools)实现——这一步不是可选项,而是打通 AI 与真实业务系统的必经路径。
准备开发环境与插件脚手架
先确认本地已安装 Python 3.12+,并建议使用虚拟环境隔离依赖。打开终端,运行以下命令安装 Dify 官方插件开发 CLI 工具:
curl -L https://github.com/langgenius/dify-plugin-cli/releases/download/v0.0.1-beta.15/dify-plugin-darwin-arm64 -o dify-plugin && chmod +x dify-plugin
macOS 用户下载的是 darwin-arm64 版本;Windows 用户请替换为 dify-plugin-windows-amd64。安装后执行 【./dify-plugin version】,输出 v0.0.1-beta.15 才代表环境就绪。若提示 command not found,请检查当前目录是否包含该二进制文件,或将其移至 /usr/local/bin 并重命名为 dify-plugin。
初始化并构建工具插件项目
运行命令创建新插件:
./dify-plugin plugin init
按提示输入插件名称(如 hr-leave-tool)、作者名、描述,并选择类型为 tool。脚手架将生成标准结构:
my-tool/
├── main.py
├── manifest.yaml
├── tools/
│ └── hr_leave.py
├── provider/
└── requirements.txt
【tools/hr_leave.py 必须继承 Tool 类并实现 _invoke 方法】,否则 Dify 后台无法识别该工具逻辑。manifest.yaml 中的 id 字段需全局唯一,重复会导致插件上传失败。
编写工具逻辑与参数定义
在 tools/hr_leave.py 中写入实际调用逻辑。例如对接企业请假审批 API:
from dify_plugin import Tool, ToolInvokeError
import requests
class HrLeaveTool(Tool):
def _invoke(self, tool_parameters: dict) -> str:
try:
employee_id = tool_parameters.get("employee_id")
days = int(tool_parameters.get("days", 1))
reason = tool_parameters.get("reason", "事假")
resp = requests.post(
"https://api.hr-system.internal/v1/leave",
json={"employee_id": employee_id, "days": days, "reason": reason},
timeout=10
)
resp.raise_for_status()
return self.create_text_message(f"请假申请已提交,单号:{resp.json()['apply_id']}")
except requests.exceptions.Timeout:
raise ToolInvokeError("审批系统超时,请稍后重试")
except Exception as e:
raise ToolInvokeError(f"调用失败:{str(e)}")
接着,在同级目录下新建 tools/hr_leave.yaml,定义前端可见参数:
name: 请假申请
description: 提交员工请假申请,需提供工号、天数和原因
parameters:
- name: employee_id
type: string
required: true
description: 员工唯一工号
- name: days
type: number
required: true
description: 请假天数,必须为正整数
- name: reason
type: string
required: false
description: 请假事由,默认为“事假”
打包上传并启用工具
第一步:进入插件根目录,执行打包命令:
./dify-plugin plugin build
成功后生成 dist/my-tool-0.1.0.tar.gz 文件。第二步:登录 Dify 控制台 → 左侧菜单点击「工具」→ 右上角「上传插件」→ 选择刚生成的 tar.gz 文件。第三步:上传完成后,页面自动跳转至工具详情页,点击「启用」开关。此时工具状态变为「已启用」,但尚未绑定到任何 Agent。
注意:上传前请确保 manifest.yaml 中的 version 字段为语义化版本(如 0.1.0),Dify 不接受 version: "dev" 或空值。
在 Agent 中添加并测试工具
① 新建或编辑一个 Agent → 进入「工具」配置页 → 点击「添加工具」→ 在列表中勾选刚启用的「请假申请」→ 保存配置。
② 编写系统提示词,明确告知模型何时调用该工具,例如:“当用户提出请假请求且提供工号时,必须调用请假申请工具,不得自行编造审批结果。”
③ 在调试窗口输入测试语句:“我工号 HR2026001,想请3天年假,原因是陪家人看病。”
④ 观察日志:若看到 [Tool Call] hr_leave → {employee_id: "HR2026001", days: 3, reason: "陪家人看病"},说明工具已正确触发并返回结果。











