ワークフローから Vertex AI モデルにアクセスする


Vertex AI の生成 AI(別名: genAI)で Google の生成 AI モデルにアクセスすることが可能で、これを複数のモダリティ(テキスト、コード、画像、スピーチ)向けに活用することができます。genAIgenAIこれらの大規模言語モデル(LLM)をテストして調整し、AI を活用したアプリケーションで使用するためにデプロイできます。詳細については、Vertex AI での生成 AI の概要をご覧ください。

Vertex AI には、次の例で使用されるモデルを含む、API を通じてアクセス可能なさまざまな生成 AI 基盤モデルがあります。

  • Gemini Pro は、自然言語タスク、マルチターン テキストとコードチャット、およびコード生成を処理するように設計されています。
  • Gemini Pro Vision は、マルチモーダル プロンプトをサポートします。プロンプト リクエストにテキスト、画像、動画を含めて、テキストまたはコード レスポンスを取得できます。
  • Pathways Language Model 2(PaLM 2) for text は、分類、要約、エンティティ抽出などの言語タスク向けに微調整されています。

各モデルは、Google Cloud プロジェクト専用のパブリッシャー エンドポイントを通じて公開されます。そのため、特定のユースケース向けにチューニングする場合を除いて、基盤モデルをデプロイする必要はありません。パブリッシャー エンドポイントにプロンプトを送信できます。プロンプトとは、レスポンスを引き出すために LLM に送信される自然言語によるリクエストのことです。

このチュートリアルでは、Workflows コネクタまたは HTTP POST リクエストを使用してパブリッシャー エンドポイントにテキスト プロンプトを送信し、Vertex AI モデルからレスポンスを生成するワークフローについて説明します。詳細については、Vertex AI API コネクタの概要HTTP リクエストを行うをご覧ください。

各ワークフローは、互いに独立してデプロイし実行できます。

目標

このチュートリアルでは、次のことを行います。

  1. Vertex AI と Workflows API を有効にし、Vertex AI ユーザー(roles/aiplatform.user)のロールをサービス アカウントに付与します。このロールを使用すると、ほとんどの Vertex AI 機能にアクセスできるようになります。Vertex AI の設定の詳細については、Google Cloud での設定をご覧ください。
  2. Vertex AI モデル(Gemini Pro Vision)に、Cloud Storage で一般公開されている画像を説明するように要求するワークフローをデプロイして実行します。詳細については、データを一般公開するをご覧ください。
  3. 国のリストを並列にループするワークフローをデプロイして実行し、Vertex AI モデル(Gemini Pro)に国の履歴を生成して返すよう指示します。並列ブランチを使用すると、LLM の呼び出しを同時に開始し、すべての呼び出しが完了するのを待ってから結果を結合できるため、合計実行時間を短縮できます。詳細については、ワークフロー ステップを並列実行するをご覧ください。
  4. 前述のワークフローと同様のワークフローをデプロイします。ただし、Vertex AI モデル(PaLM 2 for text)に、国の歴史を生成して返すよう指示します。モデルを選択する方法については、モデル情報をご覧ください。
  5. 大きなドキュメントを要約できるワークフローをデプロイします。トレーニング中(および予測)にモデルがどこまでさかのぼるかを設定するコンテキスト ウィンドウには制限があるため、ワークフローはドキュメントを小さな部分に分割してから、Vertex AI モデル(Gemini Pro)にプロンプトをお送り、各部分を並列で要約します。詳細については、要約プロンプト予測ホライズン、コンテキスト ウィンドウ、予測ウィンドウをご覧ください。

料金

このドキュメントでは、Google Cloud の次の課金対象のコンポーネントを使用します。

料金計算ツールを使うと、予想使用量に基づいて費用の見積もりを生成できます。 新しい Google Cloud ユーザーは無料トライアルをご利用いただける場合があります。

このドキュメントに記載されているタスクの完了後、作成したリソースを削除すると、それ以上の請求は発生しません。詳細については、クリーンアップをご覧ください。

始める前に

このチュートリアルの例を試す前に、次のことが完了していることを確認してください。

