iT邦幫忙

2025 iThome 鐵人賽

DAY 16
0

在 Dify 先建立 AI 聊天助手

1. 建立應用與設定 Prompt

  1. 登入 Dify 平台。
  2. 點左上角 新建應用程式 (Create App) 選擇 聊天助手 (Chatbot)
  3. 輸入名稱(例:n8n 測試助手) 點 建立
  4. 在左側選單 $\rightarrow$ 提示詞 (Prompt) 設定頁,設定 AI 的人設。

2. 獲取 API 金鑰

  1. 在左側選單 $\rightarrow$ API 金鑰 (API Keys)
  2. 生成 API 金鑰 $\rightarrow$ 複製這組金鑰(這就是後面 n8n 呼叫 Dify 服務的 Authorization 憑證)。

Part 2:在 n8n 建立串接流程

1. Webhook 節點 (接收請求)

  1. 新增 Webhook 節點。
  2. 設定:
    • HTTP MethodPOST
    • Pathdify-test
    • RespondWhen Last Node Finishes (確保 AI 回覆後才回傳)
    • Response DataFirst Incoming Item
    • (測試網址:http://localhost:5678/webhook-test/dify-test)

2. HTTP Request 節點 (呼叫 Dify API)

  1. 新增 HTTP Request 節點,連接在 Webhook 後面。
  2. 設定:
    • MethodPOST
    • URLhttps://api.dify.ai/v1/chat-messages
    • Headers
      • Content-Type = application/json
      • Authorization = Bearer 你的Dify API金鑰 (替換成 Part 1 複製的金鑰)
    • Body Content TypeJSON
    • JSON Body
      {
        "inputs": {},
        "query": "={{$json["message"]}}", 
        "response_mode": "blocking",
        "user": "api-user"
      }
      
      • 注意"={{$json["message"]}}" 是 n8n 的表達式,用於動態擷取 Webhook 傳入的 JSON 數據中的 message 欄位
    • (💡 截圖點:HTTP Request 節點的 Header 和 JSON Body)

3. Set 節點 (抽取 AI 回覆)

  1. 新增 Set 節點。
  2. 設定:
    • ModeJSON
    • JSON Body
      {
        "reply": "={{$json["answer"] || $json["outputs"][0]["content"] || $json["data"]}}"
      }
      

4. Respond to Webhook 節點 (回傳結果)

  1. 新增 Respond to Webhook 節點。
  2. 設定:
    • Respond WithFirst Incoming Item (會把 Set 節點輸出的 JSON {"reply":"..."} 回傳給呼叫者)。

Part 3:啟用 Workflow 與 PowerShell 測試

1. 啟用 Workflow

2. PowerShell 測試 (帶 UTF-8 編碼)

啟用 Workflow 後,使用 PowerShell 執行 POST 請求,將帶有中文的 JSON ({"message": "今天天氣怎樣"}) 傳給 Webhook。

Invoke-RestMethod -Uri "http://localhost:5678/webhook-test/dify-test" `
  -Method POST `
  -Headers @{ "Content-Type" = "application/json; charset=utf-8" } `
  -Body (@{ message = "今天天氣怎樣" } | ConvertTo-Json -Depth 3 -Compress)

先暫時更新,最後會補圖。


上一篇
Day 15 : API 串接失敗學習紀錄
下一篇
Day 17
系列文
從零開始 : 學習運用 n8n 與 Dify 的 AI 自動化實戰21
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言