Vertex AI Gemini API 사용해 보기

이 페이지에서는 Google Cloud 콘솔, 프로그래밍 언어 SDK 또는 REST API를 사용하여 신속하게 Vertex AI Gemini API로 요청 전송을 시작하는 방법을 보여줍니다.

Google Cloud 처음 사용

Google Cloud에서 설정

Google Cloud를 처음 사용하는 경우 계정을 만들고 Google 제품의 실제 성능을 평가해 보세요. 신규 고객에게는 워크로드를 실행, 테스트, 배포하는 데 사용할 수 있는 $300의 무료 크레딧이 제공됩니다. 설정 프로세스는 간단한 3단계입니다.

가입 스크린샷

다음 버튼을 사용하여 계정을 만듭니다. 완료되면 이 페이지로 돌아와 이 초보자 튜토리얼을 완료합니다. 이 사이트에서 제공되는 모든 기능을 사용하려면 계정을 사용하여 로그인합니다.

계정 만들기

Google Cloud에서 설정하는 방법에 대한 자세한 내용은 Google Cloud에서 설정을 참조하세요.

Vertex AI Gemini API에 요청 보내기

Vertex AI Gemini API에 요청을 보내는 방법을 보려면 다음 탭 중 하나를 선택합니다.

Python

  1. 다음을 수행하여 Google Cloud 프로젝트를 선택합니다.
    1. Google Cloud 콘솔에서 대시보드 페이지로 이동합니다.

      대시보드 페이지로 이동

    2. 페이지 상단의 프로젝트 선택 목록을 클릭합니다. 리소스 선택 창이 나타나면 프로젝트를 선택합니다.

    3. 프로젝트 정보 섹션에 표시된 프로젝트 ID를 기록합니다. 이후 단계에서 프로젝트 ID가 필요합니다.
  2. Google Cloud 콘솔에서 Cloud Shell을 활성화합니다.

    Cloud Shell 활성화

    Google Cloud 콘솔 하단에서 Cloud Shell 세션이 시작되고 명령줄 프롬프트가 표시됩니다. Cloud Shell은 Google Cloud CLI가 사전 설치된 셸 환경으로, 현재 프로젝트의 값이 이미 설정되어 있습니다. 세션이 초기화되는 데 몇 초 정도 걸릴 수 있습니다.

  3. Cloud Shell에서 다음 명령어를 실행하여 Python용 Vertex AI SDK를 설치하거나 업데이트합니다.

    pip3 install "google-cloud-aiplatform>=1.38"
    
  4. 프롬프트 요청을 보냅니다. PROJECT_ID를 Google Cloud 프로젝트의 ID로 바꿉니다.

    # TODO(developer): Vertex AI SDK - uncomment below & run
    # pip3 install --upgrade --user google-cloud-aiplatform
    # gcloud auth application-default login
    
    import vertexai
    from vertexai.generative_models import GenerativeModel, Part
    
    # Initialize Vertex AI
    vertexai.init(project=project_id, location=location)
    # Load the model
    multimodal_model = GenerativeModel(model_name="gemini-1.0-pro-vision-001")
    # Query the model
    response = multimodal_model.generate_content(
        [
            # Add an example image
            Part.from_uri(
                "gs://generativeai-downloads/images/scones.jpg", mime_type="image/jpeg"
            ),
            # Add an example query
            "what is shown in this image?",
        ]
    )
    print(response)
    return response.text
    
    

    Python용 Vertex AI SDK 설치, 업데이트, 사용에 대한 자세한 내용은 Python용 Vertex AI SDK 설치Python용 Vertex AI SDK API 참고 문서를 확인하세요.

