🤖

Google Cloud で生成 AI アプリケーションを作ろう!パート 2:PaLM API の利用例 1 〜 英文を日本語で要約する

2023/08/15に公開

はじめに

今回は、Google Cloud の大規模言語モデル(LLM) を文書要約に活用します。この後の手順で示すように、Python SDK を利用すると、Python のコードから言語モデルの API を呼び出して利用できるので、既存のアプリケーションに文書要約の機能を簡単に組み込むことができます。

文書要約の機能を追加することで、次のようなメリットが得られます。

  • 大量のテキストの内容を迅速に把握できる。

  • テキスト内の重要な情報を素早く見つけられる。

  • テキストの要点を他の人に分かりやすく伝えられる。

さらに、言語モデル以外の Google Cloud のサービスを組み合わせた、次のようなユースケースも考えられます。

  • 議事録作成:Speech-to-Text で音声データをテキスト文書に変換した後、言語モデルで要約を作成します。

  • 顧客レビューの分析:Natural Language AI でポジティブなレビューとネガティブなレビューを分類しておき、それぞれのグループの内容を言語モデルでまとめて要約します。Natural Language AI では暴力的な内容など、不適切な内容のテキストを自動判別することもできます。

Natural Language API については、「パート 3:PaLM API の利用例 2 〜 メールを分類する」であらためて紹介します。

コンソールを用いた要約処理

Python SDK を用いたコーディングを始める前に、まずは、Generative AI Studio の GUI コンソールから要約処理を試してみましょう。「パート 1 : 生成 AI ソリューションを使うための基本的なセットアップ」の手順を参考にして、Google Cloud のプロジェクトを作成したら、クラウドコンソールのナビゲーションメニューから[Vertex AI]-[GENERATIVE AI STUDIO]-[言語]を選択します。

次の画面が表示されるので、[テキスト プロンプト]をクリックします。

次のようなプロンプト入力画面が表示されるので、ここにテキストを入力して、[送信]をクリックすると、言語モデルからの応答が表示されます。

例えば、量子コンピュータについて書かれた次の少し長い英文があります。

Our quantum computers work by manipulating qubits in an orchestrated fashion that we call quantum algorithms.
The challenge is that qubits are so sensitive that even stray light can cause calculation errors — and the problem worsens as quantum computers grow.
This has significant consequences, since the best quantum algorithms that we know for running useful applications require the error rates of our qubits to be far lower than we have today.
To bridge this gap, we will need quantum error correction.
Quantum error correction protects information by encoding it across multiple physical qubits to form a “logical qubit,” and is believed to be the only way to produce a large-scale quantum computer with error rates low enough for useful calculations.
Instead of computing on the individual qubits themselves, we will then compute on logical qubits. By encoding larger numbers of physical qubits on our quantum processor into one logical qubit, we hope to reduce the error rates to enable useful quantum algorithms.

英語が得意でない方は、なかなか読む気にはならないかも知れません。Google 翻訳で日本語にするという方法もありますが、その前に言語モデルによる要約処理を加えることで、より分かりやすく日本語化できます。

この文章の前後に少しメッセージを加えて、

Provide a very short summary, no more than three sentences, for the following article:

[ここに先ほどの英文を挿入します]

Summary:

としたものを言語モデルに入力します。ここでは、先ほどの文章を3つ以下の文に短くまとめるように依頼しています。すると、言語モデルからは次のような応答が返ってきます。

Quantum computers are very sensitive and prone to errors.
Quantum error correction protects information by encoding it across multiple physical qubits to form a “logical qubit”.
By encoding larger numbers of physical qubits on our quantum processor into one logical qubit, we hope to reduce the error rates to enable useful quantum algorithms. 

確かに3つの文にまとめて要約してくれました。この結果をさらに日本語に翻訳すれば、長い英文もすばやく理解できます。参考までに、Google 翻訳で日本語にした結果は次になります。

量子コンピューターは非常に敏感で、エラーが発生しやすくなっています。
量子エラー訂正は、情報を複数の物理量子ビットにわたってエンコードして「論理量子ビット」を形成することで情報を保護します。
量子プロセッサ上の多数の物理量子ビットを 1 つの論理量子ビットにエンコードすることで、エラー率を低減し、有用な量子アルゴリズムを実現できるようにしたいと考えています。

