🤖

Cloudflare Workers AI 使ってみた「テキスト要約編」

に公開

はじめに

こんにちは、ikechan こといけがわです。

最近、Cloudflare生成AIの「BART Large CNN」 というモデルを見つけ、ChatGPTとの違いが気になり試してみました。このモデルはテキスト要約に特化しており、Cloudflare Workers AIを使えばサーバーレス環境で簡単に利用できます。

実際に使ってみた結果や、ChatGPTとの比較について具体例を交えながら共有します!

前提条件

この記事を進めるにあたり、以下の準備が必要です。

  • Cloudflare アカウント: Workers AIの利用に必須
  • Node.js 開発環境: 今回はBunを使用
  • Hono フレームワーク: 軽量なWebサーバーフレームワーク

実装手順

1. 必要な環境のセットアップ

まず、Honoをインストールします。

bun create hono@latest text-summary-app
cd text-summary-app

環境変数用の.envファイルを作成し、CloudflareのAPIトークンとアカウントIDを設定します。

2. APIリクエストの実装

Cloudflare Workers AIの「BART Large CNN」モデルを使ったテキスト要約の関数を以下のように実装しました。

export const summarizeText = async (
  params: TextSummarizationParams
): Promise<CloudflareSummaryResponse> => {
  const response = await makeApiRequest({
    endpoint: "/@cf/facebook/bart-large-cnn",
    data: JSON.stringify({
      input_text: params.text,
      max_length: params.maxLength || 1024,
    }),
    contentType: "application/json",
  });

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

  return response.json();
};

エンドポイントを以下のように設定します。

app.post("/summarize", async (c) => {
  try {
    const { text } = await c.req.json();
    if (!text) {
      return c.json({ error: "Text is required" }, 400);
    }

    const response = await summarizeText({ text, maxLength: 1024 });

    if (
      !response ||
      !response.result ||
      typeof response.result.summary !== "string"
    ) {
      return c.json({ error: "Invalid API response format" }, 500);
    }

    const cleanSummary = response.result.summary.replace(/\n/g, " ").trim();

    return c.json({ summary: cleanSummary });
  } catch (error) {
    return c.json({ error: "Failed to summarize text" }, 500);
  }
});

動作確認

1. サーバー起動

以下のコマンドでサーバーを起動します。

bun run index.ts

2. 要約のリクエスト

curl -X POST http://localhost:8080/summarize \
-H "Content-Type: application/json" \
-d '{
  "text": "In today's competitive market, businesses need to adopt innovative strategies to stay ahead. This includes leveraging technology to improve efficiency, enhancing customer experience, and focusing on sustainable practices. Companies that fail to adapt risk losing their competitive edge and being left behind in the rapidly evolving global economy."
}'
要約結果の比較

元の文章:

In today's competitive market, businesses need to adopt innovative strategies to stay ahead. This includes leveraging technology to improve efficiency, enhancing customer experience, and focusing on sustainable practices. Companies that fail to adapt risk losing their competitive edge and being left behind in the rapidly evolving global economy.

Cloudflare Workers AIの要約:

Businesses must innovate, use technology, and focus on sustainability to stay competitive.

ChatGPTの要約:

To stay competitive, businesses must adopt innovative strategies such as leveraging technology for efficiency, enhancing customer experiences, and focusing on sustainability. Failure to adapt may result in losing their competitive edge in the fast-evolving global market.

比較分析

モデル 要約の特徴
Cloudflare 簡潔でわかりやすい要約。情報量が少なめ。
ChatGPT 詳細な情報を保持しつつ簡潔な要約を生成。

結論

  • Cloudflare Workers AIは簡潔で短い要約に向いていそう
  • ChatGPTは、具体性を求める場合に適していそう

まとめ

今回の検証から、BART Large CNNモデルは非常に簡潔な要約を生成する特徴があることがわかりました。一方でChatGPTは、より詳細な情報を保持しながら要約を生成できることも確認できました。

これからさらにモデルの動作を試行錯誤しながら、プロンプト設計や前処理を改善することで、より望ましい結果が得られる可能性を探りたいと思います。

参考リンク

Discussion