コンソール

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  3. Google Cloud プロジェクトで課金が有効になっていることを確認します

  4. Vertex AI and Workflows API を有効にします。

    API を有効にする

  5. Create a service account:

    1. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    2. Select your project.
    3. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

      In the Service account description field, enter a description. For example, Service account for quickstart.

    4. Click Create and continue.
    5. Grant the Vertex AI > Vertex AI User role to the service account.

      To grant the role, find the Select a role list, then select Vertex AI > Vertex AI User.

    6. Click Continue.
    7. Click Done to finish creating the service account.

  6. Google Cloud Console の [プロジェクト セレクタ] ページで、Google Cloud プロジェクトを選択または作成します。

    プロジェクト セレクタに移動

  7. Google Cloud プロジェクトで課金が有効になっていることを確認します

  8. Vertex AI and Workflows API を有効にします。

    API を有効にする

  9. Create a service account:

    1. In the Google Cloud console, go to the Create service account page.

      Go to Create service account
    2. Select your project.
    3. In the Service account name field, enter a name. The Google Cloud console fills in the Service account ID field based on this name.

      In the Service account description field, enter a description. For example, Service account for quickstart.

    4. Click Create and continue.
    5. Grant the Vertex AI > Vertex AI User role to the service account.

      To grant the role, find the Select a role list, then select Vertex AI > Vertex AI User.

    6. Click Continue.
    7. Click Done to finish creating the service account.

gcloud

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. Google Cloud CLI をインストールします。
  3. gcloud CLI を初期化するには:

    gcloud init
  4. Google Cloud プロジェクトを作成または選択します

    • Google Cloud プロジェクトを作成します。

      gcloud projects create PROJECT_ID

      PROJECT_ID は、作成する Google Cloud プロジェクトの名前に置き換えます。

    • 作成した Google Cloud プロジェクトを選択します。

      gcloud config set project PROJECT_ID

      PROJECT_ID は、実際の Google Cloud プロジェクト名に置き換えます。

  5. Google Cloud プロジェクトで課金が有効になっていることを確認します

  6. Vertex AI and Workflows API を有効にします。

    gcloud services enable aiplatform.googleapis.comworkflows.googleapis.com
  7. Set up authentication:

    1. Create the service account:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      Replace SERVICE_ACCOUNT_NAME with a name for the service account.

    2. Grant the roles/aiplatform.user IAM role to the service account:

      gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=roles/aiplatform.user

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account
  8. Google Cloud CLI をインストールします。
  9. gcloud CLI を初期化するには:

    gcloud init
  10. Google Cloud プロジェクトを作成または選択します

    • Google Cloud プロジェクトを作成します。

      gcloud projects create PROJECT_ID

      PROJECT_ID は、作成する Google Cloud プロジェクトの名前に置き換えます。

    • 作成した Google Cloud プロジェクトを選択します。

      gcloud config set project PROJECT_ID

      PROJECT_ID は、実際の Google Cloud プロジェクト名に置き換えます。

  11. Google Cloud プロジェクトで課金が有効になっていることを確認します

  12. Vertex AI and Workflows API を有効にします。

    gcloud services enable aiplatform.googleapis.comworkflows.googleapis.com
  13. Set up authentication:

    1. Create the service account:

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      Replace SERVICE_ACCOUNT_NAME with a name for the service account.

    2. Grant the roles/aiplatform.user IAM role to the service account:

      gcloud projects add-iam-policy-binding PROJECT_ID --member="serviceAccount:SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com" --role=roles/aiplatform.user

      Replace the following:

      • SERVICE_ACCOUNT_NAME: the name of the service account
      • PROJECT_ID: the project ID where you created the service account

画像を説明するワークフローをデプロイする(Gemini Pro Vision)

コネクタ メソッド(generateContent)を使用するワークフローをデプロイして、Gemini Pro Vision パブリッシャー エンドポイントにリクエストを送信します。このメソッドは、マルチモーダル入力によるコンテンツ生成をサポートします。

このワークフローは、テキスト プロンプトと、Cloud Storage バケットで一般公開されている画像の URI を提供します。画像を表示したり、Google Cloud コンソールでオブジェクトの詳細を確認したりすることができます。