Node.js

  1. 다음을 수행하여 Google Cloud 프로젝트를 선택합니다.
    1. Google Cloud 콘솔에서 대시보드 페이지로 이동합니다.

      대시보드 페이지로 이동

    2. 페이지 상단의 프로젝트 선택 목록을 클릭합니다. 리소스 선택 창이 나타나면 프로젝트를 선택합니다.

    3. 프로젝트 정보 섹션에 표시된 프로젝트 ID를 기록합니다. 이후 단계에서 프로젝트 ID가 필요합니다.
  2. Google Cloud 콘솔에서 Cloud Shell을 활성화합니다.

    Cloud Shell 활성화

    Google Cloud 콘솔 하단에서 Cloud Shell 세션이 시작되고 명령줄 프롬프트가 표시됩니다. Cloud Shell은 Google Cloud CLI가 사전 설치된 셸 환경으로, 현재 프로젝트의 값이 이미 설정되어 있습니다. 세션이 초기화되는 데 몇 초 정도 걸릴 수 있습니다.

  3. Cloud Shell에서 다음 명령어를 실행하여 Node.js용 Vertex AI SDK를 설치하거나 업데이트합니다.

    npm install @google-cloud/vertexai
    
  4. 프롬프트 요청을 보냅니다. PROJECT_ID를 Google Cloud 프로젝트의 ID로 바꿉니다.

    const {VertexAI} = require('@google-cloud/vertexai');
    
    /**
     * TODO(developer): Update these variables before running the sample.
     */
    async function createNonStreamingMultipartContent(
      projectId = 'PROJECT_ID',
      location = 'us-central1',
      model = 'gemini-1.0-pro-vision',
      image = 'gs://generativeai-downloads/images/scones.jpg',
      mimeType = 'image/jpeg'
    ) {
      // Initialize Vertex with your Cloud project and location
      const vertexAI = new VertexAI({project: projectId, location: location});
    
      // Instantiate the model
      const generativeVisionModel = vertexAI.getGenerativeModel({
        model: model,
      });
    
      // For images, the SDK supports both Google Cloud Storage URI and base64 strings
      const filePart = {
        fileData: {
          fileUri: image,
          mimeType: mimeType,
        },
      };
    
      const textPart = {
        text: 'what is shown in this image?',
      };
    
      const request = {
        contents: [{role: 'user', parts: [filePart, textPart]}],
      };
    
      console.log('Prompt Text:');
      console.log(request.contents[0].parts[1].text);
    
      console.log('Non-Streaming Response Text:');
      // Create the response stream
      const responseStream =
        await generativeVisionModel.generateContentStream(request);
    
      // Wait for the response stream to complete
      const aggregatedResponse = await responseStream.response;
    
      // Select the text from the response
      const fullTextResponse =
        aggregatedResponse.candidates[0].content.parts[0].text;
    
      console.log(fullTextResponse);
    }

    Vertex AI Node.js SDK 설치 및 사용에 대한 자세한 내용은 Node.js용 Vertex AI SDK 참고 문서를 확인하세요.

Java

  1. 다음을 수행하여 Google Cloud 프로젝트를 선택합니다.

    1. Google Cloud 콘솔에서 대시보드 페이지로 이동합니다.

      대시보드 페이지로 이동

    2. 페이지 상단의 프로젝트 선택 목록을 클릭합니다. 리소스 선택 창이 나타나면 프로젝트를 선택합니다.

    3. 프로젝트 정보 섹션에 표시된 프로젝트 ID를 확인합니다. 이후 단계에서 프로젝트 ID가 필요합니다.

  2. Java 개발 환경을 설정합니다.

  3. 다음 명령어를 실행하여 인증합니다. PROJECT_ID를 Google Cloud 프로젝트 ID로 바꾸고 ACCOUNT를 Google Cloud 사용자 이름으로 바꿉니다.

    gcloud config set project PROJECT_ID &&
    gcloud auth login ACCOUNT
    
  4. google-cloud-vertexai를 종속 항목으로 추가합니다.

    <!--If you are using Maven with BOM, add the following in your pom.xml-->
    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>libraries-bom</artifactId>
          <version>26.32.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-vertexai</artifactId>
      </dependency>
    </dependencies>
    
    <!--If you are using Maven without BOM, add the following to your pom.xml-->
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>google-cloud-vertexai</artifactId>
      <version>0.4.0</version>
    </dependency>
    
    <!--If you are using Gradle without BOM, add the following to your build.gradle-->
    implementation 'com.google.cloud:google-cloud-vertexai:0.4.0'
    
  5. 프롬프트 요청을 보냅니다. projectID를 Google Cloud 프로젝트 ID로 설정합니다.

    import com.google.cloud.vertexai.VertexAI;
    import com.google.cloud.vertexai.api.GenerateContentResponse;
    import com.google.cloud.vertexai.generativeai.ContentMaker;
    import com.google.cloud.vertexai.generativeai.GenerativeModel;
    import com.google.cloud.vertexai.generativeai.PartMaker;
    import java.io.IOException;
    
    public class Quickstart {
    
      public static void main(String[] args) throws IOException {
        // TODO(developer): Replace these variables before running the sample.
        String projectId = "your-google-cloud-project-id";
        String location = "us-central1";
        String modelName = "gemini-1.0-pro-vision";
    
        String output = quickstart(projectId, location, modelName);
        System.out.println(output);
      }
    
      // Analyzes the provided Multimodal input.
      public static String quickstart(String projectId, String location, String modelName)
          throws IOException {
        // Initialize client that will be used to send requests. This client only needs
        // to be created once, and can be reused for multiple requests.
        try (VertexAI vertexAI = new VertexAI(projectId, location)) {
          String imageUri = "gs://cloud-samples-data/vertex-ai/llm/prompts/landmark1.png";
    
          GenerativeModel model = new GenerativeModel(modelName, vertexAI);
          GenerateContentResponse response = model.generateContent(ContentMaker.fromMultiModalData(
              PartMaker.fromMimeTypeAndData("image/png", imageUri),
              "What's in this photo"
          ));
    
          return response.toString();
        }
      }
    }

    Vertex AI Java 개발 키트(JDK) 설치 및 사용에 대한 자세한 내용은 Vertex AI JDK 참고 문서를 확인하세요.

