Guía de inicio rápido de la API de Gemini en Vertex AI

En esta guía de inicio rápido, se muestra cómo instalar el SDK de Google Gen AI para el lenguaje que elijas y, luego, realizar tu primera solicitud a la API. Los ejemplos varían ligeramente según si usas una clave de API o credenciales predeterminadas de la aplicación (ADC) para la autenticación.

Elige un método de autenticación:


Antes de comenzar

Si no configuraste las credenciales predeterminadas de la aplicación, consulta Cómo configurar credenciales predeterminadas de la aplicación.

Configura tu entorno

Python

  1. Con Python 3.9 o versiones posteriores, instala el SDK de IA generativa de Google:

    pip install -q -U google-genai
  2. Establece las variables de entorno:

    export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID

REST

Establece las variables de entorno:

export GOOGLE_CLOUD_PROJECT=YOUR_PROJECT_ID

Realiza tu primera solicitud

Usa el método generateContent para enviar una solicitud a la API de Gemini en 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"
    }
  }
}'
      

Generar imágenes

Gemini puede generar y procesar imágenes de forma conversacional. Puedes indicarle a Gemini texto, imágenes o una combinación de ambos para realizar varias tareas relacionadas con las imágenes, como la generación y edición de imágenes. En el siguiente código, se muestra cómo generar una imagen en función de una instrucción descriptiva:

Debes incluir responseModalities: ["TEXT", "IMAGE"] en tu configuración. No se admite la salida de solo imagen con estos modelos.

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

Comprensión de imágenes

Gemini también puede entender las imágenes. En el siguiente código, se usa la imagen generada en la sección anterior y se usa un modelo diferente para inferir información sobre la imagen:

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. Establece una variable de shell para la imagen que usas:

    export B64_BASE_IMAGE=YOUR_B64_ENCODED_IMAGE
  2. Ejecuta el siguiente 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",
              }
            }
          ]
        }
      ]
    }'
              

Ejecución de código

La API de Gemini en la función de ejecución de código de Vertex AI permite que el modelo genere y ejecute código de Python y aprenda de forma iterativa a partir de los resultados hasta llegar a un resultado final. Vertex AI proporciona la ejecución de código como una herramienta, de forma similar a las llamadas a funciones. Puedes usar esta función de ejecución de código para crear aplicaciones que se beneficien del razonamiento basado en código y que produzcan resultados de texto. Por ejemplo:

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

Para obtener más ejemplos de ejecución de código, consulta la documentación de ejecución de código.

¿Qué sigue?

Ahora que realizaste tu primera solicitud a la API, te recomendamos que explores las siguientes guías que muestran cómo configurar funciones más avanzadas de Vertex AI para el código de producción: