OpenTelemetry OpenAI Agents Instrumentation

0.58.0 · active · verified Sat Apr 11

This library provides official OpenTelemetry instrumentation for the `openai-agents` SDK, converting the rich trace data emitted by the Agents runtime into the GenAI semantic conventions, enriching spans with request/response payload metadata, and recording duration/token usage metrics. It is currently at version `0.58.0` and maintains an active development pace with frequent updates, often related to compliance with evolving OpenTelemetry Generative AI semantic conventions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up the OpenTelemetry Python SDK with an OTLP exporter and then enable instrumentation for OpenAI Agents. After running this code, traces generated by the agent's operations will be sent to the configured OpenTelemetry collector. Make sure an OpenTelemetry collector is running and accessible.

import os
from agents import Agent, Runner, function_tool
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.openai_agents import OpenAIAgentsInstrumentor
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

def configure_otel() -> None:
    # Configure an OpenTelemetry TracerProvider
    provider = TracerProvider()
    processor = BatchSpanProcessor(OTLPSpanExporter())
    provider.add_span_processor(processor)
    trace.set_tracer_provider(provider)

    # Instrument OpenAI Agents
    OpenAIAgentsInstrumentor().instrument(tracer_provider=provider)

@function_tool
def get_weather(city: str) -> str:
    """Provides the weather for a given city."""
    return f"The forecast for {city} is sunny with pleasant temperatures."

if __name__ == "__main__":
    # Ensure OTLP collector is running, e.g., with Docker:
    # docker run -d -p 4317:4317 -p 4318:4318 otel/opentelemetry-collector-contrib

    # Configure OpenTelemetry
    configure_otel()

    # Example OpenAI Agent usage
    assistant = Agent(
        name="Travel Concierge",
        instructions="You are a concise travel concierge.",
        tools=[get_weather],
    )

    print("Running agent...")
    # Provide dummy API key if required by 'openai-agents', though it might be configured via env vars.
    # For real use, ensure OpenAI API key is set via environment variable, e.g., OPENAI_API_KEY
    os.environ['OPENAI_API_KEY'] = os.environ.get('OPENAI_API_KEY', 'sk-dummy-key-for-example')

    result = Runner.run_sync(assistant, "I'm visiting Barcelona this weekend. How should I pack?")
    print(f"Agent final output: {result.final_output}")
    print("Traces should now be visible in your configured OpenTelemetry backend.")

view raw JSON →