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 コンソールで、「Cloud Shell をアクティブにする」をクリックします。

    Cloud Shell をアクティブにする

    Google Cloud コンソールの下部で Cloud Shell セッションが開始し、コマンドライン プロンプトが表示されます。Cloud Shell はシェル環境です。Google Cloud CLI がすでにインストールされており、現在のプロジェクトの値もすでに設定されています。セッションが初期化されるまで数秒かかることがあります。

  2. Cloud Shell で次のコマンドを実行して、Vertex AI SDK for Python をインストールまたは更新します。

    pip install "google-cloud-aiplatform>=1.38"
    

プロンプト リクエストを送信します。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

def generate_text(project_id: str, location: str) -> str:
    # Initialize Vertex AI
    vertexai.init(project=project_id, location=location)
    # Load the model
    multimodal_model = GenerativeModel("gemini-1.0-pro-vision")
    # 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

Vertex AI SDK for Python のインストールまたは更新の方法については、Vertex AI SDK for Python をインストールするをご覧ください。詳細については、Vertex AI SDK for Python API リファレンス ドキュメントをご覧ください。

Node.js

  1. Google Cloud コンソールで、「Cloud Shell をアクティブにする」をクリックします。

    Cloud Shell をアクティブにする

    Google Cloud コンソールの下部で Cloud Shell セッションが開始し、コマンドライン プロンプトが表示されます。Cloud Shell はシェル環境です。Google Cloud CLI がすでにインストールされており、現在のプロジェクトの値もすでに設定されています。セッションが初期化されるまで数秒かかることがあります。

  2. Cloud Shell で次のコマンドを実行して、Vertex AI SDK for Node.js をインストールまたは更新します。

    npm install @google-cloud/vertexai
    

プロンプト リクエストを送信します。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 のインストール方法と使用方法の詳細については、Vertex AI SDK for Node.js のリファレンス ドキュメントをご覧ください。

Java

  1. Java 開発環境を設定します
  2. 次のコマンドを実行して認証を行います。PROJECT_ID は Google Cloud プロジェクト ID に、ACCOUNT は Google Cloud ユーザー名に置き換えます。

    gcloud config set project PROJECT_ID &&
    gcloud auth login ACCOUNT
    
  3. 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'
    

プロンプト リクエストを送信します。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://generativeai-downloads/images/scones.jpg";

      GenerativeModel model = new GenerativeModel(modelName, vertexAI);
      GenerateContentResponse response = model.generateContent(ContentMaker.fromMultiModalData(
          PartMaker.fromMimeTypeAndData("image/jpg", imageUri),
          "What's in this photo"
      ));

      return response.toString();
    }
  }
}

Vertex AI Java Development Kit(JDK)のインストール方法と使用方法の詳細については、Vertex AI JDK のリファレンス ドキュメントをご覧ください。

Go

  1. Go 開発環境を準備します
  2. 利用可能な Vertex AI API Go パッケージを確認して、プロジェクトのニーズに最適なパッケージを判断します。

    • パッケージ cloud.google.com/go/vertexai推奨

      vertexai は人の手で作成されたパッケージで、一般的な機能へのアクセスを提供します。

      Vertex AI API を使用して構築するほとんどのデベロッパーにとって、これは出発点としておすすめのパッケージです。このパッケージに含まれていない機能にアクセスするには、自動生成された aiplatform を使用してください。

    • パッケージ cloud.google.com/go/aiplatform

      aiplatform は自動生成されたパッケージです。

      このパッケージは、人が作成した vertexai パッケージではまだ提供されていない Vertex AI API 機能にアクセスする必要があるプロジェクトを対象としています。

  3. 次のいずれかのコマンドを実行して、プロジェクトのニーズに基づいて必要な 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

プロンプト リクエストを送信します。PROJECT_ID は、Google Cloud プロジェクトの ID に置き換えます。

import (
	"context"
	"encoding/json"
	"fmt"
	"io"

	"cloud.google.com/go/vertexai/genai"
)

var projectId = "PROJECT_ID"
var region = "us-central1"

func tryGemini(w io.Writer, projectId string, region string, modelName string) error {

	ctx := context.Background()
	client, err := genai.NewClient(ctx, projectId, region)
	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, _ := json.MarshalIndent(resp, "", "  ")
	fmt.Fprintln(w, string(rb))
	return nil
}

Vertex AI SDK for Go のインストール方法と使用方法については、Vertex AI SDK for Go のリファレンス ドキュメントをご覧ください。

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 コンソールで、「Cloud Shell をアクティブにする」をクリックします。

    Cloud Shell をアクティブにする

  2. 次のように入力して、環境変数を構成します。PROJECT_ID は、Google Cloud プロジェクトの ID に置き換えます。

    MODEL_ID="gemini-1.0-pro-vision"
    PROJECT_ID="PROJECT_ID"
    
  3. エンドポイントをプロビジョニングします。

    gcloud beta services identity create --service=aiplatform.googleapis.com --project=PROJECT_ID
    
  4. 次の 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."
          }
        ]
      }
    }'
    
  5. Cloud Shell を承認するよう求められたら、[承認] をクリックします。

    モデルによりレスポンスが返されます。レスポンスはセクション内で生成され、各セクションの安全性が個別に評価されます。

コンソール

Vertex AI Studio を使用し、プロンプトを速やかに設計して反復処理できます。プロンプトの準備ができたら、サポートされているいずれかのプログラミング言語でプロンプトのコードを取得できます。

  1. Google Cloud コンソールで、[Vertex AI Studio] ページに移動します。

    Vertex AI Studio

  2. [マルチモーダル] をクリックします。

  3. [サンプル プロンプト] で、「Extract text from images」というタイトルのプロンプトを見つけて、[オープン] をクリックします。

    プロンプト ページが開き、[Prompt] フィールドにプロンプトが入力されます。

  4. [送信] をクリックしてプロンプトを送信します。

    モデルによりレスポンスが返されます。

  5. [ コードを取得] をクリックして、このプロンプト リクエストと同等のコードを表示します。

次のステップ