Vertex AI를 사용하여 워크플로에서 Gemini 모델에 액세스

Vertex AI의 생성형 AI(genAI 또는 gen AI라고도 함)를 통해 다양한 형식(텍스트, 코드, 이미지, 음성)으로 Google의 생성형 AI 모델에 액세스할 수 있습니다. 이러한 대규모 언어 모델(LLM)을 테스트하고 조정한 후 AI 기반 애플리케이션에서 사용하도록 배포할 수 있습니다. 자세한 내용은 Vertex AI의 생성형 AI 개요를 참조하세요.

Vertex AI에는 이 가이드에 사용된 모델을 포함하여 API를 통해 액세스할 수 있는 다양한 생성형 AI 기반 모델이 있습니다. 모델을 선택하는 방법에 대한 자세한 내용은 Google 모델을 참고하세요.

각 모델은Google Cloud 프로젝트에 따라 달라지는 게시자 엔드포인트를 통해 노출되므로, 특정 사용 사례에 맞게 조정해야 하는 경우가 아니라면 기반 모델을 배포할 필요가 없습니다. 게시자 엔드포인트에 프롬프트를 보낼 수 있습니다. 프롬프트는 응답을 다시 유도하기 위해 LLM에 전송되는 자연어 요청입니다.

이 튜토리얼에서는 Workflow 커넥터 또는 HTTP POST 요청을 통해 텍스트 프롬프트를 게시자 엔드포인트로 전송하여 Vertex AI 모델에서 응답을 생성하는 워크플로를 보여줍니다. 자세한 내용은 Vertex AI API 커넥터 개요HTTP 요청 수행을 참조하세요.

각 워크플로는 서로 독립적으로 배포하고 실행할 수 있습니다.

이미지를 설명하는 워크플로 배포

커넥터 메서드(generateContent)를 사용하여 모델 게시자 엔드포인트에 요청을 수행하는 워크플로를 배포합니다. 이 메서드는 멀티모달 입력을 통한 콘텐츠 생성을 지원합니다.

이 워크플로는 텍스트 프롬프트와 Cloud Storage 버킷에서 공개적으로 사용 가능한 이미지의 URI를 제공합니다. 이미지를 볼 수 있으며 Google Cloud 콘솔에서 객체 세부정보를 볼 수 있습니다.

이 워크플로는 모델의 생성된 응답에서 이미지 설명을 반환합니다.

LLM에 프롬프트를 표시할 때 사용되는 HTTP 요청 본문 매개변수와 응답 본문 요소에 대한 자세한 내용은 Gemini API 참조를 확인하세요.

콘솔

  1. Google Cloud 콘솔에서 Workflows 페이지로 이동합니다.

    Workflows로 이동

  2. 만들기를 클릭합니다.

  3. 새 워크플로의 이름 describe-image를 입력합니다.

  4. 리전 목록에서 us-central1(아이오와)을 선택합니다.

  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 콘솔에서 Workflows 페이지로 이동합니다.

    Workflows로 이동

  2. Workflows 페이지에서 describe-image 워크플로를 선택하여 세부정보 페이지로 이동합니다.

  3. Workflows 세부정보 페이지에서 실행을 클릭합니다.

  4. 입력에서 다음을 입력합니다.

    {"image_url":"gs://generativeai-downloads/images/scones.jpg"}
  5. 실행을 다시 클릭합니다.

  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 콘솔에서 Workflows 페이지로 이동합니다.

    Workflows로 이동

  2. 만들기를 클릭합니다.

  3. 새 워크플로의 이름 gemini-pro-country-histories를 입력합니다.

  4. 리전 목록에서 us-central1(아이오와)을 선택합니다.

  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 콘솔에서 Workflows 페이지로 이동합니다.

    Workflows로 이동

  2. Workflows 페이지에서 gemini-pro-country-histories 워크플로를 선택하여 세부정보 페이지로 이동합니다.

  3. Workflows 세부정보 페이지에서 실행을 클릭합니다.

  4. 입력에서 다음을 입력합니다.

    {"countries":["Argentina", "Bhutan", "Cyprus", "Denmark", "Ethiopia"]}
  5. 실행을 다시 클릭합니다.

  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 요청을 병렬로 수행합니다. 이 워크플로는 마침내 요약된 부분을 완전한 요약으로 결합합니다.

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 콘솔에서 Workflows 페이지로 이동합니다.

    Workflows로 이동

  2. 만들기를 클릭합니다.

  3. 새 워크플로의 이름 gemini-pro-summaries를 입력합니다.

  4. 리전 목록에서 us-central1(아이오와)을 선택합니다.

  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