Kurzanleitung: Gemini API in Vertex AI

In dieser Kurzanleitung erfahren Sie, wie Sie das Google Gen AI SDK für die gewünschte Sprache installieren und dann Ihre erste API-Anfrage senden. Die Beispiele unterscheiden sich geringfügig, je nachdem, ob Sie für die Authentifizierung einen API-Schlüssel oder Standardanmeldedaten für Anwendungen (ADC) verwenden.

Wählen Sie die Authentifizierungsmethode aus:


Hinweise

Wenn Sie noch keine Standardanmeldedaten für Anwendungen eingerichtet haben, lesen Sie den Hilfeartikel Standardanmeldedaten für Anwendungen konfigurieren.

Umgebung einrichten

Python

  1. Installieren Sie das Google Gen AI SDK mit Python 3.9 oder höher:

    pip install -q -U google-genai
  2. Legen Sie Umgebungsvariablen fest:

    export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID

REST

Legen Sie Umgebungsvariablen fest:

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID

Erste Anfrage senden

Verwenden Sie die Methode generateContent, um eine Anfrage an die Gemini API in Vertex AI zu senden:

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"
    }
  }
}'
      

Bilder erstellen

Gemini kann Bilder in Unterhaltungen generieren und verarbeiten. Sie können Gemini mit Text, Bildern oder einer Kombination aus beiden Prompts geben, um verschiedene bildbezogene Aufgaben auszuführen, z. B. Bildgenerierung und ‑bearbeitung. Der folgende Code zeigt, wie ein Bild anhand eines beschreibenden Prompts generiert wird:

Sie müssen responseModalities: ["TEXT", "IMAGE"] in Ihre Konfiguration aufnehmen. Die Ausgabe von reinen Bildern wird bei diesen Modellen nicht unterstützt.

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"]
  }
}'
      

Bilder verstehen

Gemini kann auch Bilder verstehen. Im folgenden Code wird das im vorherigen Abschnitt generierte Bild verwendet und mit einem anderen Modell werden Informationen zum Bild abgeleitet:

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. Legen Sie eine Shell-Variable für das verwendete Image fest:

    export B64_BASE_IMAGE=YOUR_B64_ENCODED_IMAGE
  2. Führen Sie dazu diesen Befehl aus:

    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",
              }
            }
          ]
        }
      ]
    }'
              

Codeausführung

Die Funktion „Codeausführung“ der Gemini API in Vertex AI ermöglicht es dem Modell, Python-Code zu generieren und auszuführen und iterativ aus den Ergebnissen zu lernen, bis das Modell eine endgültige Ausgabe erstellt hat. Vertex AI stellt die Codeausführung ähnlich wie den Funktionsaufruf als Tool zur Verfügung. Sie können diese Codeausführungsfunktion verwenden, um Anwendungen zu erstellen, die die Vorteile codebasierter Schlussfolgerungen nutzen und Textausgaben erzeugen. Beispiel:

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."
    }
  },
}'
      

Weitere Beispiele für die Codeausführung finden Sie in der Dokumentation zur Codeausführung.

Nächste Schritte

Nachdem Sie Ihre erste API-Anfrage gesendet haben, sollten Sie sich die folgenden Anleitungen ansehen, in denen beschrieben wird, wie Sie erweiterte Vertex AI-Funktionen für Produktionscode einrichten: