0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[テスト自動化] Dify APIとNode.jsで複数質問の出力をテキストに保存する

Posted at

Difyのテストを簡略化するため、Node.jsで複数の質問のテスト出力をテキストファイルに保存するスクリプトを書いた。例えば、50個の入力を用意し、今までプレビュー画面等で一個一個手作業で出力テストを行なっていたものをコマンド一つで50個一気に出力できるようになる。

Dify

感情分類器を入れた単純なフロー図である
スクリーンショット 2025-09-14 午前7.14.11.png

API シークレットキー

Difyレフトメニューの[APIアクセス]から、APIページに移動し、右上のAPIキーからAPIシークレットキーを取得する
スクリーンショット 2025-09-14 午前7.14.31.png

Node.js

node.js
import fs from "fs";
import fetch from "node-fetch";

const DIFY_API_KEY = "app-*";
const API_URL = "https://api.dify.ai/v1/chat-messages";

// テキストファイルから質問を読み込む
const prompts = fs
  .readFileSync("./prompts.txt", "utf8")
  .split("\n")
  .map((line) => line.trim())
  .filter(Boolean);

// Difyに問い合わせる関数
async function callDify(prompt) {
  const response = await fetch(API_URL, {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${DIFY_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      inputs: {},
      query: prompt,
      response_mode: "blocking",
      conversation_id: "",
      user: "cli-user",
    }),
  });

  if (!response.ok) {
    const err = await response.text();
    throw new Error(`API Error ${response.status}: ${err}`);
  }

  const data = await response.json();
  return data.answer || "(No answer)";
}

// メイン処理
(async () => {
  const results = [];
  results.push("=== 質問と回答 ===\n");

  for (const [i, prompt] of prompts.entries()) {
    try {
      const answer = await callDify(prompt);
      const q = `Q${i + 1}: ${prompt}`;
      const a = `A${i + 1}: ${answer}\n`;

      // CLIに出力
      console.log(q);
      console.log(a);

      // ファイル保存用にも追加
      results.push(q, a);
    } catch (err) {
      const e = `Error for "${prompt}": ${err.message}`;
      console.error(e);
      results.push(e);
    }
  }

  // ファイルに保存
  fs.writeFileSync("results.txt", results.join("\n"), "utf8");
  console.log("\n=== 回答を results.txt に保存しました ===");
})();

用意する質問

prompt.txt

Node.jsでAPIリクエストを送る方法を教えてください。
ReactとVueの違いは何ですか?
GPTとBERTの違いを説明してください。

出力結果

results.txt

=== 質問と回答 ===

Q1: Node.jsでAPIリクエストを送る方法を教えてください。
A1: うむ、それは簡単じゃ。まず、"axios"というライブラリをインストールせんとな。次に「axios.get("リクエスト先のURL")」というコードを書く。これでAPIにリクエストを送れるぞ。

Q2: ReactとVueの違いは何ですか?
A2: ふむ、ReactとVueか。ReactはFacebook製で大規模開発に向いており、Vueはやさしく始められる。しかし、どちらも優れたツールだ。お主が何を求めているか、それによる。

Q3: GPTとBERTの違いを説明してください。
A3: うむ、そなたが知識を求める姿勢は評価するぞ。GPTとは文章を生成するためのモデルで、一方、BERTは文章を理解するためのものじゃ。それぞれの目的に応じて、我々は適切な道具を選ぶべきじゃ。

まとめ

  • テストする入力が4~5個ぐらいであれば変わらないが、30個、50個、100個と多数の入力をテストする場合は、APIを使ってプログラムでテストを自動化した方が圧倒的に作業効率化になる
  • 本コードでは、conversation_id: "" としているの、リクエストを投げるたびに新しい質問が飛び、連続した会話ではない。conversation_idの値を引き継ぐように書けば、質問内容、回答を引き継いだ形でのテストもできるようになる。
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?