Add example scripts and README for Gemini API usage with ADC authentication

This commit is contained in:
2026-06-10 17:51:14 +02:00
parent 66ab4d9863
commit 3577a87948
4 changed files with 183 additions and 1 deletions
+4 -1
View File
@@ -5,4 +5,7 @@ terraform.tfvars
terraform.tfstate terraform.tfstate
terraform.tfstate.backup terraform.tfstate.backup
tfplan* tfplan*
# VS Code
.vscode/*
+82
View File
@@ -0,0 +1,82 @@
# Gemini API Python Examples (Gemini Enterprise Agent Platform (Vertex AI) / ADC Authentication)
This directory contains examples for interacting with the Gemini API using the **`google-genai`** Python SDK and the **`gemini-3.5-flash`** model.
To comply with enterprise security policies that disable static API keys, these examples use the **Gemini Enterprise Agent Platform** (Vertex AI) authenticated via secure **Application Default Credentials (ADC)**.
## Core Features
* **Gemini 3.5 Flash**: Offers frontier-level intelligence, advanced reasoning, and pro-level coding capability inside an ultra-fast, cost-efficient Flash tier.
* **Agentic Capabilities**: Optimized out of the box for handling complex, multi-step agentic workflows and sustained reasoning tasks.
* **Gemini Enterprise Agent Platform (Vertex AI) Integration**: Uses native Google Cloud IAM authorization instead of long-lived API keys.
---
## Prerequisites
1. **Google Cloud Project**: You need an active Google Cloud Project.
2. **Gemini Enterprise Agent Platform (Vertex AI) API Enabled**: Make sure the API (`aiplatform.googleapis.com`) is enabled in your project.
3. **IAM Permissions**: Your Google account (or service account) must have the **Gemini Enterprise Agent Platform User** (Vertex AI User) (`roles/aiplatform.user`) role.
4. **Google Cloud SDK (`gcloud`)**: Installed and configured on your machine.
---
## Setup Guide
### 1. Install Dependencies
Create a virtual environment (optional but recommended) and install the required dependencies:
```bash
# Create and activate a virtual environment
python3 -m venv venv
source venv/bin/activate
# Install the modern google-genai library
pip install -r requirements.txt
```
### 2. Authenticate locally with Application Default Credentials (ADC)
Generate local credentials that the SDK will automatically detect:
```bash
gcloud auth application-default login
```
### 3. Set Environment Variables
Specify your Google Cloud project and region:
```bash
# Set your GCP Project ID (Required)
export GOOGLE_CLOUD_PROJECT="your-gcp-project-id"
# Set your preferred location (Optional, defaults to us-central1)
export GOOGLE_CLOUD_LOCATION="us-central1"
```
---
## Running the Examples
Run the script to verify the connection and see both standard content generation and config-based content generation in action:
```bash
python call_gemini.py
```
---
## Troubleshooting
### "Gemini Enterprise Agent Platform (Vertex AI) API has not been used in project..."
Enable the API on your Google Cloud Console or use the `gcloud` CLI:
```bash
gcloud services enable aiplatform.googleapis.com --project="your-gcp-project-id"
```
### "Permission denied..." or "Lack of IAM permissions..."
Ensure your authenticated user or active service account has the **Gemini Enterprise Agent Platform User** (Vertex AI User) role on your project:
```bash
gcloud projects add-iam-policy-binding your-gcp-project-id \
--member="user:your-email@example.com" \
--role="roles/aiplatform.user"
```
+96
View File
@@ -0,0 +1,96 @@
import os
import sys
from google import genai
from google.genai import types
def main():
# When API keys are disabled by organizational policy, we must authenticate using
# Google Cloud Application Default Credentials (ADC) via the Gemini Enterprise Agent Platform (Vertex AI) API.
# Check for GCP project configuration
project_id = os.environ.get("GOOGLE_CLOUD_PROJECT")
location = os.environ.get("GOOGLE_CLOUD_LOCATION", "us-central1")
if not project_id:
print("Error: GOOGLE_CLOUD_PROJECT environment variable is not set.", file=sys.stderr)
print("Please configure your GCP project using one of the following methods:", file=sys.stderr)
print("\nMethod 1: Set the environment variable directly:", file=sys.stderr)
print(" export GOOGLE_CLOUD_PROJECT=\"your-gcp-project-id\"", file=sys.stderr)
print("\nMethod 2: Authenticate using gcloud CLI Application Default Credentials (ADC):", file=sys.stderr)
print(" gcloud auth application-default login", file=sys.stderr)
print(" gcloud config set project your-gcp-project-id", file=sys.stderr)
sys.exit(1)
print("Initializing Gemini Client via Gemini Enterprise Agent Platform (Vertex AI) using Application Default Credentials (ADC)...")
print(f"Project ID: {project_id}")
print(f"Location: {location}")
print("-" * 50)
try:
# Initialize the Client for Gemini Enterprise Agent Platform (Vertex AI) using Application Default Credentials (ADC).
# Setting vertexai=True routes the request through the Gemini Enterprise Agent Platform (Vertex AI Agent Engine).
client = genai.Client(
vertexai=True,
project=project_id,
location=location
)
except Exception as e:
print(f"Failed to initialize client: {e}", file=sys.stderr)
print("Please ensure you have run 'gcloud auth application-default login'", file=sys.stderr)
sys.exit(1)
# Use the gemini-3.5-flash model, which offers frontier-level reasoning,
# coding capability, and agentic workflows.
model_name = "gemini-2.5-flash"
# Prepare a simple text prompt
prompt = "Explain the concept of containerization in three simple sentences."
print(f"\nSending prompt to model '{model_name}':")
print(f"\"{prompt}\"")
print("-" * 50)
try:
# Send the prompt to Gemini Enterprise Agent Platform (Vertex AI) and get the response
response = client.models.generate_content(
model=model_name,
contents=prompt,
)
# Print the response text
print("Response received:")
print(response.text)
print("-" * 50)
except Exception as e:
print(f"An error occurred while generating content: {e}", file=sys.stderr)
print("\nTroubleshooting tips:", file=sys.stderr)
print("1. Ensure Gemini Enterprise Agent Platform (Vertex AI) API ('aiplatform.googleapis.com') is enabled in your project.", file=sys.stderr)
print("2. Ensure your authenticated identity has the \"Gemini Enterprise Agent Platform User\" (\"Vertex AI User\") role (roles/aiplatform.user).", file=sys.stderr)
sys.exit(1)
# Example 2: Sending a prompt with configuration options (temperature, etc.)
prompt_config = "Describe three advantages of microservices architecture."
print(f"\nSending prompt with configuration to model '{model_name}':")
print(f"\"{prompt_config}\"")
print("-" * 50)
try:
response_config = client.models.generate_content(
model=model_name,
contents=prompt_config,
config=types.GenerateContentConfig(
temperature=0.2, # Lower temperature means more deterministic responses
max_output_tokens=300, # Limit the response length
)
)
print("Response received (with config):")
print(response_config.text)
print("-" * 50)
except Exception as e:
print(f"An error occurred: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
google-genai>=0.1.0