ワークフローは、モデルで生成されたレスポンスから画像の説明を返します。

LLM のプロンプトで使用される HTTP リクエストの本文パラメータと、レスポンスの本文要素の詳細については、Gemini API リファレンスをご覧ください。

コンソール

  1. Google Cloud コンソールの [ワークフロー] ページに移動します。

    [ワークフロー] に移動

  2. [ 作成] をクリックします。

  3. 新しいフィールドの名前を入力します: describe-image

  4. [リージョン] リストで [us-central1 (Iowa)] を選択します。

  5. [サービス アカウント] で、先ほど作成したサービス アカウントを選択します。

  6. [次へ] をクリックします。

  7. ワークフロー エディタで、次のワークフローの定義を入力します。

    main:
        params: [args]
        steps:
        - init:
            assign:
                - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
                - location: "us-central1"
                - model: "gemini-1.0-pro-vision"
                - text_combined: ""
        - ask_llm:
            call: googleapis.aiplatform.v1.projects.locations.endpoints.generateContent
            args:
                model: ${"projects/" + project + "/locations/" + location + "/publishers/google/models/" + model}
                region: ${location}
                body:
                    contents:
                        role: user
                        parts:
                        - fileData:
                            mimeType: image/jpeg
                            fileUri: ${args.image_url}
                        - text: Describe this picture in detail
                    generation_config:
                        temperature: 0.4
                        max_output_tokens: 2048
                        top_p: 1
                        top_k: 32
            result: llm_response
        - return_result:
            return:
                image_url: ${args.image_url}
                image_description: ${llm_response.candidates[0].content.parts[0].text}
  8. [Deploy] をクリックします。

gcloud

  1. ワークフローのソースコード ファイルを作成します。

    touch describe-image.yaml
    
  2. テキスト エディタで、次のワークフローをソースコード ファイルにコピーします。

    main:
        params: [args]
        steps:
        - init:
            assign:
                - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
                - location: "us-central1"
                - model: "gemini-1.0-pro-vision"
                - text_combined: ""
        - ask_llm:
            call: googleapis.aiplatform.v1.projects.locations.endpoints.generateContent
            args:
                model: ${"projects/" + project + "/locations/" + location + "/publishers/google/models/" + model}
                region: ${location}
                body:
                    contents:
                        role: user
                        parts:
                        - fileData:
                            mimeType: image/jpeg
                            fileUri: ${args.image_url}
                        - text: Describe this picture in detail
                    generation_config:
                        temperature: 0.4
                        max_output_tokens: 2048
                        top_p: 1
                        top_k: 32
            result: llm_response
        - return_result:
            return:
                image_url: ${args.image_url}
                image_description: ${llm_response.candidates[0].content.parts[0].text}
  3. 次のコマンドを入力してワークフローをデプロイします。

    gcloud workflows deploy describe-image \
        --source=describe-image.yaml \
        --location=us-central1 \
        --service-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com

ワークフローを実行する

ワークフローを実行すると、そのワークフローに関連付けられた現在のワークフロー定義が実行されます。

コンソール

  1. Google Cloud コンソールの [ワークフロー] ページに移動します。

    [ワークフロー] に移動

  2. [ワークフロー] ページで、[describe-image] ワークフローを選択して詳細ページに移動します。

  3. [ワークフローの詳細] ページで [ 実行] を選択します。

  4. [Input] に、次のように入力します。

    {"image_url":"gs://generativeai-downloads/images/scones.jpg"}
  5. もう一度 [Execute] をクリックします。

  6. ワークフローの結果が [出力] ペインに表示されます。

    出力例を以下に示します。

    {
      "image_description": "There are three pink peony flowers on the right side of the picture[]...]There is a white napkin on the table.",
      "image_url": "gs://generativeai-downloads/images/scones.jpg"
    }