また、「初心者にもわかりやすく」や「50 語以内で」といった細かい要約の仕方も設定できます。これらの条件を組み合わせる指定も可能です。次は、量子コンピュータの記事を「初心者にもわかりやすく 50 語以内で要約する」ように指示する例です。

Provide a very short summary for beginners, under 50 words, for the following article:

[ここに先ほどの英文を挿入します]

Summary:

出力結果を Google 翻訳で日本語にすると次のようになります。重要なポイントを抜き出して、非常に短く要約できていることが分かります。

量子誤り訂正は、複数の物理量子ビットにわたって量子情報をエンコードすることにより、量子情報を保護します。

さらに、Generative AI Studio では、温度パラメーターで、出力の多様性が調整できます。温度を高くすると、よりバラエティに飛んだクリエイティブな返答が得られます。温度の値は 0 から 1 の範囲で指定します。先ほどの量子コンピュータの例で、温度を 1 にして、より面白く要約するように伝えてみましょう。次のように入力します。

Provide a very short interesting and funny summary, no more than three sentences for the following article:

[ここに先ほどの英文を挿入します]

Summary:

出力結果を Google 翻訳で日本語に翻訳すると次のようになります。雪の結晶に例えて説明する例が得られました。

量子コンピューターは、非常に繊細な雪の結晶のようなものです。 環境の影響を受けやすく、ちょっとした騒音でもミスをしてしまうことがあります。 これが、雪の結晶を寒さから守る特別な種類の冬のコートのような量子誤り訂正が必要な理由です。 量子誤り訂正を使えば、役に立つことを行うのに十分な大きさの量子コンピューターを構築できます。

ただし、温度を高くすると、言語モデルが生成するテキストは実行ごとにより大きくランダムに変化します。言い換えると、同じ内容を与えても毎回違うコンテンツを出力します。

ここでは、量子コンピュータに関するテキストを用いましたが、実際のビジネスシーンでは、長い英文メールを要約するなどの応用が考えられます。メールを受信した際に、長い英文メールについては、内容を要約して日本語に翻訳したものを自動表示する機能があれば、便利になりそうです。

このような機能を既存のアプリケーションに組み込むには、先ほど Generative AI Studioで作業した内容をアプリケーションから実行する必要があります。ここで利用できるのが、API サービスです。次は、API サービスを利用して、先ほどの手順をプログラムコードから実行する方法を説明します。

Python SDK を用いた要約処理

Python SDK を使って、Python のプログラムコードから要約処理を実行する手順を説明します。「パート 1 : 生成 AI ソリューションを使うための基本的なセットアップ」の手順を参考にして、Workbench の環境で新しいノートブックを開きます。

この後は、ノートブック上で順番にコードを実行していきます。すでにコードを書き込んだノートブックが GitHub で公開されていますので、そちらも参考にしてください。

まず、必要となるライブラリをインストールします。

!pip install google-cloud-aiplatform --upgrade --user
!pip install google-cloud-translate==2.0.1 --user

ライブラリーをインストールした直後は、一度、ノートブックのカーネルを再起動する必要があります。再起動ボタン(下図の回転矢印ボタン)をクリックして、カーネルを再起動します。

この後は、上図の + ボタンをクリックしてコード用のセルを追加しながら、コードを順番に実行していきます。

続いて、Vertex AI のクライアントモジュールをインポートして、PaLM API のクライアントオブジェクトを取得します。この際、使用する言語モデルの種類をオプションで指定できます。

from vertexai.preview.language_models import TextGenerationModel

generation_model = TextGenerationModel.from_pretrained('text-bison@001')

Vertex AI では、大規模言語モデルとして PaLM 2 をベースとした複数のモデルが選択可能で、ここでは、汎用的な text-bision@001 を選択しています。利用可能なモデルについては、こちらのドキュメントを参考にしてください。

言語モデルに入力するプロンプトは、先ほどコンソール上で使ったものをそのまま利用します。

prompt = """
Provide a very short summary, no more than three sentences, for the following article:

Our quantum computers work by manipulating qubits in an orchestrated fashion that we call quantum algorithms.
The challenge is that qubits are so sensitive that even stray light can cause calculation errors — and the problem worsens as quantum computers grow.
This has significant consequences, since the best quantum algorithms that we know for running useful applications require the error rates of our qubits to be far lower than we have today.
To bridge this gap, we will need quantum error correction.
Quantum error correction protects information by encoding it across multiple physical qubits to form a “logical qubit,” and is believed to be the only way to produce a large-scale quantum computer with error rates low enough for useful calculations.
Instead of computing on the individual qubits themselves, we will then compute on logical qubits. By encoding larger numbers of physical qubits on our quantum processor into one logical qubit, we hope to reduce the error rates to enable useful quantum algorithms.

Summary:
"""

