Files
gemini-ent/examples/call_gemini.py
T

97 lines
4.1 KiB
Python

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()