選單
GSS 技術部落格
在這個園地裡我們將從技術、專案管理、客戶對談面和大家分享我們多年的經驗,希望大家不管是喜歡或是有意見,都可以回饋給我們,讓我們有機會和大家對話並一起成長!
若有任何問題請來信:gss_crm@gss.com.tw

如何使用 Dify 和 Python 來建立 Plugin,產生訊息及檔案

如何使用 Dify 和 Python 來建立 Plugin,產生訊息及檔案

Dify 是非常受歡迎的 LLM 應用平台之一。
本篇將依照 Dify 官方文件「Dify 插件开发:Hello World 指南」內容,帶大家手把手寫出一個 Plugin,並實作讓 Plugin 產生 text、json 及 files 格式的回應!

實作

1.環境準備

  • 需要 Python 3.12 或更高的版本,請執行 python3 --version 來檢查
  • dify-plugin-daemon 依 OS 環境來下載 Dify Plugin CLI 執行檔
    • macOS/Linux 要設定允許執行權限 chmod +x {檔案名}
    • 把下載的執行檔,改名成 dify

2.建立 Plugin

(1).開啟命令視窗,執行初始化

./dify plugin init

設定名稱為echo

語言選擇python
template 選擇tool
權限的話,按Tab來啟用Tools

Minimal Dify version 如果沒有特別需求,這裡可以直接按 Enter 跳過

這樣 Dify Plugin CLI 就會為我們建立一個 echo 目錄。接著,使用 VS Code 開啟 echo 目錄。

(2).建立 Python 虛擬環境
在 VS Code 中,開啟 Terminal (在 echo 目錄),輸入 python3 -m venv venv

(3).啟動虛擬環境

  • macOS / Linux:

source venv/bin/activate

  • Windows (cmd.exe):

venv\Scripts\activate.bat

(4).安裝需要的套件
範本會將預設需要的套件寫在requirements.txt中,未來如果有需要其他套件,再自行加入。

pip install -r requirements.txt

(5).Plugin Tool 說明
echo.py預設會直接回傳 JSON 訊息(使用self.create_json_message方法)

class EchoTool(Tool):
def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage]:
yield self.create_json_message({
"result": "Hello, world!"
})

echo.yaml定義這個工具的相關資訊,預設有一個query的必填參數

parameters:
- name: query
type: string
required: true
label:
en_US: Query string
zh_Hans: 查询语句
pt_BR: Query string
human_description:
en_US: echo input
zh_Hans: echo input
pt_BR: echo input
llm_description: echo input
form: llm