gcloud

  1. ターミナルを開きます。

  2. ワークフローを実行します。

    gcloud workflows run describe-image \
        --data='{"image_url":"gs://generativeai-downloads/images/scones.jpg"}'

    結果の例を以下に示します。

      Waiting for execution [258b530e-a093-46d7-a4ff-cbf5392273c0] to complete...done.
      argument: '{"image_url":"gs://generativeai-downloads/images/scones.jpg"}'
      createTime: '2024-02-09T13:59:32.166409938Z'
      duration: 4.174708484s
      endTime: '2024-02-09T13:59:36.341118422Z'
      name: projects/1051295516635/locations/us-central1/workflows/describe-image/executions/258b530e-a093-46d7-a4ff-cbf5392273c0
      result: "{\"image_description\":\"The picture shows a rustic table with a white surface,\
        \ on which there are several scones with blueberries, as well as two cups of coffee\
        [...]
        \ on the table. The background of the table is a dark blue color.\",\"image_url\"\
        :\"gs://generativeai-downloads/images/scones.jpg\"}"
      startTime: '2024-02-09T13:59:32.166409938Z'
      state: SUCCEEDED

国の歴史を生成するワークフローをデプロイする(Gemini Pro)

国の入力リストをparallelにループするワークフローをデプロイし、コネクタ メソッド(generateContent)を使用して Gemini Pro パブリッシャー エンドポイントに対してリクエストを行います。このメソッドは、マルチモーダル入力によるコンテンツ生成をサポートします。

ワークフローが、モデルによって生成された国の歴史を返し、マップにまとめます。

LLM のプロンプトで使用される HTTP リクエストの本文パラメータと、レスポンスの本文要素の詳細については、Gemini API リファレンスをご覧ください。

コンソール

  1. Google Cloud コンソールの [ワークフロー] ページに移動します。

    [ワークフロー] に移動

  2. [ 作成] をクリックします。

  3. 新しいフィールドの名前を入力します: gemini-pro-country-histories

  4. [リージョン] リストで [us-central1 (Iowa)] を選択します。

  5. [サービス アカウント] で、先ほど作成したサービス アカウントを選択します。

  6. [次へ] をクリックします。

  7. ワークフロー エディタで、次のワークフローの定義を入力します。

    main:
        params: [args]
        steps:
        - init:
            assign:
                - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
                - location: "us-central1"
                - model: "gemini-1.0-pro"
                - histories: {}
        - loop_over_countries:
            parallel:
                shared: [histories]
                for:
                    value: country
                    in: ${args.countries}
                    steps:
                        - ask_llm:
                            call: googleapis.aiplatform.v1.projects.locations.endpoints.generateContent
                            args:
                                model: ${"projects/" + project + "/locations/" + location + "/publishers/google/models/" + model}
                                region: ${location}
                                body:
                                    contents:
                                        role: "USER"
                                        parts:
                                            text: ${"Can you tell me about the history of " + country}
                                    generation_config:
                                        temperature: 0.5
                                        max_output_tokens: 2048
                                        top_p: 0.8
                                        top_k: 40
                            result: llm_response
                        - add_to_histories:
                            assign:
                                - histories[country]: ${llm_response.candidates[0].content.parts[0].text}
        - return_result:
            return: ${histories}
  8. [Deploy] をクリックします。

gcloud

  1. ワークフローのソースコード ファイルを作成します。

    touch gemini-pro-country-histories.yaml
    
  2. テキスト エディタで、次のワークフローをソースコード ファイルにコピーします。

    main:
        params: [args]
        steps:
        - init:
            assign:
                - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
                - location: "us-central1"
                - model: "gemini-1.0-pro"
                - histories: {}
        - loop_over_countries:
            parallel:
                shared: [histories]
                for:
                    value: country
                    in: ${args.countries}
                    steps:
                        - ask_llm:
                            call: googleapis.aiplatform.v1.projects.locations.endpoints.generateContent
                            args:
                                model: ${"projects/" + project + "/locations/" + location + "/publishers/google/models/" + model}
                                region: ${location}
                                body:
                                    contents:
                                        role: "USER"
                                        parts:
                                            text: ${"Can you tell me about the history of " + country}
                                    generation_config:
                                        temperature: 0.5
                                        max_output_tokens: 2048
                                        top_p: 0.8
                                        top_k: 40
                            result: llm_response
                        - add_to_histories:
                            assign:
                                - histories[country]: ${llm_response.candidates[0].content.parts[0].text}
        - return_result:
            return: ${histories}
  3. 次のコマンドを入力してワークフローをデプロイします。

    gcloud workflows deploy gemini-pro-country-histories \
        --source=gemini-pro-country-histories.yaml \
        --location=us-central1 \
        --service-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com

