Vertex AI を使用してワークフローから Gemini モデルにアクセスする

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

Vertex AI には、このガイドで使用されているモデルなど、API を介してアクセス可能なさまざまな生成 AI 基盤モデルがあります。モデルを選択する方法については、Google モデルをご覧ください。

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

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

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

画像を説明するワークフローをデプロイする

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

このワークフローは、テキスト プロンプトと、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-2.5-flash"
                - 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. [デプロイ] をクリックします。

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-2.5-flash"
                - 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

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

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

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

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-2.5-flash"
                - 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. [デプロイ] をクリックします。

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-2.5-flash"
                - 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

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

大きなドキュメントを小さな部分に分割するワークフローをデプロイし、モデル パブリッシャー エンドポイントへの http.post リクエストを並列で実行して、モデルが各部分を同時に要約できるようにします。ワークフローが最終的に、部分的なサマリーをすべて 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-2.5-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. [デプロイ] をクリックします。

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-2.5-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