Go

  1. 다음을 수행하여 Google Cloud 프로젝트를 선택합니다.
    1. Google Cloud 콘솔에서 대시보드 페이지로 이동합니다.

      대시보드 페이지로 이동

    2. 페이지 상단의 프로젝트 선택 목록을 클릭합니다. 리소스 선택 창이 나타나면 프로젝트를 선택합니다.

    3. 프로젝트 정보 섹션에 표시된 프로젝트 ID를 기록합니다. 이후 단계에서 프로젝트 ID가 필요합니다.
  2. Go 개발을 위해 환경을 준비합니다.
  3. 사용 가능한 Vertex AI API Go 패키지를 검토하여 프로젝트 요구에 가장 적합한 패키지를 확인합니다.

    • 패키지 cloud.google.com/go/vertexai (권장)

      vertexai는 일반적인 기능에 대한 액세스를 제공하는 인간이 작성한 패키지입니다.

      이 패키지는 Vertex AI API를 사용하여 빌드하는 대부분의 개발자에게 시작점으로 권장됩니다. 이 패키지에 아직 포함되지 않은 기능을 이용하려면 자동 생성된 aiplatform을 사용하세요.

    • 패키지 cloud.google.com/go/aiplatform

      aiplatform은 자동 생성된 패키지입니다.

      이 패키지는 인간이 작성한 vertexai 패키지에서 아직 제공하지 않는 Vertex AI API 기능에 액세스해야 하는 프로젝트를 대상으로 합니다.

  4. 다음 명령어중 하나를 실행하여 프로젝트 요구에 따라 원하는 Go 패키지를 설치합니다.

    # Human authored package. Recommended for most developers.
    go get cloud.google.com/go/vertexai
    
    # Auto-generated package. go get cloud.google.com/go/aiplatform
  5. 프롬프트 요청을 보냅니다. PROJECT_ID를 Google Cloud 프로젝트의 ID로 바꿉니다.

    import (
    	"context"
    	"encoding/json"
    	"fmt"
    	"io"
    
    	"cloud.google.com/go/vertexai/genai"
    )
    
    func tryGemini(w io.Writer, projectID string, location string, modelName string) error {
    	// location := "us-central1"
    	// modelName := "gemini-1.0-pro-vision-001"
    
    	ctx := context.Background()
    	client, err := genai.NewClient(ctx, projectID, location)
    	if err != nil {
    		return fmt.Errorf("error creating client: %w", err)
    	}
    	gemini := client.GenerativeModel(modelName)
    
    	img := genai.FileData{
    		MIMEType: "image/jpeg",
    		FileURI:  "gs://generativeai-downloads/images/scones.jpg",
    	}
    	prompt := genai.Text("What is in this image?")
    
    	resp, err := gemini.GenerateContent(ctx, img, prompt)
    	if err != nil {
    		return fmt.Errorf("error generating content: %w", err)
    	}
    	rb, err := json.MarshalIndent(resp, "", "  ")
    	if err != nil {
    		return fmt.Errorf("json.MarshalIndent: %w", err)
    	}
    	fmt.Fprintln(w, string(rb))
    	return nil
    }
    

    Go용 Vertex AI SDK 설치 및 사용에 대한 자세한 내용은 Go용 Vertex AI SDK 참고 문서를 확인하세요.

C#

이 샘플을 사용해 보기 전에 Vertex AI 빠른 시작: 클라이언트 라이브러리 사용C# 설정 안내를 따르세요. 자세한 내용은 Vertex AI C# API 참고 문서를 참조하세요.

Vertex AI에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


using Google.Api.Gax.Grpc;
using Google.Cloud.AIPlatform.V1;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