ワークフローを実行する

ワークフローを実行すると、そのワークフローに関連付けられた現在のワークフロー定義が実行されます。

コンソール

  1. Google Cloud コンソールの [ワークフロー] ページに移動します。

    [ワークフロー] に移動

  2. [ワークフロー] ページで、[gemini-pro-country-histories] ワークフローを選択して詳細ページに移動します。

  3. [ワークフローの詳細] ページで [ 実行] を選択します。

  4. [Input] に、次のように入力します。

    {"countries":["Argentina", "Bhutan", "Cyprus", "Denmark", "Ethiopia"]}
  5. もう一度 [Execute] をクリックします。

  6. ワークフローの結果が [出力] ペインに表示されます。

    出力例を以下に示します。

    {
      "Argentina": "The history of Argentina is a complex and fascinating one, marked by periods of prosperity and decline, political [...]
      "Bhutan": "The history of Bhutan is a rich and fascinating one, dating back to the 7th century AD. Here is a brief overview: [...]
      "Cyprus": "The history of Cyprus is a long and complex one, spanning over 10,000 years. The island has been ruled by a succession [...]
      "Denmark": "1. **Prehistory and Early History (c. 12,000 BC - 800 AD)**\\n   - The earliest evidence of human habitation in Denmark [...]
      "Ethiopia": "The history of Ethiopia is a long and complex one, stretching back to the earliest human civilizations. The country is [...]
    }

gcloud

  1. ターミナルを開きます。

  2. ワークフローを実行します。

    gcloud workflows run gemini-pro-country-histories \
        --data='{"countries":["Argentina", "Bhutan", "Cyprus", "Denmark", "Ethiopia"]}' \
        --location=us-central1

    結果の例を以下に示します。

      Waiting for execution [7ae1ccf1-29b7-4c2c-99ec-7a12ae289391] to complete...done.
      argument: '{"countries":["Argentina","Bhutan","Cyprus","Denmark","Ethiopia"]}'
      createTime: '2024-02-09T16:25:16.742349156Z'
      duration: 12.075968673s
      endTime: '2024-02-09T16:25:28.818317829Z'
      name: projects/1051295516635/locations/us-central1/workflows/gemini-pro-country-histories/executions/7ae1ccf1-29b7-4c2c-99ec-7a12ae289391
      result: "{\"Argentina\":\"The history of Argentina can be traced back to the arrival\
        [...]
        n* 2015: Argentina elects Mauricio Macri as president.\",\"Bhutan\":\"The history\
        [...]
        \ natural beauty, ancient monasteries, and friendly people.\",\"Cyprus\":\"The history\
        [...]
        ,\"Denmark\":\"The history of Denmark can be traced back to the Stone Age, with\
        [...]
        \ a high standard of living.\",\"Ethiopia\":\"The history of Ethiopia is long and\
        [...]
      startTime: '2024-02-09T16:25:16.742349156Z'
      state: SUCCEEDED

国の歴史を生成するワークフローをデプロイする(PaLM 2 for text)

モデルとして Gemini Pro を使用しない場合も考えられます。次の例では、前のものと同様のワークフローを使用します。ただし、コネクタ メソッド(predict)を使用して、PaLM 2 for text のパブリッシャー エンドポイントに対してリクエストを行います。このメソッドは、オンライン予測を行います。

LLM のプロンプトに使用される HTTP リクエストの本文パラメータと、レスポンスの本文の要素の詳細については、PaLM 2 for Text API リファレンスをご覧ください。

