워크플로에서 Vertex AI 모델 액세스


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

Vertex AI에는 다음 예시에 사용된 모델을 포함하여 API를 통해 액세스할 수 있는 다양한 생성형 AI 기반 모델이 있습니다.

  • Gemini Pro는 자연어 태스크, 멀티턴 텍스트 및 코드 채팅, 코드 생성을 처리하도록 설계되었습니다.
  • Gemini Pro Vision은 멀티 모달 프롬프트를 지원합니다. 프롬프트 요청에 텍스트, 이미지, 동영상을 포함하고 텍스트 또는 코드 응답을 얻을 수 있습니다.
  • 텍스트용 Pathways Language Model 2(PaLM 2)는 분류, 요약, 항목 추출과 같은 언어 태스크에 맞게 미세 조정됩니다.

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

이 튜토리얼에서는 HTTP POST 요청을 통해 텍스트 프롬프트를 게시자 엔드포인트로 전송하여 Vertex AI 모델에서 응답을 생성하는 4가지 워크플로를 보여줍니다. 각 워크플로는 서로 독립적으로 배포하고 실행할 수 있습니다.

목표

이 튜토리얼에서 학습할 내용은 다음과 같습니다.

  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)에서 국가의 기록을 생성하고 반환하도록 요청합니다. 모델을 선택하는 방법에 대한 자세한 내용은 모델 정보를 참조하세요.
  5. 대규모 문서를 요약할 수 있는 워크플로를 배포합니다. 학습 중(및 예측 시) 모델이 처리하는 기간을 설정하는 컨텍스트 윈도우에는 한도가 있으므로 워크플로는 문서를 더 작은 부분으로 분할한 후 Vertex AI 모델(Gemini Pro)에서 각 부분을 동시에 요약하도록 요청합니다. 자세한 내용은 요약 프롬프트예측 범위, 컨텍스트 윈도우, 예측 기간을 참조하세요.

비용

이 문서에서는 비용이 청구될 수 있는 다음과 같은 Google Cloud 구성요소를 사용합니다.

프로젝트 사용량을 기준으로 예상 비용을 산출하려면 가격 계산기를 사용하세요. Google Cloud를 처음 사용하는 사용자는 무료 체험판을 사용할 수 있습니다.

이 문서에 설명된 태스크를 완료했으면 만든 리소스를 삭제하여 청구가 계속되는 것을 방지할 수 있습니다. 자세한 내용은 삭제를 참조하세요.

시작하기 전에

이 튜토리얼의 예시를 시도하기 전에 다음을 완료했는지 확인합니다.

콘솔

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  2. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  3. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  4. API Vertex AI and Workflows 사용 설정

    API 사용 설정

  5. 서비스 계정을 만듭니다.

    1. Google Cloud Console에서 서비스 계정 만들기 페이지로 이동합니다.

      서비스 계정 만들기로 이동
    2. 프로젝트를 선택합니다.
    3. 서비스 계정 이름 필드에 이름을 입력합니다. Google Cloud 콘솔은 이 이름을 기반으로 서비스 계정 ID 필드를 채웁니다.

      서비스 계정 설명 필드에 설명을 입력합니다. 예를 들면 Service account for quickstart입니다.

    4. 만들고 계속하기를 클릭합니다.
    5. 서비스 계정에 Vertex AI > Vertex AI User 역할을 부여합니다.

      역할을 부여하려면 역할 선택 목록을 찾은 후 Vertex AI > Vertex AI User을 선택합니다.

    6. 계속을 클릭합니다.
    7. 완료를 클릭하여 서비스 계정 만들기를 마칩니다.

  6. Google Cloud Console의 프로젝트 선택기 페이지에서 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기로 이동

  7. Google Cloud 프로젝트에 결제가 사용 설정되어 있는지 확인합니다.

  8. API Vertex AI and Workflows 사용 설정

    API 사용 설정

  9. 서비스 계정을 만듭니다.

    1. Google Cloud Console에서 서비스 계정 만들기 페이지로 이동합니다.

      서비스 계정 만들기로 이동
    2. 프로젝트를 선택합니다.
    3. 서비스 계정 이름 필드에 이름을 입력합니다. Google Cloud 콘솔은 이 이름을 기반으로 서비스 계정 ID 필드를 채웁니다.

      서비스 계정 설명 필드에 설명을 입력합니다. 예를 들면 Service account for quickstart입니다.

    4. 만들고 계속하기를 클릭합니다.
    5. 서비스 계정에 Vertex AI > Vertex AI User 역할을 부여합니다.

      역할을 부여하려면 역할 선택 목록을 찾은 후 Vertex AI > Vertex AI User을 선택합니다.

    6. 계속을 클릭합니다.
    7. 완료를 클릭하여 서비스 계정 만들기를 마칩니다.

gcloud

  1. Google Cloud 계정에 로그인합니다. Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다.
  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.com workflows.googleapis.com
  7. 인증을 설정합니다.

    1. 서비스 계정을 만듭니다.

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      SERVICE_ACCOUNT_NAME을 서비스 계정 이름으로 바꿉니다.

    2. 서비스 계정에 roles/aiplatform.user IAM 역할을 부여합니다.

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

      다음을 바꿉니다.

      • SERVICE_ACCOUNT_NAME: 서비스 계정의 이름입니다.
      • PROJECT_ID: 서비스 계정을 만든 프로젝트 ID입니다.
  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.com workflows.googleapis.com
  13. 인증을 설정합니다.

    1. 서비스 계정을 만듭니다.

      gcloud iam service-accounts create SERVICE_ACCOUNT_NAME

      SERVICE_ACCOUNT_NAME을 서비스 계정 이름으로 바꿉니다.

    2. 서비스 계정에 roles/aiplatform.user IAM 역할을 부여합니다.

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

      다음을 바꿉니다.

      • SERVICE_ACCOUNT_NAME: 서비스 계정의 이름입니다.
      • PROJECT_ID: 서비스 계정을 만든 프로젝트 ID입니다.

