搭建AI应用-Dify插件开发入门

张开发
2026/4/15 9:38:24 15 分钟阅读

分享文章

搭建AI应用-Dify插件开发入门
可以使用python和go语言开发dify插件本文主要针对windows环境下使用python语言开发。一开发环境准备‌1.安装依赖工具‌Docker desktopGitPython ≥ 3.12推荐使用 pyenv 或虚拟环境2.下载dify-plugin工具https://github.com/langgenius/dify-plugin-daemon/releases下载完成后把dify-plugin-windows-amd64.exe文件复制到插件开发目录如D:\dify-plugincdD:\dify-plugin3.验证dify-plugin工具D:\dify-plugindify-plugin-windows-amd64.exe version v0.5.6二创建插件项目按照提示进行填写D:\dify-plugindify-plugin-windows-amd64.exe plugin init Select thetypeof plugin you want to create, and pressEntertocontinueEdit minimal Dify version requirement, leave it blank by default Minimal Dify version(press Enter to next step):1.0.02026/04/0112:00:00 INFO plugin created successfullynamehello_worldguidehello_world/GUIDE.mdPlugin name‌插件唯一标识如hello_world‌Author‌插件作者‌Description‌功能简述‌Language‌选择 PythonType‌选择 ToolAdditional Features‌按需勾选如 Provider 验证、持久存储等生成的代码结构hello_world/ ├── _assets/ # 图标资源 ├── provider/ # 凭证配置如需 ├── tools/ # 核心工具实现 ├── .difyignore # 类似.gitignore指定Dify平台忽略的文件 ├── .env.example # 环境变量示例文件(不含敏感值) ├── .gitignore # Git版本控制忽略规则 ├── GUIDE.md # 项目使用指南文档 ├── main.py # 应用主入口文件 ├── manifest.yaml # 项目清单文件(定义应用元数据/依赖等) ├── PRIVACY.md # 隐私政策说明文档 ├── README.md # 项目说明文档 └── requirements.txt # Python依赖包清单文件创建虚拟环境(python)python-mvenv venv‌三、插件逻辑实现‌新增工具tool1tools/tool1.pyfromcollections.abcimportGeneratorfromtypingimportAnyfromdify_pluginimportToolfromdify_plugin.entities.toolimportToolInvokeMessageclasstool1Tool(Tool):def_invoke(self,tool_parameters:dict[str,Any])-Generator[ToolInvokeMessage]:print(tool_parameters[query])resulttool_parameters[query]yieldself.create_json_message({result:tool1, result})tools/tool1.yamlidentity:name:tool1author:The idea of riding a donkeylabel:en_US:tool1zh_Hans:tool1pt_BR:tool1ja_JP:tool1description:human:en_US:tool1zh_Hans:tool1pt_BR:tool1ja_JP:tool1llm:tool1parameters:-name:querytype:string required:true label:en_US:Query string zh_Hans:查询语句 pt_BR:Query string ja_JP:クエリ文字列 human_description:en_US:tool1zh_Hans:tool1pt_BR:tool1ja_JP:tool1llm_description:tool1form:llm extra:python:source:tools/tool1.py‌新增工具tool2tools/tool2.pyfromcollections.abcimportGeneratorfromtypingimportAnyfromdify_pluginimportToolfromdify_plugin.entities.toolimportToolInvokeMessageclasstool2Tool(Tool):def_invoke(self,tool_parameters:dict[str,Any])-Generator[ToolInvokeMessage]:print(tool_parameters[query])resulttool_parameters[query]yieldself.create_json_message({result:tool2, result})tools/tool2.yamlidentity:name:tool2author:The idea of riding a donkeylabel:en_US:tool2zh_Hans:tool2pt_BR:tool2ja_JP:tool2description:human:en_US:tool2zh_Hans:tool2pt_BR:tool2ja_JP:tool2llm:tool2parameters:1.name:querytype:string required:true label:en_US:Query string zh_Hans:查询语句 pt_BR:Query string ja_JP:クエリ文字列 human_description:en_US:tool2zh_Hans:tool2pt_BR:tool2ja_JP:tool2llm_description:tool2form:llm extra:python:source:tools/tool2.py主服务接口实现provider/hello.pyfromtypingimportAnyfromdify_pluginimportToolProviderfromdify_plugin.errors.toolimportToolProviderCredentialValidationErrorclassHelloProvider(ToolProvider):def_validate_credentials(self,credentials:dict[str,Any])-None:try: IMPLEMENT YOUR VALIDATION HERE exceptExceptionase:raiseToolProviderCredentialValidationError(str(e))########################################################################################## If OAuth is supported, uncomment the following functions.# Warning: please make sure that the sdk version is 0.4.2 or higher.########################################################################################## def _oauth_get_authorization_url(self, redirect_uri: str, system_credentials: Mapping[str, Any]) - str:# # Generate the authorization URL for hello OAuth.# # try:# # IMPLEMENT YOUR AUTHORIZATION URL GENERATION HERE# # except Exception as e:# raise ToolProviderOAuthError(str(e))# return # def _oauth_get_credentials(# self, redirect_uri: str, system_credentials: Mapping[str, Any], request: Request# ) - Mapping[str, Any]:# # Exchange code for access_token.# # try:# # IMPLEMENT YOUR CREDENTIALS EXCHANGE HERE# # except Exception as e:# raise ToolProviderOAuthError(str(e))# return dict()# def _oauth_refresh_credentials(# self, redirect_uri: str, system_credentials: Mapping[str, Any], credentials: Mapping[str, Any]# ) - OAuthCredentials:# # Refresh the credentials# # return OAuthCredentials(credentialscredentials, expires_at-1)provider/hello.yamlidentity:author:lishiwen2name:hellolabel:en_US:hellozh_Hans:hellopt_BR:helloja_JP:hellodescription:en_US:hellozh_Hans:hellopt_BR:helloja_JP:helloicon:icon.svg########################################################################################## If you want to support OAuth, you can uncomment the following code.########################################################################################## oauth_schema:# client_schema:# - name: client_id# type: secret-input# required: true# url: https://example.com/oauth/authorize# placeholder:# en_US: Please input your Client ID# zh_Hans: 请输入你的 Client ID# pt_BR: Insira seu Client ID# help:# en_US: Client ID is used to authenticate requests to the example.com API.# zh_Hans: Client ID 用于认证请求到 example.com API。# pt_BR: Client ID é usado para autenticar solicitações à API do example.com.# label:# zh_Hans: Client ID# en_US: Client ID# - name: client_secret# type: secret-input# required: true# url: https://example.com/oauth/authorize# placeholder:# en_US: Please input your Client Secret# zh_Hans: 请输入你的 Client Secret# pt_BR: Insira seu Client Secret# help:# en_US: Client Secret is used to authenticate requests to the example.com API.# zh_Hans: Client Secret 用于认证请求到 example.com API。# pt_BR: Client Secret é usado para autenticar solicitações à API do example.com.# label:# zh_Hans: Client Secret# en_US: Client Secret# credentials_schema:# - name: access_token# type: secret-input# label:# zh_Hans: Access Token# en_US: Access Tokentools:1.tools/tool1.yaml2.tools/tool2.yaml extra:python:source:provider/hello.py安装依赖requirements.txt增加dify_plugin0.4.0,0.7.0pipinstall-r.\requirements.txt完整代码目录project_root/ ├── _assets/ # 静态资源目录 │ ├── icon-dark.svg # 深色模式下的应用图标(SVG格式) │ └── icon.svg # 默认应用图标(SVG格式) ├── .venv/ # Python虚拟环境目录(用于依赖隔离) ├── .vscode/ # VSCode编辑器配置目录 │ ├── settings.json # 工作区设置 │ └── extensions.json # 推荐插件配置 ├── provider/ # 核心服务提供模块 │ ├── hello.py # 主服务接口实现(Python) │ └── hello.yaml # 服务配置文件(定义API端点/参数等) └── tools/ # 工具模块目录 │ ├── tool1.py # 工具1功能实现(Python) │ ├── tool1.yaml # 工具1配置文件(定义工具元数据/参数) │ ├── tool2.py # 工具2功能实现(Python) │ └── tool2.yaml # 工具2配置文件(定义工具元数据/参数) ├── .difyignore # 类似.gitignore指定Dify平台忽略的文件 ├── .env # 环境变量配置文件(包含敏感信息) ├── .env.example # 环境变量示例文件(不含敏感值) ├── .gitignore # Git版本控制忽略规则 ├── GUIDE.md # 项目使用指南文档 ├── main.py # 应用主入口文件 ├── manifest.yaml # 项目清单文件(定义应用元数据/依赖等) ├── PRIVACY.md # 隐私政策说明文档 ├── README.md # 项目说明文档 └── requirements.txt # Python依赖包清单文件四本地运行与调试复制创建.envcopy .env.example .env修改.env文件INSTALL_METHODremote#以下信息从dify平台工具-插件-调试出获取REMOTE_INSTALL_URLlocalhost:5003#你的dify调试urlREMOTE_INSTALL_KEYxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxx#你的dify调试key启动插件服务python-mmaindify平台调试插件五插件打包dify-plugin-windows-amd64.exe plugin package 插件名称D:\dify-plugindify-plugin-windows-amd64.exe plugin package hello_world2026/04/0112:10:00 INFO plugin packaged successfullyoutput_pathhello_world.difypkg六打包签名openssl方式# 生成签名密钥对openssl genrsa-outprivate.pem2048openssl rsa-inprivate.pem-pubout-outpublic.pem# 打包时指定私钥dify-cli plugin pack ./your_plugin--keyprivate.pemdify-plugin方式# 生成秘钥dify-plugin-windows-amd64.exe signature generate-f秘钥名称# 打包项目dify-plugin-windows-amd64.exe plugin package 项目名称# 使用秘钥签名dify-plugin-windows-amd64.exe signature sign 包名称.difypkg-p秘钥.private.pem

更多文章