コンソール

  1. Google Cloud コンソールの [ワークフロー] ページに移動します。

    [ワークフロー] に移動

  2. [ 作成] をクリックします。

  3. 新しいフィールドの名前を入力します: text-bison-country-histories

  4. [リージョン] リストで [us-central1 (Iowa)] を選択します。

  5. [サービス アカウント] で、先ほど作成したサービス アカウントを選択します。

  6. [次へ] をクリックします。

  7. ワークフロー エディタで、次のワークフローの定義を入力します。

    main:
        params: [args]
        steps:
        - init:
            assign:
                - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
                - location: "us-central1"
                - model: "text-bison"
                - histories: {}
        - loop_over_countries:
            parallel:
                shared: [histories]
                for:
                    value: country
                    in: ${args.countries}
                    steps:
                        - ask_llm:
                            call: googleapis.aiplatform.v1.projects.locations.endpoints.predict
                            args:
                                endpoint: ${"projects/" + project + "/locations/" + location + "/publishers/google/models/" + model }
                                region: ${location}
                                body:
                                    instances:
                                        - prompt: '${"Can you  tell me about the history of " + country}'
                                    parameters:
                                        temperature: 0.5
                                        maxOutputTokens: 2048
                                        topP: 0.8
                                        topK: 40
                            result: llm_response
                        - add_to_histories:
                            assign:
                                - history: ${llm_response.predictions[0].content}
                                # Remove leading whitespace from start of text
                                - history: ${text.substring(history, 1, len(history))}
                                - histories[country]: ${history}
        - return_result:
            return: ${histories}

    使用するモデルによっては、レスポンスから不要な空白文字を削除することが必要な場合があります。

  8. [Deploy] をクリックします。

gcloud

  1. ワークフローのソースコード ファイルを作成します。

    touch text-bison-country-histories.yaml
    
  2. テキスト エディタで、次のワークフローをソースコード ファイルにコピーします。

    main:
        params: [args]
        steps:
        - init:
            assign:
                - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
                - location: "us-central1"
                - model: "text-bison"
                - histories: {}
        - loop_over_countries:
            parallel:
                shared: [histories]
                for:
                    value: country
                    in: ${args.countries}
                    steps:
                        - ask_llm:
                            call: googleapis.aiplatform.v1.projects.locations.endpoints.predict
                            args:
                                endpoint: ${"projects/" + project + "/locations/" + location + "/publishers/google/models/" + model }
                                region: ${location}
                                body:
                                    instances:
                                        - prompt: '${"Can you  tell me about the history of " + country}'
                                    parameters:
                                        temperature: 0.5
                                        maxOutputTokens: 2048
                                        topP: 0.8
                                        topK: 40
                            result: llm_response
                        - add_to_histories:
                            assign:
                                - history: ${llm_response.predictions[0].content}
                                # Remove leading whitespace from start of text
                                - history: ${text.substring(history, 1, len(history))}
                                - histories[country]: ${history}
        - return_result:
            return: ${histories}

    使用するモデルによっては、レスポンスから不要な空白文字を削除することが必要な場合があります。

  3. 次のコマンドを入力してワークフローをデプロイします。

    gcloud workflows deploy text-bison-country-histories \
        --source=text-bison-country-histories.yaml \
        --location=us-central1 \
        --service-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com

大きなドキュメントを要約するワークフローをデプロイする(Gemini Pro)

大きなドキュメントを小さな部分に分割するワークフローをデプロイし、Gemini Pro パブリッシャー エンドポイントへの http.post リクエストをparallelで実行して、モデルが各部分を同時に要約できるようにします。ワークフローが最終的に、部分的なサマリーをすべて 1 つのサマリーにまとめます。

LLM のプロンプトで使用される HTTP リクエストの本文パラメータと、レスポンスの本文要素の詳細については、Gemini API リファレンスをご覧ください。

このワークフロー定義は、テキスト ファイルをアップロードできる Cloud Storage バケットを作成していることを前提としています。Cloud Storage バケットからオブジェクトを取得するために使用される Workflows コネクタ(googleapis.storage.v1.objects.get)の詳細については、コネクタ リファレンスをご覧ください。

