Pular para o conteúdo principal

Exportar rastreamentos do Langfuse para o Databricks MLflow

Configure o Langfuse para enviar spans de rastreamento baseados em OpenTelemetry para o endpoint OTLP Databricks MLflow , para que os rastreamentos sejam armazenados em tabelas Unity Catalog juntamente com seus outros rastreamentos MLflow .

Consolidar rastros no Databricks oferece os seguintes benefícios:

  • Consulte e compare chamadas instrumentadas com Langfuse juntamente com rastreamentos de outras estruturas em um único local.
  • Utilize o Databricks SQL para analisar dados de rastreamento em grande escala.
  • Aplique as regras de governança do Unity Catalog, como controles de acesso e linhagem, a todos os seus rastreamentos.

Requisitos

o passo 1: Instalar pacote

Instale o pacote necessário no seu Notebook Databricks :

Python
%pip install "langfuse>=3.14.5" "mlflow[databricks]>=3.10.0" opentelemetry-api opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
%restart_python

o passo 2: Desativar a coleta de rastreamento do Langfuse

Langfuse requer as variáveis de ambiente LANGFUSE_HOST, LANGFUSE_PUBLIC_KEY e LANGFUSE_SECRET_KEY para inicializar seu SDK. Defina essas variáveis com valores fictícios para impedir que os rastreamentos sejam enviados para um servidor Langfuse. Somente o exportador OTEL, configurado em Adicionar o exportador OTLP, receberá os spans.

Python
import os

os.environ["LANGFUSE_HOST"] = "localhost"
os.environ["LANGFUSE_PUBLIC_KEY"] = ""
os.environ["LANGFUSE_SECRET_KEY"] = ""
nota

Esta é a abordagem mais simples para impedir que o Langfuse colete rastros em seus próprios servidores. Alternativamente, você pode definir LANGFUSE_TRACING_ENABLED=False para desativar a coleta de rastreamento integrada do Langfuse.

o passo 3: Configurar a conexão Databricks

Recupere o URL do host workspace e os tokens API . Em um Notebook Databricks , você pode obter essas informações no contexto do Notebook:

Python
# If running outside a Databricks notebook, set DATABRICKS_HOST and DATABRICKS_TOKEN environment variables manually.
context = dbutils.notebook.entry_point.getDbutils().notebook().getContext()
DATABRICKS_HOST = context.apiUrl().get().rstrip("/")
DATABRICKS_TOKEN = context.apiToken().get()

a etapa 4: Vincular um experimento ao Unity Catalog

Defina seu catálogo e esquema do Unity Catalog e, em seguida, vincule-os a um experimento do MLflow usando set_experiment_trace_location. Isso indica ao Databricks onde armazenar os rastreamentos recebidos.

Python
import mlflow
from mlflow.entities import UCSchemaLocation
from mlflow.tracing.enablement import set_experiment_trace_location

CATALOG_NAME = "<UC_CATALOG_NAME>"
SCHEMA_NAME = "<UC_SCHEMA_NAME>"
EXPERIMENT_ID = "<EXPERIMENT_ID>"

trace_location = set_experiment_trace_location(
location=UCSchemaLocation(catalog_name=CATALOG_NAME, schema_name=SCHEMA_NAME),
experiment_id=EXPERIMENT_ID,
)

o passo 5: Adicionar o exportador OTLP Databricks

Obtenha o TracerProvider que o Langfuse usa e, em seguida, anexe um BatchSpanProcessor com um OTLPSpanExporter que aponta para o endpoint OTLP do Databricks.

Python
from langfuse import get_client
from opentelemetry import trace as otel_trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace.export import BatchSpanProcessor

# Initialize the Langfuse client. Langfuse registers its own TracerProvider as the global OpenTelemetry TracerProvider.
langfuse = get_client()

# Retrieve the global TracerProvider.
# Use this to attach an additional span processor that forwards Langfuse spans to Databricks.
provider = otel_trace.get_tracer_provider()

# Configure the OTLP exporter to send spans to the Databricks MLflow endpoint.
# The X-Databricks-UC-Table-Name header routes incoming spans to the Unity Catalog table defined by the trace location.
databricks_exporter = OTLPSpanExporter(
endpoint=f"{DATABRICKS_HOST}/api/2.0/otel/v1/traces",
headers={
"content-type": "application/x-protobuf",
"Authorization": f"Bearer {DATABRICKS_TOKEN}",
"X-Databricks-UC-Table-Name": trace_location.full_otel_spans_table_name,
},
)

# Attach the Databricks exporter to Langfuse's provider. Because the Langfuse
# env vars are set to dummy values, this processor is the only active exporter,
# so all spans are sent exclusively to Databricks.
provider.add_span_processor(BatchSpanProcessor(databricks_exporter))

o passo 6: execução de uma função rastreada

Use o decorador @observe() do Langfuse para instrumentar suas funções. O decorador cria spans OTEL que o exportador envia para o Databricks.

Python
from langfuse import observe

@observe()
def my_llm_call(prompt: str) -> str:
# Replace with your LLM logic (OpenAI, Anthropic, etc.)
return f"Response to: {prompt}"

@observe()
def my_pipeline(user_input: str) -> str:
result = my_llm_call(user_input)
return result

my_pipeline("Hello, world!")

o passo 7: visualizar rastros

Abra o experimento MLflow em seu workspace Databricks e clique na tab Rastreamentos . O rastreamento da chamada my_pipeline deve aparecer.

Próximos passos