이미지를 설명하는 워크플로 배포(Gemini Pro Vision)

Gemini Pro Vision 게시자 엔드포인트에 http.post 요청을 수행하는 워크플로를 배포합니다.

이 워크플로는 텍스트 프롬프트와 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-1.0-pro-vision"
                - method: "generateContent"
                - llm_api_endpoint: ${"https://" + location + "-aiplatform.googleapis.com" + "/v1/projects/" + project + "/locations/" + location + "/publishers/google/models/" + model + ":" + method}
                - text_combined: ""
        - ask_llm:
            call: http.post
            args:
                url: ${llm_api_endpoint}
                auth:
                    type: OAuth2
                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.body.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-1.0-pro-vision"
                - method: "generateContent"
                - llm_api_endpoint: ${"https://" + location + "-aiplatform.googleapis.com" + "/v1/projects/" + project + "/locations/" + location + "/publishers/google/models/" + model + ":" + method}
                - text_combined: ""
        - ask_llm:
            call: http.post
            args:
                url: ${llm_api_endpoint}
                auth:
                    type: OAuth2
                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.body.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

국가 기록을 생성하는 워크플로 배포(Gemini Pro)

국가의 입력 목록을 병렬로 반복하는 워크플로를 배포하여 Gemini Pro 게시자 엔드포인트에 http.post 요청을 수행합니다.

이 워크플로는 모델에서 생성된 국가 기록을 반환하고 지도에 결합합니다.

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-1.0-pro"
                - method: "generateContent"
                - llm_api_endpoint: ${"https://" + location + "-aiplatform.googleapis.com" + "/v1/projects/" + project + "/locations/" + location + "/publishers/google/models/" + model + ":" + method}
                - histories: {}
        - loop_over_countries:
            parallel:
                shared: [histories]
                for:
                    value: country
                    in: ${args.countries}
                    steps:
                        - ask_llm:
                            call: http.post
                            args:
                                url: ${llm_api_endpoint}
                                auth:
                                    type: OAuth2
                                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.body.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-1.0-pro"
                - method: "generateContent"
                - llm_api_endpoint: ${"https://" + location + "-aiplatform.googleapis.com" + "/v1/projects/" + project + "/locations/" + location + "/publishers/google/models/" + model + ":" + method}
                - histories: {}
        - loop_over_countries:
            parallel:
                shared: [histories]
                for:
                    value: country
                    in: ${args.countries}
                    steps:
                        - ask_llm:
                            call: http.post
                            args:
                                url: ${llm_api_endpoint}
                                auth:
                                    type: OAuth2
                                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.body.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

국가 기록을 생성하는 워크플로 배포(텍스트용 PaLM 2)

Gemini Pro를 모델로 사용하지 않을 수 있습니다. 다음 예시에서는 앞의 워크플로와 유사한 워크플로를 사용합니다. 하지만 http.post 요청은 텍스트 게시자 엔드포인트에 대한 PaLM 2에서 수행됩니다.

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

콘솔

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

    Workflows로 이동

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

  3. 새 워크플로의 이름 text-bison-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: "text-bison"
                - method: "predict"
                - llm_api_endpoint: ${"https://" + location + "-aiplatform.googleapis.com" + "/v1/projects/" + project + "/locations/" + location + "/publishers/google/models/" + model + ":" + method}
                - histories: {}
        - loop_over_countries:
            parallel:
                shared: [histories]
                for:
                    value: country
                    in: ${args.countries}
                    steps:
                        - ask_llm:
                            call: http.post
                            args:
                                url: ${llm_api_endpoint}
                                auth:
                                    type: OAuth2
                                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.body.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. 배포를 클릭합니다.

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"
                - method: "predict"
                - llm_api_endpoint: ${"https://" + location + "-aiplatform.googleapis.com" + "/v1/projects/" + project + "/locations/" + location + "/publishers/google/models/" + model + ":" + method}
                - histories: {}
        - loop_over_countries:
            parallel:
                shared: [histories]
                for:
                    value: country
                    in: ${args.countries}
                    steps:
                        - ask_llm:
                            call: http.post
                            args:
                                url: ${llm_api_endpoint}
                                auth:
                                    type: OAuth2
                                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.body.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 요청을 병렬로 수행합니다. 이 워크플로는 마침내 요약된 부분을 완전한 요약으로 결합합니다.

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-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-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. Google Cloud 콘솔에서 리소스 관리 페이지로 이동합니다.

    리소스 관리로 이동

  2. 프로젝트 목록에서 삭제할 프로젝트를 선택하고 삭제를 클릭합니다.
  3. 대화상자에서 프로젝트 ID를 입력한 후 종료를 클릭하여 프로젝트를 삭제합니다.

gcloud

Google Cloud 프로젝트를 삭제합니다.

gcloud projects delete PROJECT_ID

개별 리소스 삭제

이 튜토리얼에서 만든 워크플로를 삭제합니다.

다음 단계