(6).設定 Debug 環境
(6.1).將檔案.env.example複制為.env
(6.2).連到 Dify 系統,點選外掛 (https://yourdifyurl/plugins), 點擊蟲蟲圖示的按鈕
(6.3).將URLKey的值貼到.env中的REMOTE_INSTALL_URLREMOTE_INSTALL_KEY

註:如果 Dify URL 與 Plugin Debug URL 不同,可以調整EXPOSE_PLUGIN_DEBUGGING_HOST環境變數

(7).Debug 安裝 Plugin
.env設定完成後,在 Terminal 視窗中輸入python -m main按下 Enter,這時會出現以下的錯誤,

Traceback (most recent call last):
File "venv/lib/python3.13/site-packages/dify_plugin/core/plugin_registration.py", line 106, in _load_plugin_configuration
self.configuration = PluginConfiguration(**file)
~~~~~~~~~~~~~~~~~~~^^^^^^^^
File "venv/lib/python3.13/site-packages/pydantic/main.py", line 253, in __init__
validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
pydantic_core._pydantic_core.ValidationError: 1 validation error for PluginConfiguration
resource.permission.storage.size
Input should be greater than or equal to 1024 [type=greater_than_equal, input_value=0, input_type=int]
For further information visit https://errors.pydantic.dev/2.11/v/greater_than_equal

主要就是因為manifest.yaml中的storage它的size值為所致,將size的值改成1024,再執行一次python -m main,如果出現以下訊息表示 Plugin 已經裝到 Dify Server 上了

{“event”: “log”, “data”: {“level”: “INFO”, “message”: “Installed tool: echo”, “timestamp”: 1749434984.628976}}
INFO:dify_plugin.plugin:Installed tool: echo

重整 Browser 頁面,可以發現 echo 已被安裝上去,下面有個DEBUGGING PLUGIN,如下圖:

(8).Debug Plugin
到 Workflow 中,加入 echo plugin 這個 tool 並進行測試,如下圖:

query參數給abc,會輸出以下的 json 內容,

所以工具可以輸出 text, files & json 的內容(目前工具僅回傳 json 欄位)。

到這裡已經完成從建立 Plugin 到部署到 Dify Server 的 Debug,如果 Debug 沒有問題的話就可以進行打包的工作。

(9).打包 Plugin
Control + C,結束 Debug,切到上層目錄,透過dify plugin package來打包 Plugin

cd ..
dify plugin package ./echo

它會產生echo.difypkg

(10).安裝外掛程式
連到 Dify 系統,點選外掛(https://yourdifyurl/plugins),點擊安裝外掛程式圖示的 Button,選取本地包檔,然後選擇echo.difypkg來安裝 Plugin

如果有PluginDaemonBadRequestError: plugin verification has been enabled, and the plugin you want to install has a bad signature的錯誤,解法請參考第三方签名验证

3.讓 Plugin 支援多格式回傳(Text、JSON、File)

學會基本 Plugin 實作後,我們可以擴展功能,讓 Plugin 能同時回傳 text、json、file 三種格式。
修改 tools/echo.py

from collections.abc import Generator
from typing import Any

from dify_plugin import Tool
from dify_plugin.entities.tool import ToolInvokeMessage

class EchoTool(Tool):
def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage]:
query_str = tool_parameters['query']
echo_str = f"Echo: {query_str}"
echo_barray = echo_str.encode('utf-8')
yield self.create_json_message({
"result": echo_str
})
yield self.create_text_message(echo_str)
yield self.create_blob_message(
blob=echo_barray,
meta={
"mime_type": "text/plain",
"filename": "echo.txt",
}
)

  • create_json_message 回傳 json
  • create_text_message 回傳文字
  • create_blob_message 回傳檔案

完成後,在 echo 目錄中的 Terminal 視窗中輸入python -m main來進行 Debug 安裝。
到 Dify 中建立聊天流(開始->echo->直接回覆)來進行測試,
將 sys.query 給 echo Tool 的 query

直接回覆的回覆內容分別輸出 text, json 及 file

Text:
{{#1749446615792.text#}}
=================
Json:
{{#1749446615792.json#}}
=================
Files:
{{#1749446615792.files#}}
=================

json 及 files 請先 copy Text 出來後,將 text 改成 json or files ,例如 {{#1749446615792.json#}}

測試後在聊天流設定(開始 → echo → 直接回覆),可以看到三種格式的回覆:

完成後,離開虛擬環境可執行 deactivate

4.進階應用:Excel 與 JSON 轉換 Plugin

有了前述多格式回傳的基礎,我們可以進一步設計更實用的 Plugin。
例如,想將 JSON 字串轉為 Excel 檔案,只需用 pandas 讀取 json 並轉出 Excel,即可回傳成 file 給 Dify 聊天流。

參考:Dify Json to Excel Plugin

結論

本篇從開發環境準備、Plugin 建立、Debug 測試、打包安裝到如何擴展回傳內容(text、json、file),完整展示了如何用 Dify 與 Python 實作一個專屬 Plugin。對於想要讓自家 LLM 具備更多自訂功能的工程師來說,Dify Plugin 是一個高擴展性且門檻低的選擇。

你可以從簡單的 Echo Tool 開始練習,逐步延伸出如 Json/Excel 轉換等更實用的插件。
只要配合官方的 Plugin CLI 與範本,無論是測試或實際上線都非常高效穩定。如果遇到簽章驗證等問題,也能參考文件快速排除。
未來如果有更多串接第三方 API、資料轉換或自動化需求,都能以 Plugin 方式靈活擴展 Dify 的應用!

參考資源

Dify 插件开发:Hello World 指南
Dify Json to Excel Plugin

從風口到落地:IT人該如何看待技術熱潮?

相關文章

 

評論

尚無評論
已經注冊了? 這裡登入
Guest
2025/06/09, 週一

Captcha 圖像