Skip to main content
This example demonstrates how to instrument OpenAI’s chat completions API with OpenInference tracing.

Prerequisites

  • Python 3.9+
  • OpenAI API key
  • Phoenix or another OpenTelemetry collector running

Installation

1

Install dependencies

2

Set environment variables

Complete Example

Key Features

Automatic Instrumentation

The OpenAIInstrumentor automatically traces all OpenAI API calls without requiring code changes to your OpenAI usage.

Context Attributes

Use using_attributes() context manager to add:
  • Session tracking: session_id and user_id
  • Metadata: Custom key-value pairs for filtering and analysis
  • Tags: Labels for categorization
  • Prompt templates: Track template versions and variables

Multiple Exporters

This example uses both:
  • OTLPSpanExporter: Send traces to Phoenix or any OTLP-compatible backend
  • ConsoleSpanExporter: Print traces to console for debugging

Next Steps