OpenTelemetry Instrumentation for Hugging Face Transformers

0.58.0 · active · verified Fri Apr 10

The `opentelemetry-instrumentation-transformers` library provides OpenTelemetry instrumentation for the Hugging Face Transformers library. It automatically captures traces for operations performed using Transformers models, helping to monitor and observe AI/ML application performance and behavior. The current version is 0.58.0, and it follows a rapid release cadence, often aligning with updates to OpenTelemetry's Generative AI semantic conventions.

Warnings

Install

Imports

Quickstart

This example sets up a basic OpenTelemetry SDK with a console exporter, then instruments the Hugging Face Transformers library. It then runs a sentiment analysis pipeline, generating traces that 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.transformers import TransformersInstrumentor
from transformers import pipeline

# Configure OpenTelemetry SDK
# In production, use OTLPExporter to send traces to a collector.
resource = Resource.create({"service.name": "transformers-app"})
provider = TracerProvider(resource=resource)
processor = SimpleSpanProcessor(ConsoleSpanExporter())
provider.add_span_processor(processor)
trace.set_tracer_provider(provider)

# Instrument the transformers library
TransformersInstrumentor().instrument()

# Use a transformers pipeline
print("Running transformers pipeline...")
pipe = pipeline("sentiment-analysis")
result = pipe("I love OpenTelemetry!")
print("Pipeline result:", result)

# Ensure traces are flushed before exit
provider.shutdown()

view raw JSON →