ワークフローをデプロイしたら、適切な Eventarc トリガーを作成し、ファイルをバケットにアップロードして実行できます。詳細については、Cloud Storage イベントを Workflows に転送するをご覧ください。追加の API を有効にする必要があります。また、サービス アカウントに Cloud Storage オブジェクトの使用をサポートするストレージ オブジェクト ユーザー(roles/storage.objectUser)のロールを付与するなど、追加のロールを付与する必要があります。詳細については、トリガーの作成を準備するセクションをご覧ください。

コンソール

  1. Google Cloud コンソールの [ワークフロー] ページに移動します。

    [ワークフロー] に移動

  2. [ 作成] をクリックします。

  3. 新しいフィールドの名前を入力します: gemini-pro-summaries

  4. [リージョン] リストで [us-central1 (Iowa)] を選択します。

  5. [サービス アカウント] で、先ほど作成したサービス アカウントを選択します。

  6. [次へ] をクリックします。

  7. ワークフロー エディタで、次のワークフローの定義を入力します。

    main:
        params: [input]
        steps:
        - assign_file_vars:
            assign:
                - file_size: ${int(input.data.size)}
                - chunk_size: 64000
                - n_chunks: ${int(file_size / chunk_size)}
                - summaries: []
                - all_summaries_concatenated: ""
        - loop_over_chunks:
            parallel:
                shared: [summaries]
                for:
                    value: chunk_idx
                    range: ${[0, n_chunks]}
                    steps:
                        - assign_bounds:
                            assign:
                                - lower_bound: ${chunk_idx * chunk_size}
                                - upper_bound: ${(chunk_idx + 1) * chunk_size}
                                - summaries: ${list.concat(summaries, "")}
                        - dump_file_content:
                            call: http.get
                            args:
                                url: ${"https://storage.googleapis.com/storage/v1/b/" + input.data.bucket + "/o/" + input.data.name + "?alt=media"}
                                auth:
                                    type: OAuth2
                                headers:
                                    Range: ${"bytes=" + lower_bound + "-" + upper_bound}
                            result: file_content
                        - assign_chunk:
                            assign:
                                - chunk: ${file_content.body}
                        - generate_chunk_summary:
                            call: ask_gemini_for_summary
                            args:
                                textToSummarize: ${chunk}
                            result: summary
                        - assign_summary:
                            assign:
                                - summaries[chunk_idx]: ${summary}
        - concat_summaries:
            for:
                value: summary
                in: ${summaries}
                steps:
                    - append_summaries:
                        assign:
                            - all_summaries_concatenated: ${all_summaries_concatenated + "\n" + summary}
        - reduce_summary:
            call: ask_gemini_for_summary
            args:
                textToSummarize: ${all_summaries_concatenated}
            result: final_summary
        - return_result:
            return:
                - summaries: ${summaries}
                - final_summary: ${final_summary}
    
    ask_gemini_for_summary:
        params: [textToSummarize]
        steps:
            - init:
                assign:
                    - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
                    - location: "us-central1"
                    - model: "gemini-pro"
                    - summary: ""
            - call_gemini:
                call: http.post
                args:
                    url: ${"https://" + location + "-aiplatform.googleapis.com" + "/v1/projects/" + project + "/locations/" + location + "/publishers/google/models/" + model + ":generateContent"}
                    auth:
                        type: OAuth2
                    body:
                        contents:
                            role: user
                            parts:
                                - text: '${"Make a summary of the following text:\n\n" + textToSummarize}'
                        generation_config:
                            temperature: 0.2
                            maxOutputTokens: 2000
                            topK: 10
                            topP: 0.9
                result: gemini_response
            # Sometimes, there's no text, for example, due to safety settings
            - check_text_exists:
                switch:
                - condition: ${not("parts" in gemini_response.body.candidates[0].content)}
                  next: return_summary
            - extract_text:
                assign:
                    - summary: ${gemini_response.body.candidates[0].content.parts[0].text}
            - return_summary:
                return: ${summary}
  8. [Deploy] をクリックします。