public class GeminiQuickstart
{
    public async Task<string> GenerateContent(
        string projectId = "your-project-id",
        string location = "us-central1",
        string publisher = "google",
        string model = "gemini-1.0-pro-vision"
    )
    {
        // Create client
        var predictionServiceClient = new PredictionServiceClientBuilder
        {
            Endpoint = $"{location}-aiplatform.googleapis.com"
        }.Build();

        // Prompt
        string prompt = "What's in this photo";
        string imageUri = "gs://generativeai-downloads/images/scones.jpg";

        // Initialize request argument(s)
        var content = new Content
        {
            Role = "USER"
        };
        content.Parts.AddRange(new List<Part>()
        {
            new() {
                Text = prompt
            },
            new() {
                FileData = new() {
                    MimeType = "image/png",
                    FileUri = imageUri
                }
            }
        });

        var generateContentRequest = new GenerateContentRequest
        {
            Model = $"projects/{projectId}/locations/{location}/publishers/{publisher}/models/{model}",
            GenerationConfig = new GenerationConfig
            {
                Temperature = 0.4f,
                TopP = 1,
                TopK = 32,
                MaxOutputTokens = 2048
            }
        };
        generateContentRequest.Contents.Add(content);

        // Make the request, returning a streaming response
        using PredictionServiceClient.StreamGenerateContentStream response = predictionServiceClient.StreamGenerateContent(generateContentRequest);

        StringBuilder fullText = new();

        // Read streaming responses from server until complete
        AsyncResponseStream<GenerateContentResponse> responseStream = response.GetResponseStream();
        await foreach (GenerateContentResponse responseItem in responseStream)
        {
            fullText.Append(responseItem.Candidates[0].Content.Parts[0].Text);
        }

        return fullText.ToString();
    }
}

REST

  1. 다음을 수행하여 Google Cloud 프로젝트를 선택합니다.

    1. Google Cloud 콘솔에서 대시보드 페이지로 이동합니다.

      대시보드 페이지로 이동

    2. 페이지 상단의 프로젝트 선택 목록을 클릭합니다. 리소스 선택 창이 나타나면 프로젝트를 선택합니다.

    3. 프로젝트 정보 섹션에 표시된 프로젝트 ID를 확인합니다. 이후 단계에서 프로젝트 ID가 필요합니다.

  2. Google Cloud 콘솔에서 Cloud Shell을 활성화합니다.

    Cloud Shell 활성화

  3. 다음을 입력하여 환경 변수를 구성합니다. PROJECT_ID를 Google Cloud 프로젝트의 ID로 바꿉니다.

    MODEL_ID="gemini-1.0-pro-vision"
    PROJECT_ID="PROJECT_ID"
    
  4. 엔드포인트를 프로비저닝합니다.

    gcloud beta services identity create --service=aiplatform.googleapis.com --project=PROJECT_ID
    
  5. 다음 curl 명령어를 입력하여 프롬프트 요청을 보냅니다.

    curl \
    -X POST \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json" \
    https://us-central1-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/us-central1/publishers/google/models/${MODEL_ID}:streamGenerateContent -d \
    $'{
      "contents": {
        "role": "user",
        "parts": [
          {
          "fileData": {
            "mimeType": "image/jpeg",
            "fileUri": "gs://generativeai-downloads/images/scones.jpg"
            }
          },
          {
            "text": "Describe this picture."
          }
        ]
      }
    }'
    
  6. Cloud Shell을 승인하라는 메시지가 표시되면 승인을 클릭합니다.

    모델이 응답을 반환합니다. 응답은 여러 섹션으로 생성되고, 안전을 위해 각 섹션이 개별적으로 평가됩니다.

콘솔

Vertex AI Studio를 사용하여 프롬프트를 빠르게 설계하고 반복할 수 있습니다. 프롬프트가 준비되면 지원되는 프로그래밍 언어로 프롬프트 코드를 가져올 수 있습니다.

  1. 다음을 수행하여 Google Cloud 프로젝트를 선택합니다.
    1. Google Cloud 콘솔에서 대시보드 페이지로 이동합니다.

      대시보드 페이지로 이동

    2. 페이지 상단의 프로젝트 선택 목록을 클릭합니다. 리소스 선택 창이 나타나면 프로젝트를 선택합니다.

  2. Google Cloud 콘솔에서 Vertex AI Studio 페이지로 이동합니다.

    Vertex AI Studio

  3. 멀티모달을 클릭합니다.

  4. 샘플 프롬프트에서 이미지에서 텍스트 추출이라는 프롬프트를 찾고 열기를 클릭합니다.

    프롬프트 페이지가 열리고 프롬프트 필드에 프롬프트가 채워집니다.

  5. 제출을 클릭하여 프롬프트를 제출합니다.

    모델이 응답을 반환합니다.

  6. 코드 가져오기를 클릭하여 이 프롬프트 요청에 해당하는 코드를 확인합니다.

다음 단계