OpenTelemetry OpenAI Instrumentation

0.58.0 · active · verified Thu Apr 09

This library provides OpenTelemetry instrumentation for the OpenAI Python SDK, enabling automatic tracing, metric collection (e.g., token usage, duration), and optional logging of prompt and completion content. It is actively maintained by Traceloop/OpenLLMetry and receives frequent updates, currently at version 0.58.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up OpenTelemetry with the `opentelemetry-instrumentation-openai` library. It initializes a basic `TracerProvider` with a `ConsoleSpanExporter` to print traces to the console, then instruments the OpenAI client. Any subsequent OpenAI API calls will automatically generate spans.

import os
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor
from opentelemetry.instrumentation.openai import OpenAIInstrumentor
from openai import OpenAI

# Configure OpenTelemetry Tracer Provider
provider = TracerProvider()
processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# Instrument the OpenAI SDK
OpenAIInstrumentor().instrument()

# Set your OpenAI API key (replace with actual key or use env var)
os.environ['OPENAI_API_KEY'] = os.environ.get('OPENAI_API_KEY', 'sk-YOUR_OPENAI_API_KEY')

# Initialize OpenAI client and make a call
client = OpenAI()

try:
    print("Making an OpenAI chat completion call...")
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "Tell me a short story about a brave knight."}
        ]
    )
    print("OpenAI response received.")
    print(f"Story: {response.choices[0].message.content}")
except Exception as e:
    print(f"An error occurred: {e}")
    print("Ensure OPENAI_API_KEY is set and valid.")

# You should see OpenTelemetry traces printed to the console.

view raw JSON →