gcloud

  1. ワークフローのソースコード ファイルを作成します。

    touch gemini-pro-summaries.yaml
    
  2. テキスト エディタで、次のワークフローをソースコード ファイルにコピーします。

    main:
        params: [input]
        steps:
        - assign_file_vars:
            assign:
                - file_size: ${int(input.data.size)}
                - chunk_size: 64000
                - n_chunks: ${int(file_size / chunk_size)}
                - summaries: []
                - all_summaries_concatenated: ""
        - loop_over_chunks:
            parallel:
                shared: [summaries]
                for:
                    value: chunk_idx
                    range: ${[0, n_chunks]}
                    steps:
                        - assign_bounds:
                            assign:
                                - lower_bound: ${chunk_idx * chunk_size}
                                - upper_bound: ${(chunk_idx + 1) * chunk_size}
                                - summaries: ${list.concat(summaries, "")}
                        - dump_file_content:
                            call: http.get
                            args:
                                url: ${"https://storage.googleapis.com/storage/v1/b/" + input.data.bucket + "/o/" + input.data.name + "?alt=media"}
                                auth:
                                    type: OAuth2
                                headers:
                                    Range: ${"bytes=" + lower_bound + "-" + upper_bound}
                            result: file_content
                        - assign_chunk:
                            assign:
                                - chunk: ${file_content.body}
                        - generate_chunk_summary:
                            call: ask_gemini_for_summary
                            args:
                                textToSummarize: ${chunk}
                            result: summary
                        - assign_summary:
                            assign:
                                - summaries[chunk_idx]: ${summary}
        - concat_summaries:
            for:
                value: summary
                in: ${summaries}
                steps:
                    - append_summaries:
                        assign:
                            - all_summaries_concatenated: ${all_summaries_concatenated + "\n" + summary}
        - reduce_summary:
            call: ask_gemini_for_summary
            args:
                textToSummarize: ${all_summaries_concatenated}
            result: final_summary
        - return_result:
            return:
                - summaries: ${summaries}
                - final_summary: ${final_summary}
    
    ask_gemini_for_summary:
        params: [textToSummarize]
        steps:
            - init:
                assign:
                    - project: ${sys.get_env("GOOGLE_CLOUD_PROJECT_ID")}
                    - location: "us-central1"
                    - model: "gemini-pro"
                    - summary: ""
            - call_gemini:
                call: http.post
                args:
                    url: ${"https://" + location + "-aiplatform.googleapis.com" + "/v1/projects/" + project + "/locations/" + location + "/publishers/google/models/" + model + ":generateContent"}
                    auth:
                        type: OAuth2
                    body:
                        contents:
                            role: user
                            parts:
                                - text: '${"Make a summary of the following text:\n\n" + textToSummarize}'
                        generation_config:
                            temperature: 0.2
                            maxOutputTokens: 2000
                            topK: 10
                            topP: 0.9
                result: gemini_response
            # Sometimes, there's no text, for example, due to safety settings
            - check_text_exists:
                switch:
                - condition: ${not("parts" in gemini_response.body.candidates[0].content)}
                  next: return_summary
            - extract_text:
                assign:
                    - summary: ${gemini_response.body.candidates[0].content.parts[0].text}
            - return_summary:
                return: ${summary}
  3. 次のコマンドを入力してワークフローをデプロイします。

    gcloud workflows deploy gemini-pro-summaries \
        --source=gemini-pro-summaries.yaml \
        --location=us-central1 \
        --service-account=SERVICE_ACCOUNT_NAME@PROJECT_ID.iam.gserviceaccount.com

クリーンアップ

このチュートリアルで使用したリソースについて、Google Cloud アカウントに課金されないようにするには、リソースを含むプロジェクトを削除するか、プロジェクトを維持して個々のリソースを削除します。

プロジェクトの削除

コンソール

  1. In the Google Cloud console, go to the Manage resources page.

    Go to Manage resources

  2. In the project list, select the project that you want to delete, and then click Delete.
  3. In the dialog, type the project ID, and then click Shut down to delete the project.

gcloud

Delete a Google Cloud project:

gcloud projects delete PROJECT_ID

リソースを個別に削除する

このチュートリアルで作成したワークフローを削除します

次のステップ