OpenTelemetry Google Generative AI Instrumentation

0.58.0 · active · verified Fri Apr 10

This library provides OpenTelemetry automatic instrumentation for the `google-generativeai` Python client, enabling distributed tracing of calls to Google's Generative AI models. It is part of the broader OpenLLMetry project, which focuses on LLM observability, and has a frequent release cadence, often aligning with updates to OpenTelemetry GenAI semantic conventions. The current version is 0.58.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up the OpenTelemetry SDK with a console exporter, initialize the `GoogleGenerativeAIInstrumentor`, and then make a request using the `google-generativeai` client. Traces for the `generate_content` call will be printed to the console.

import os
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.google_generativeai import GoogleGenerativeAIInstrumentor
import google.generativeai as genai

# Configure OpenTelemetry SDK for console output
resource = Resource.create({"service.name": "google-generativeai-example"})
provider = TracerProvider(resource=resource)
processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# Initialize the Google Generative AI instrumentation
GoogleGenerativeAIInstrumentor().instrument()

# Configure Google Generative AI with API key
genai.configure(api_key=os.environ.get("GOOGLE_API_KEY", ""))

# Make a call to the Generative AI model
if genai.get_default_base_url(): # Check if API key might be configured
    try:
        model = genai.GenerativeModel('gemini-pro')
        print("Calling Gemini-Pro...")
        response = model.generate_content("What is OpenTelemetry?", stream=False)
        print(f"Response: {response.text[:100]}...")
    except Exception as e:
        print(f"Error calling Google Generative AI: {e}")
        print("Ensure GOOGLE_API_KEY environment variable is set.")
else:
    print("Google Generative AI API key not configured. Set GOOGLE_API_KEY environment variable.")

view raw JSON →