OpenTelemetry Vertex AI Instrumentation
This library provides OpenTelemetry instrumentation for Google Cloud's Vertex AI, allowing developers to trace prompts, completions, and embeddings from Vertex AI models. It integrates with the official Vertex AI Python client library. The current version is 0.58.0, with frequent releases, often multiple times a month, reflecting active development.
Warnings
- breaking The library frequently updates to conform with evolving OpenTelemetry Generative AI Semantic Conventions (GenAI SemConv). This may lead to changes in span attribute names and data structures across minor versions, requiring adjustments in how you query or analyze your traces.
- gotcha By default, this instrumentation logs prompts, completions, and embeddings to span attributes, which may contain sensitive user data. For privacy reasons or to reduce trace size, you might want to disable this behavior.
- gotcha This instrumentation relies on the `google-cloud-aiplatform` and `google-generativeai` libraries. Ensure that compatible versions of these libraries are installed alongside the instrumentation to avoid runtime errors or incomplete tracing. Specific compatibility requirements may evolve.
Install
-
pip install opentelemetry-instrumentation-vertexai -
pip install opentelemetry-sdk google-cloud-aiplatform google-generativeai
Imports
- VertexAIInstrumentor
from opentelemetry.instrumentation.vertexai import VertexAIInstrumentor
Quickstart
import os
import vertexai
from vertexai.generative_models import GenerativeModel
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.vertexai import VertexAIInstrumentor
# Configure OpenTelemetry SDK
resource = Resource.create({"service.name": "vertexai-app-example"})
tracer_provider = TracerProvider(resource=resource)
tracer_provider.add_span_processor(SimpleSpanProcessor(ConsoleSpanExporter()))
trace.set_tracer_provider(tracer_provider)
# Instrument Vertex AI
VertexAIInstrumentor().instrument()
# Initialize Vertex AI (ensure GOOGLE_APPLICATION_CREDENTIALS or gcloud auth is set)
# For a real application, consider explicit project/location via env vars or arguments
project_id = os.environ.get('GCP_PROJECT_ID', 'your-gcp-project-id')
location = os.environ.get('GCP_LOCATION', 'us-central1')
vertexai.init(project=project_id, location=location)
# Use Vertex AI GenerativeModel
model = GenerativeModel("gemini-1.5-flash")
print(f"\n--- Invoking Vertex AI model ({model.model_name}) ---\n")
response = model.generate_content("Explain the importance of OpenTelemetry in AI observability.")
print("Response from model:")
for part in response.candidates[0].content.parts:
print(part.text)
print("\n--- Traces should be visible in console output ---\n")