Vertex AI の Gemini API クイックスタート

このクイックスタートでは、任意の言語の Google Gen AI SDK をインストールして、最初の API リクエストを行う方法について説明します。サンプルは、認証にAPI キーを使用するか、アプリケーションのデフォルト認証情報(ADC)を使用するかによって若干異なります。

認証方法を選択します。


始める前に

アプリケーションのデフォルト認証情報を設定していない場合は、アプリケーションのデフォルト認証情報を構成するをご覧ください。

環境の設定

Python

  1. Python 3.9 以降を使用して、Google Gen AI SDK をインストールします。

    pip install -q -U google-genai
  2. 環境変数を設定します。

    export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID

REST

環境変数を設定します。

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID

最初のリクエストを送信する

generateContent メソッドを使用して、Vertex AI の Gemini API にリクエストを送信します。

Python

from google import genai

client = genai.Client(vertexai=True, project="${GOOGLE_CLOUD_PROJECT}", location="global")

response = client.models.generate_content(
    model="gemini-2.0-flash", contents="Explain how AI works in a few words"
)
print(response.text)
      

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://aiplatform.googleapis.com/v1/projects/${GOOGLE_CLOUD_PROJECT}/locations/global/publishers/google/models/gemini-2.0-flash-001:generateContent -d \
$'{
  "contents": {
    "role": "user",
    "parts": {
      "text": "Explain how AI works in a few words"
    }
  }
}'
      

画像を生成

Gemini は、会話を通じて画像を生成、処理できます。Gemini にテキスト、画像、またはその両方のプロンプトを送信して、画像の生成や編集など、さまざまな画像関連タスクを実行できます。次のコードは、記述的なプロンプトに基づいて画像を生成する方法を示しています。

構成に responseModalities: ["TEXT", "IMAGE"] を含める必要があります。これらのモデルでは、画像のみの出力はサポートされていません。

Python

from google import genai
from google.genai import types
from PIL import Image
from io import BytesIO
import base64

client = genai.Client(vertexai=True, project="${GOOGLE_CLOUD_PROJECT}", location="global")

contents = ('Hi, can you create an image of the Eiffel tower with fireworks in the background?')

response = client.models.generate_content(
    model="gemini-2.0-flash-preview-image-generation",
    contents=contents,
    config=types.GenerateContentConfig(
      response_modalities=['TEXT', 'IMAGE']
    )
)


for part in response.candidates[0].content.parts:
  if part.text is not None:
    print(part.text)
  elif part.inline_data is not None:
    image = Image.open(BytesIO((part.inline_data.data)))
    image.save('gemini-native-image.png')
    image.show()
      

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://aiplatform.googleapis.com/v1/projects/${GOOGLE_CLOUD_PROJECT}/locations/global/publishers/google/models/gemini-2.0-flash-preview-image-generation:generateContent -d \
$'{
  "contents": {
    "role": "user",
    "parts": {
      "text": "Can you create an image of the Eiffel tower with fireworks in the background?"
    }
  },
  "generationConfig": {
    "responseModalities":["TEXT","IMAGE"]
  }
}'
      

画像の理解

Gemini は画像も理解できます。次のコードでは、前のセクションで生成された画像を使用し、別のモデルを使用して画像に関する情報を推測します。

Python

from google import genai
from google.genai import types


with open("gemini-native-image.png", "rb") as f:
    image = f.read()


client = genai.Client(vertexai=True, project="${GOOGLE_CLOUD_PROJECT}", location="global")


response = client.models.generate_content(
    model="gemini-flash-2.0",
    contents=[
        Part.from_bytes(data=image, mime_type="image/png"),
        "Write a short and engaging blog post based on this picture.",
    ],
)

print(response.text)
'''
Okay, here's a short and engaging blog post inspired by the image:

**Paris Aglow: A Night to Remember!**

WOW! Just look at this image. Fireworks exploding over Paris, the Eiffel Tower brilliantly lit – can you imagine a more magical sight? This is Paris at its most dazzling, a city transformed into a canvas of light and color.

The Eiffel Tower, the iconic symbol of Paris, stands proud amidst the spectacle.  It's illuminated in blue, adding to the magical atmosphere of the celebrations.

Whether it's a special occasion, a national holiday, or just a spontaneous celebration of life, Paris knows how to put on a show. This image is a reminder of the city's enduring beauty and its power to inspire awe. Have you ever witnessed the magic of Paris? Let me know in the comments!
'''
      

REST

  1. 使用しているイメージのシェル変数を設定します。

    export B64_BASE_IMAGE=YOUR_B64_ENCODED_IMAGE
  2. 次のコマンドを実行します。

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json" \
    https://aiplatform.googleapis.com/v1/projects/${GOOGLE_CLOUD_PROJECT}/locations/global/publishers/google/models/gemini-2.0-flash:generateContent -d \
    $'{
      "contents": [
        {
          "role": "user",
          "parts": [
            {"text": "Write a short and engaging blog post based on this picture."},
            {"inlineData": {
                "data": "${B64_BASE_IMAGE}",
                "mimeType": "image/png",
              }
            }
          ]
        }
      ]
    }'
              

コードの実行

Vertex AI の Gemini API のコード実行機能を使用すると、モデルは Python コードを生成して実行し、最終的な出力に到達するまで結果から反復的に学習できます。Vertex AI は、関数呼び出しと同様に、コード実行をツールとして提供します。このコード実行機能を使用すると、コードベースの推論を活用し、テキスト出力を生成するアプリケーションを構築できます。次に例を示します。

Python

from google import genai
from google.genai import types

client = genai.Client(vertexai=True, project="${GOOGLE_CLOUD_PROJECT}", location="global")

response = client.models.generate_content(
  model="gemini-2.0-flash",
  contents="What is the sum of the first 50 prime numbers? "
  "Generate and run code for the calculation, and make sure you get all 50.",
  config=types.GenerateContentConfig(
      tools=[types.Tool(code_execution=types.ToolCodeExecution)]
  ),
)

for part in response.candidates[0].content.parts:
  if part.text is not None:
      print(part.text)
  if part.executable_code is not None:
      print(part.executable_code.code)
  if part.code_execution_result is not None:
      print(part.code_execution_result.output)
      

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/v1/projects/${GOOGLE_CLOUD_PROJECT}/locations/us-central1/publishers/google/models/gemini-2.0-flash-001:generateContent -d \
$'{
  "tools": [{'codeExecution': {}}],
  "contents": {
    "role": "user",
    "parts": {
      "text": "What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50."
    }
  },
}'
      

コード実行のその他の例については、コード実行のドキュメントをご覧ください。

次のステップ

最初の API リクエストを送信したので、本番環境コード用に高度な Vertex AI 機能を設定する方法について、次のガイドをご覧ください。