How to get started with Vertex AI
Quick answer
To get started with Vertex AI, install the vertexai Python SDK and authenticate using Google Cloud credentials. Initialize the SDK with your project and location, then create a GenerativeModel instance to generate text with models like gemini-2.0-flash.
PREREQUISITES
Python 3.8+Google Cloud project with Vertex AI enabledGoogle Cloud SDK installed and authenticated (gcloud auth application-default login)pip install vertexai
Setup
Install the vertexai SDK and authenticate your environment with Google Cloud credentials. Set your project ID and location for Vertex AI.
pip install vertexai Step by step
This example shows how to initialize Vertex AI, load the gemini-2.0-flash model, and generate a text completion.
import os
import vertexai
from vertexai import language_models
# Initialize Vertex AI with your Google Cloud project and location
vertexai.init(project=os.environ["GOOGLE_CLOUD_PROJECT"], location="us-central1")
# Load the Gemini 2.0 Flash model
model = language_models.GenerativeModel("gemini-2.0-flash")
# Generate text
response = model.generate_content("Explain quantum computing in simple terms.")
print(response.text) output
Quantum computing is a type of computing that uses quantum bits, or qubits, which can represent both 0 and 1 at the same time. This allows quantum computers to solve certain problems much faster than traditional computers.
Common variations
Use model.generate_content(stream=True) for streaming output. Switch models by changing the model name, e.g., gemini-2.5-pro. Use asynchronous calls with async and await in Python.
import asyncio
async def async_generate():
vertexai.init(project=os.environ["GOOGLE_CLOUD_PROJECT"], location="us-central1")
model = language_models.GenerativeModel("gemini-2.0-flash")
response = await model.generate_content("What is AI?", stream=True)
async for chunk in response:
print(chunk.text, end="", flush=True)
asyncio.run(async_generate()) output
Artificial intelligence (AI) is the simulation of human intelligence processes by machines, especially computer systems...
Troubleshooting
If you see authentication errors, run gcloud auth application-default login to set up credentials. Ensure your Google Cloud project has Vertex AI API enabled. Check your environment variables GOOGLE_CLOUD_PROJECT and GOOGLE_APPLICATION_CREDENTIALS are set correctly.
Key Takeaways
- Install the vertexai SDK and authenticate with Google Cloud before usage.
- Initialize Vertex AI with your project and location to access models like gemini-2.0-flash.
- Use generate_content for text generation, supporting streaming and async calls.
- Verify Google Cloud credentials and API enablement if you encounter errors.