跳到主要内容

使用 OpenTelemetry 进行跟踪

由 CNCF 支持的 OpenTelemetry 项目提供厂商中立的可观测性 API 和 SDK,用于从您的应用程序收集遥测数据。MLflow Tracing 完全兼容 OpenTelemetry,避免了厂商锁定。

使用 MLflow Tracing SDK

MLflow Tracing SDK 构建在 OpenTelemetry SDK 之上。如果您想以最小的精力来追踪您的 AI 应用程序,请使用 MLflow Tracing SDK

python
import mlflow
from openai import OpenAI

mlflow.openai.autolog()

client = OpenAI()
response = client.responses.create(model="gpt-4o-mini", input="Hello, world!")

使用其他 OpenTelemetry 库

您可能希望追踪 MLflow Tracing SDK 不支持 的 LLM 或框架,或者追踪用 Python 和 TypeScript/JavaScript 以外的语言编写的应用程序。

MLflow Server 在 /v1/traces 处公开一个 OTLP 端点(OTLP),该端点接受来自任何 OpenTelemetry 仪器的追踪数据,允许您追踪用 Java、Go、Rust 等其他语言编写的应用程序。要将追踪数据导出到 MLflow,请将 OTEL_EXPORTER_OTLP_TRACES_ENDPOINT 设置为 MLflow 服务器端点,并将 x-mlflow-experiment-id 头设置为 MLflow 实验 ID。

bash
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://:5000/v1/traces
export OTEL_EXPORTER_OTLP_TRACES_HEADERS=x-mlflow-experiment-id=123

有关 MLflow OpenTelemetry 集成的更多详细信息,请参阅 将 OpenTelemetry 追踪收集到 MLflow

结合使用 OpenTelemetry SDK 和 MLflow Tracing SDK

由于 MLflow Tracing SDK 构建在 OpenTelemetry SDK 之上,您可以结合使用它们来获得两全其美的效果。要在单个应用程序中使用这两个 SDK,请将 MLFLOW_USE_DEFAULT_TRACER_PROVIDER 环境变量设置为 false

以下示例显示了如何将 MLflow 的 OpenAI 自动追踪与 OpenTelemetry 的原生 FastAPI 仪器相结合。

python
import os
import mlflow
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, Response
from openai import OpenAI
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor

# Use the OpenTelemetry tracer provider instead of MLflow's default tracer provider.
os.environ["MLFLOW_USE_DEFAULT_TRACER_PROVIDER"] = "false"


# Enable MLflow OpenAI auto-tracing at application startup.
@asynccontextmanager
async def lifespan(app: FastAPI):
mlflow.set_tracking_uri("https://:5000")
mlflow.set_experiment("FastAPI")
mlflow.openai.autolog()
yield


app = FastAPI(lifespan=lifespan)
# Enable FastAPI auto-instrumentation, which creates an OpenTelemetry span for each endpoint call.
FastAPIInstrumentor.instrument_app(app)


@app.post("/rag/v1/answer")
@mlflow.trace
async def answer_question(query: Request) -> Response:
return ...

从两个 SDK 生成的 Span 将合并到一个追踪中。

The MLflow UI showing the MLflow and OpenTelemetry combined spans