Difyのチャットフローにサーバ側からAPIリクエストでテストしたい

node.js

const DIFY_API_KEY = "";
const WORKFLOW_ID = "";

// APIエンドポイントのURL
const url = "https://api.dify.ai/v1/chat-messages";

// APIリクエストの実行
async function runDifyChat() {
  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "Authorization": `Bearer ${DIFY_API_KEY}` // APIキーをAuthorizationヘッダーに設定
      },
      body: JSON.stringify({
        "inputs": {}, // 必要に応じて入力データを設定
        "query": "Node.jsでAPIリクエストを送る方法を教えてください。", // ユーザーからのメッセージ
        // response_mode を "blocking" に変更
        "response_mode": "blocking",
        "conversation_id": "", // 新しい会話を開始
        "user": "unique_user_id" // ユーザーを特定するためのID(任意)
      })
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`API Error: ${response.status} - ${JSON.stringify(errorData)}`);
    }

    // blockingモードなら、response.json() で直接パースできる
    const data = await response.json();
    console.log("APIレスポンス:", data);

  } catch (error) {
    console.error("エラーが発生しました:", error);
  }
}

// 関数を実行
runDifyChat();

$ node chat.js
APIレスポンス: {
event: ‘message’,
task_id: ’52ba8605-bac3-46b4-a0aa-5958079a3d01′,
id: ‘d858017a-052d-4a1b-86eb-da673707423e’,
message_id: ‘d858017a-052d-4a1b-86eb-da673707423e’,
conversation_id: ’37feb5fc-5694-48ae-ab86-e45fae25aaa9′,
mode: ‘advanced-chat’,
answer: ‘まずは「axios」というライブラリを用いると良い。以下のコードを参考にせんといかん。\n’ +
‘“`javascript\n’ +
“const axios = require(‘axios’);\n” +
“axios.get(‘APIのURL’)\n” +
‘ .then(response => {\n’ +
‘ console.log(response.data);\n’ +
‘ })\n’ +
‘ .catch(error => {\n’ +
‘ console.error(error);\n’ +
‘ });\n’ +
‘“`\n’ +
‘上記はGETリクエストの例で、POSTリクエストを送る際は`axios.get`の部分を`axios.post`に変え、第二引数に送りたいデータをオブジェクトとして渡せばよい。’,
metadata: {
annotation_reply: null,
retriever_resources: [ [Object], [Object], [Object] ],
usage: {
prompt_tokens: 2379,
prompt_unit_price: ‘0.03’,
prompt_price_unit: ‘0.001’,
prompt_price: ‘0.049953’,
completion_tokens: 206,
completion_unit_price: ‘0.06’,
completion_price_unit: ‘0.001’,
completion_price: ‘0.0091425’,
total_tokens: 2585,
total_price: ‘0.0590955’,
currency: ‘USD’,
latency: 2.760161219164729
}
},
created_at: 1757759242
}