後は、このプロンプトを言語モデルに送信するだけです。この際、温度パラメーターなどのオプションも指定できます。次のコードを実行すると、言語モデルからの応答が変数 response に保存されます。

response = generation_model.predict(
        prompt, temperature=0.2, max_output_tokens=1024,
        top_k=40, top_p=0.8).text

得られた結果を表示してみましょう。

print(response)

結果は次のようになります。

Quantum computers are very sensitive and even stray light can cause calculation errors.
Quantum error correction protects information by encoding it across multiple physical qubits to form a “logical qubit”.
By encoding larger numbers of physical qubits on our quantum processor into one logical qubit, we hope to reduce the error rates to enable useful quantum algorithms.

Translation API を用いて、この結果を日本語に翻訳します。Translation API のモジュールをインポートして、クライアントオブジェクトを取得します。

from google.cloud import translate_v2 as translate

translate_client = translate.Client()

Translation API は様々な言語に対応しており、変換先の言語(今の場合は日本語)を指定する必要があります。英語から変換可能な言語は、次のコマンドで確認できます。

translate_client.get_languages(target_language='en')

実行結果は次のようになります。

[{'language': 'af', 'name': 'Afrikaans'},
 {'language': 'sq', 'name': 'Albanian'},

(中略)

 {'language': 'ja', 'name': 'Japanese'},

(以下省略)

この結果から、日本語は ja で指定できることがわかります。そこで、日本語に変換する関数を次のように定義しておきます。

def translate_text(text):
    translated = []
    for line in text.split('\n'):
        result = translate_client.translate(line, target_language='ja')
        translated.append(result['translatedText'])
    return '\n'.join(translated)

それでは、この関数を用いて、言語モデルによって要約された内容を翻訳してみましょう。

print(translate_text(response))

結果は次のようになります。

量子コンピューターは非常に敏感であり、エラーが発生しやすいです。
量子エラー訂正は、複数の物理量子ビットにわたって情報をエンコードして論理量子ビットを形成することで情報を保護します。
量子プロセッサ上で多数の物理量子ビットを 1 つの論理量子ビットにエンコードすることで、エラー率を低減し、有用な量子アルゴリズムを実現できるようにしたいと考えています。

最後に、要約と翻訳をまとめて実行する関数を作っておきます。

def summarize_and_translate_text(text):
    prompt = """
Provide a very short summary, no more than three sentences, for the following article:

{}

Summary:
""".format(text)
    response = generation_model.predict(
        prompt, temperature=0.2, max_output_tokens=1024,
        top_k=40, top_p=0.8).text
    return translate_text(response)

この関数は、次のように、要約対象のテキストだけを入力すると、日本語の要約文が得られます。

text = """
Our quantum computers work by manipulating qubits in an orchestrated fashion that we call quantum algorithms.
The challenge is that qubits are so sensitive that even stray light can cause calculation errors — and the problem worsens as quantum computers grow.
This has significant consequences, since the best quantum algorithms that we know for running useful applications require the error rates of our qubits to be far lower than we have today.
To bridge this gap, we will need quantum error correction.
Quantum error correction protects information by encoding it across multiple physical qubits to form a “logical qubit,” and is believed to be the only way to produce a large-scale quantum computer with error rates low enough for useful calculations.
Instead of computing on the individual qubits themselves, we will then compute on logical qubits. By encoding larger numbers of physical qubits on our quantum processor into one logical qubit, we hope to reduce the error rates to enable useful quantum algorithms.
"""

print(summarize_and_translate_text(text))

実行結果は、みなさんの環境で実際に確認してみてください。

まとめ

今回は、Google Cloud の大規模言語モデル(LLM)をテキスト要約に利用する例を紹介しました。ここでは、ノートブック上でコードを実行しましたが、これらのコードをアプリケーションに組み込んで、「長い英文メールを日本語で要約して表示する機能」を実現するのはそれほど難しくないでしょう。英文メール以外にも、このような要約機能が役立つ場面があるはずですので、様々な業務アプリケーションに組み込んで活用してください。

Google Cloud Japan

Discussion