Guida rapida all'API Gemini in Vertex AI

Questa guida rapida illustra come installare l'SDK Google Gen AI per il linguaggio scelto e inviare la prima richiesta API. I sample variano leggermente a seconda che tu stia utilizzando una chiave API o le credenziali predefinite dell'applicazione (ADC) per l'autenticazione.

Scegli il metodo di autenticazione:


Prima di iniziare

Se non hai configurato le credenziali predefinite dell'applicazione, consulta Configurare le credenziali predefinite dell'applicazione.

Configura l'ambiente

Python

  1. Utilizzando Python 3.9 o versioni successive, installa l'SDK Google Gen AI:

    pip install -q -U google-genai
  2. Imposta le variabili di ambiente:

    export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID

REST

Imposta le variabili di ambiente:

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID

Effettua la tua prima richiesta

Utilizza il metodo generateContent per inviare una richiesta all'API Gemini in Vertex AI:

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

Genera immagini

Gemini può generare ed elaborare immagini in modo conversazionale. Puoi fornire a Gemini testo, immagini o una combinazione di entrambi per svolgere varie attività correlate alle immagini, come la generazione e la modifica delle immagini. Il seguente codice dimostra come generare un'immagine in base a un prompt descrittivo:

Devi includere responseModalities: ["TEXT", "IMAGE"] nella configurazione. L'output solo immagine non è supportato con questi modelli.

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

Comprensione delle immagini

Gemini può comprendere anche le immagini. Il seguente codice utilizza l'immagine generata nella sezione precedente e un modello diverso per dedurre informazioni sull'immagine:

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. Imposta una variabile shell per l'immagine che stai utilizzando:

    export B64_BASE_IMAGE=YOUR_B64_ENCODED_IMAGE
  2. Esegui questo comando:

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

Esecuzione del codice

La funzionalità di esecuzione del codice dell'API Gemini in Vertex AI consente al modello di generare ed eseguire codice Python e di apprendere in modo iterativo dai risultati fino a ottenere un output finale. Vertex AI fornisce l'esecuzione di codice come strumento, in modo simile alla chiamata di funzione. Puoi utilizzare questa funzionalità di esecuzione di codice per creare applicazioni che sfruttano il ragionamento basato su codice e producono output di testo. Ad esempio:

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

Per altri esempi di esecuzione di codice, consulta la documentazione sull'esecuzione del codice.

Passaggi successivi

Ora che hai effettuato la tua prima richiesta API, ti consigliamo di consultare le seguenti guide che mostrano come configurare funzionalità Vertex AI più avanzate per il codice di produzione: