Integrazioni di tracciamento MLflow

MLflow Tracing è integrato con un'ampia gamma dei più diffusi framework e librerie di intelligenza artificiale generativa, offrendo un'esperienza di tracciamento automatico con una sola riga per tutti. Questo ti consente di ottenere un'osservabilità immediata sui tuoi agenti con una configurazione minima.

Questo ampio supporto consente di ottenere l'osservabilità senza modifiche significative del codice, sfruttando gli strumenti già usati. Per i componenti personalizzati o le librerie non supportate, MLflow offre anche potenti API di traccia manuale.

La traccia automatica acquisisce la logica e i passaggi intermedi dell'applicazione, ad esempio chiamate LLM, utilizzo degli strumenti e interazioni con agenti, in base all'implementazione della libreria o dell'SDK specifico.

Annotazioni

Nei cluster di calcolo serverless, l'autologging per i framework di tracciamento genAI non è abilitato automaticamente. È necessario abilitare esplicitamente l'autologging chiamando la funzione appropriata mlflow.<library>.autolog() per le specifiche integrazioni che si desidera tracciare.

Annotazioni

Gli esempi di avvio rapido in questa pagina richiedono MLflow 3.14 o successivo perché memorizzano le tracce nel Catalogo Unity.

Principali integrazioni a colpo d'occhio

Ecco alcuni esempi di avvio rapido per alcune delle integrazioni più usate. Fare clic su una scheda per visualizzare un esempio di utilizzo di base. Per i prerequisiti dettagliati e scenari più avanzati per ognuno di essi, visitare le pagine di integrazione dedicate (collegate dalle schede o dall'elenco riportato di seguito).

OpenAI

import mlflow
from mlflow.entities.trace_location import UnityCatalog
import openai

# If running this code outside of a Databricks notebook (e.g., locally),
# uncomment and set the following environment variables to point to your Databricks workspace:
# import os
# os.environ["DATABRICKS_HOST"] = "https://your-workspace.cloud.databricks.com"
# os.environ["DATABRICKS_TOKEN"] = "your-personal-access-token"

# Enable auto-tracing for OpenAI
mlflow.openai.autolog()

# Set up MLflow tracking
mlflow.set_tracking_uri("databricks")
mlflow.set_experiment(
    experiment_name="/Shared/openai-tracing-demo",
    trace_location=UnityCatalog(
        catalog_name="<UC_CATALOG_NAME>",
        schema_name="<UC_SCHEMA_NAME>",
        table_prefix="<UC_TABLE_PREFIX>",
    ),
)

openai_client = openai.OpenAI()

messages = [
    {
        "role": "user",
        "content": "What is the capital of France?",
    }
]

response = openai_client.chat.completions.create(
    model="gpt-4o-mini",
    messages=messages,
    temperature=0.1,
    max_tokens=100,
)
# View trace in MLflow UI

Guida completa all'integrazione di OpenAI

LangChain

import mlflow
from mlflow.entities.trace_location import UnityCatalog
from langchain.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import ChatOpenAI

# If running this code outside of a Databricks notebook (e.g., locally),
# uncomment and set the following environment variables to point to your Databricks workspace:
# import os
# os.environ["DATABRICKS_HOST"] = "https://your-workspace.cloud.databricks.com"
# os.environ["DATABRICKS_TOKEN"] = "your-personal-access-token"

mlflow.langchain.autolog()

mlflow.set_tracking_uri("databricks")
mlflow.set_experiment(
    experiment_name="/Shared/langchain-tracing-demo",
    trace_location=UnityCatalog(
        catalog_name="<UC_CATALOG_NAME>",
        schema_name="<UC_SCHEMA_NAME>",
        table_prefix="<UC_TABLE_PREFIX>",
    ),
)

llm = ChatOpenAI(model="gpt-4o-mini", temperature=0.7, max_tokens=1000)
prompt = PromptTemplate.from_template("Tell me a joke about {topic}.")
chain = prompt | llm | StrOutputParser()

chain.invoke({"topic": "artificial intelligence"})
# View trace in MLflow UI

Guida completa all'integrazione di LangChain

LangGraph

import mlflow
from mlflow.entities.trace_location import UnityCatalog
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent

# If running this code outside of a Databricks notebook (e.g., locally),
# uncomment and set the following environment variables to point to your Databricks workspace:
# import os
# os.environ["DATABRICKS_HOST"] = "https://your-workspace.cloud.databricks.com"
# os.environ["DATABRICKS_TOKEN"] = "your-personal-access-token"

mlflow.langchain.autolog() # LangGraph uses LangChain's autolog

mlflow.set_tracking_uri("databricks")
mlflow.set_experiment(
    experiment_name="/Shared/langgraph-tracing-demo",
    trace_location=UnityCatalog(
        catalog_name="<UC_CATALOG_NAME>",
        schema_name="<UC_SCHEMA_NAME>",
        table_prefix="<UC_TABLE_PREFIX>",
    ),
)

@tool
def get_weather(city: str):
    """Use this to get weather information."""
    return f"It might be cloudy in {city}"

llm = ChatOpenAI(model="gpt-4o-mini")
graph = create_react_agent(llm, [get_weather])
result = graph.invoke({"messages": [("user", "what is the weather in sf?")]})
# View trace in MLflow UI

Guida all'integrazione di Full LangGraph

Antropico

import mlflow
from mlflow.entities.trace_location import UnityCatalog
import anthropic
import os

# If running this code outside of a Databricks notebook (e.g., locally),
# uncomment and set the following environment variables to point to your Databricks workspace:
# os.environ["DATABRICKS_HOST"] = "https://your-workspace.cloud.databricks.com"
# os.environ["DATABRICKS_TOKEN"] = "your-personal-access-token"

mlflow.anthropic.autolog()

mlflow.set_tracking_uri("databricks")
mlflow.set_experiment(
    experiment_name="/Shared/anthropic-tracing-demo",
    trace_location=UnityCatalog(
        catalog_name="<UC_CATALOG_NAME>",
        schema_name="<UC_SCHEMA_NAME>",
        table_prefix="<UC_TABLE_PREFIX>",
    ),
)

client = anthropic.Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
message = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    messages=[{"role": "user", "content": "Hello, Claude"}],
)
# View trace in MLflow UI

Guida completa all'integrazione antropica

DSPy

import mlflow
from mlflow.entities.trace_location import UnityCatalog
import dspy

# If running this code outside of a Databricks notebook (e.g., locally),
# uncomment and set the following environment variables to point to your Databricks workspace:
# import os
# os.environ["DATABRICKS_HOST"] = "https://your-workspace.cloud.databricks.com"
# os.environ["DATABRICKS_TOKEN"] = "your-personal-access-token"

mlflow.dspy.autolog()

mlflow.set_tracking_uri("databricks")
mlflow.set_experiment(
    experiment_name="/Shared/dspy-tracing-demo",
    trace_location=UnityCatalog(
        catalog_name="<UC_CATALOG_NAME>",
        schema_name="<UC_SCHEMA_NAME>",
        table_prefix="<UC_TABLE_PREFIX>",
    ),
)

lm = dspy.LM("openai/gpt-4o-mini") # Assumes OPENAI_API_KEY is set
dspy.configure(lm=lm)

class SimpleSignature(dspy.Signature):
    input_text: str = dspy.InputField()
    output_text: str = dspy.OutputField()

program = dspy.Predict(SimpleSignature)
result = program(input_text="Summarize MLflow Tracing.")
# View trace in MLflow UI

Guida completa all'integrazione di DSPy

Databricks

import mlflow
from mlflow.entities.trace_location import UnityCatalog
import os
from openai import OpenAI # Databricks FMAPI uses OpenAI client

# If running this code outside of a Databricks notebook (e.g., locally),
# uncomment and set the following environment variables to point to your Databricks workspace:
# os.environ["DATABRICKS_HOST"] = "https://your-workspace.cloud.databricks.com"
# os.environ["DATABRICKS_TOKEN"] = "your-personal-access-token"

mlflow.openai.autolog() # Traces Databricks FMAPI using OpenAI client

mlflow.set_tracking_uri("databricks")
mlflow.set_experiment(
    experiment_name="/Shared/databricks-fmapi-tracing",
    trace_location=UnityCatalog(
        catalog_name="<UC_CATALOG_NAME>",
        schema_name="<UC_SCHEMA_NAME>",
        table_prefix="<UC_TABLE_PREFIX>",
    ),
)

client = OpenAI(
    api_key=os.environ.get("DATABRICKS_TOKEN"),
    base_url=f"{os.environ.get('DATABRICKS_HOST')}/serving-endpoints"
)
response = client.chat.completions.create(
    model="databricks-llama-4-maverick",
    messages=[{"role": "user", "content": "Key features of MLflow?"}],
)
# View trace in MLflow UI

Guida completa all'integrazione di Databricks

Roccia madre

import mlflow
from mlflow.entities.trace_location import UnityCatalog
import boto3

# If running this code outside of a Databricks notebook (e.g., locally),
# uncomment and set the following environment variables to point to your Databricks workspace:
# import os
# os.environ["DATABRICKS_HOST"] = "https://your-workspace.cloud.databricks.com"
# os.environ["DATABRICKS_TOKEN"] = "your-personal-access-token"

mlflow.bedrock.autolog()

mlflow.set_tracking_uri("databricks")
mlflow.set_experiment(
    experiment_name="/Shared/bedrock-tracing-demo",
    trace_location=UnityCatalog(
        catalog_name="<UC_CATALOG_NAME>",
        schema_name="<UC_SCHEMA_NAME>",
        table_prefix="<UC_TABLE_PREFIX>",
    ),
)

bedrock = boto3.client(
    service_name="bedrock-runtime",
    region_name="us-east-1" # Replace with your region
)
response = bedrock.converse(
    modelId="anthropic.claude-3-5-sonnet-20241022-v2:0",
    messages=[{"role": "user", "content": "Hello World in one line."}]
)
# View trace in MLflow UI

Guida completa all'integrazione di Bedrock

AutoGen

import mlflow
from mlflow.entities.trace_location import UnityCatalog
from autogen import ConversableAgent
import os

# If running this code outside of a Databricks notebook (e.g., locally),
# uncomment and set the following environment variables to point to your Databricks workspace:
# os.environ["DATABRICKS_HOST"] = "https://your-workspace.cloud.databricks.com"
# os.environ["DATABRICKS_TOKEN"] = "your-personal-access-token"

mlflow.autogen.autolog()

mlflow.set_tracking_uri("databricks")
mlflow.set_experiment(
    experiment_name="/Shared/autogen-tracing-demo",
    trace_location=UnityCatalog(
        catalog_name="<UC_CATALOG_NAME>",
        schema_name="<UC_SCHEMA_NAME>",
        table_prefix="<UC_TABLE_PREFIX>",
    ),
)

config_list = [{"model": "gpt-4o-mini", "api_key": os.environ.get("OPENAI_API_KEY")}]
assistant = ConversableAgent("assistant", llm_config={"config_list": config_list})
user_proxy = ConversableAgent("user_proxy", human_input_mode="NEVER", code_execution_config=False)

user_proxy.initiate_chat(assistant, message="What is 2+2?")
# View trace in MLflow UI

Guida completa all'integrazione di AutoGen

Sfoglia tutte le integrazioni

Fornitori di modelli

Anthropic Antropico
AWS Bedrock AWS Bedrock
BytePlus Fornitore di modelli
Cohere Fornitore di modelli
API del modello Databricks Foundation Modelli di Databricks Foundation
DeepSeek DeepSeek
FireworksAI Fornitore di modelli
Google Gemini Google Gemini
Groq Groq
Mistral Mistral
Intelligenza artificiale Moonshot Fornitore di modelli
Novita AI Fornitore di modelli
Ollama Ollama
OpenAI OpenAI
Qwen Fornitore di modelli
Insieme AI Fornitore di modelli
xAI / Grok Fornitore di modelli

Framework per agent e app

AG2 Framework agente
Agno Framework agente
Amazon Bedrock AgentCore Framework agente
AutoGen Framework multiagente
Claude Agent SDK Framework agente
CrewAI Framework agente
DSPy Framework di ottimizzazione
Google ADK Framework agente
Haystack Framework agente
Koog Framework agente
LangChain Framework agente
LangChain DeepAgent Framework agente
LangGraph Framework agente
LlamaIndex Framework dei dati
Agenti LiveKit Framework per agenti vocali
Mastra Framework per agenti TypeScript
Microsoft Agent Framework Framework agente
OpenAI Agent Framework agente
Pipecat Framework per gli agenti vocali
PydanticAI Framework agente
Quarkus LangChain4j Framework per agenti Java
Kernel semantico Framework multilingua
Smolagents Framework agente
Spring AI Framework Java
Strands Framework agente
Swarm Framework agente
TxtAI Framework di ricerca semantica
Vercel AI SDK Framework TypeScript
VoltAgent Framework per agenti TypeScript
Watsonx Orchestrate Piattaforma di orchestrazione

Agenti di programmazione & Agenti a esecuzione prolungata

Claude Code Agente di codifica
Codex CLI - Interfaccia della riga di comando Agente di codifica
Gemini CLI Agente di codifica
Agente Hermes Agente di codifica
Omnigent Agente di codifica
OpenCode Agente di codifica
OpenHands Agente di codifica
Codice Qwen Agente di codifica

Gateways

Databricks AI Gateway Gateway LLM
Helicone Gateway LLM
Kong AI Gateway Gateway LLM
LiteLLM Proxy Gateway LLM
MLflow AI Gateway Gateway LLM
OpenRouter Gateway LLM
Portkey Gateway LLM
Pydantic AI Gateway Gateway LLM
TrueFoundry Gateway LLM
Vercel AI Gateway Gateway LLM

Osservabilità e strumenti

Arize / Phoenix Piattaforma di osservabilità
Istruttore Libreria di output strutturata
Langfuse Piattaforma di osservabilità
LiteLLM Libreria di astrazione LLM
OpenTelemetry Standard di osservabilità

Piattaforme No-Code

Oca Agente di spazio di lavoro autonomo
Langflow Costruttore di flussi di lavoro visivi
n8n Piattaforma di automazione dei flussi di lavoro
Aprire WebUI Piattaforma di interfaccia chat

Protezione della gestione delle chiavi API

Per gli ambienti di produzione, Databricks consiglia di usare i segreti del gateway di intelligenza artificiale o di Databricks per gestire le chiavi API. Il gateway di intelligenza artificiale è il metodo preferito e offre funzionalità di governance aggiuntive.

Avvertimento

Non eseguire mai il commit delle chiavi API direttamente nel codice o nei notebook. Usare sempre i segreti del gateway di intelligenza artificiale o di Databricks per le credenziali sensibili.

Databricks consiglia AI Gateway per governare e monitorare l'accesso ai modelli di IA generativa.

Creare un endpoint del modello foundation configurato con il gateway di intelligenza artificiale:

  1. Nell'area di lavoro di Databricks, vai a Servizio>Crea un nuovo endpoint.
  2. Scegliere un tipo di endpoint e un provider.
  3. Configurare l'endpoint con la chiave API.
  4. Durante la configurazione dell'endpoint, abilitare il gateway di intelligenza artificiale e configurare la limitazione della frequenza, i fallback e le protezioni in base alle esigenze.
  5. È possibile ottenere il codice generato automaticamente per iniziare rapidamente a eseguire query sull'endpoint. Passare a Gestione> dell'endpoint >Usare>query. Assicurarsi di aggiungere il codice di traccia:
import mlflow
from mlflow.entities.trace_location import UnityCatalog
from openai import OpenAI
import os

# How to get your Databricks token: https://docs.databricks.com/en/dev-tools/auth/pat.html
# DATABRICKS_TOKEN = os.environ.get('DATABRICKS_TOKEN')
# Alternatively in a Databricks notebook you can use this:
DATABRICKS_TOKEN = dbutils.notebook.entry_point.getDbutils().notebook().getContext().apiToken().get()

# Enable auto-tracing for OpenAI
mlflow.openai.autolog()

# Set up MLflow tracking (if running outside Databricks)
# If running in a Databricks notebook, these are not needed.
mlflow.set_tracking_uri("databricks")
mlflow.set_experiment(
    experiment_name="/Shared/my-genai-app",
    trace_location=UnityCatalog(
        catalog_name="<UC_CATALOG_NAME>",
        schema_name="<UC_SCHEMA_NAME>",
        table_prefix="<UC_TABLE_PREFIX>",
    ),
)

client = OpenAI(
  api_key=DATABRICKS_TOKEN,
  base_url="<YOUR_HOST_URL>/serving-endpoints"
)

chat_completion = client.chat.completions.create(
  messages=[
  {
    "role": "system",
    "content": "You are an AI assistant"
  },
  {
    "role": "user",
    "content": "What is MLflow?"
  }
  ],
  model="<YOUR_ENDPOINT_NAME>",
  max_tokens=256
)

print(chat_completion.choices[0].message.content)

Segreti di Databricks

Usare i segreti di Databricks per gestire le chiavi API:

  1. Creare un ambito segreto e archiviare la chiave API:

    from databricks.sdk import WorkspaceClient
    
    # Set your secret scope and key names
    secret_scope_name = "llm-secrets"  # Choose an appropriate scope name
    secret_key_name = "api-key"        # Choose an appropriate key name
    
    # Create the secret scope and store your API key
    w = WorkspaceClient()
    w.secrets.create_scope(scope=secret_scope_name)
    w.secrets.put_secret(
        scope=secret_scope_name,
        key=secret_key_name,
        string_value="your-api-key-here"  # Replace with your actual API key
    )
    
  2. Recuperare e usare il segreto nel codice:

    import mlflow
    import openai
    import os
    
    # Configure your secret scope and key names
    secret_scope_name = "llm-secrets"
    secret_key_name = "api-key"
    
    # Retrieve the API key from Databricks secrets
    os.environ["OPENAI_API_KEY"] = dbutils.secrets.get(
        scope=secret_scope_name,
        key=secret_key_name
    )
    
    # Enable automatic tracing
    mlflow.openai.autolog()
    
    # Use OpenAI client with securely managed API key
    client = openai.OpenAI()
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": "Explain MLflow Tracing"}],
        max_tokens=100
    )
    

Abilitazione di più integrazioni di traccia automatica

Poiché gli agenti spesso combinano più librerie, MLflow Tracing permette di abilitare l'auto-tracciamento per diverse integrazioni simultaneamente, offrendo un'esperienza di tracciamento unificata.

Ad esempio, per abilitare sia LangChain che il tracciamento diretto di OpenAI:

import mlflow

# Enable MLflow Tracing for both LangChain and OpenAI
mlflow.langchain.autolog()
mlflow.openai.autolog()

# Your code using both LangChain and OpenAI directly...
# ... an example can be found on the Automatic Tracing page ...

MLflow genererà una singola traccia coesa che combina i passaggi delle chiamate LangChain e OpenAI LLM dirette, consentendo di esaminare il flusso completo. Altri esempi di combinazione di integrazioni sono disponibili nella pagina Traccia automatica .

Disabilitare la traccia automatica

La traccia automatica per qualsiasi libreria specifica può essere disabilitata chiamando mlflow.<library>.autolog(disable=True). Per disabilitare tutte le integrazioni di registrazione automatica contemporaneamente, usare mlflow.autolog(disable=True).

import mlflow

# Disable for a specific library
mlflow.openai.autolog(disable=True)

# Disable all autologging
mlflow.autolog(disable=True)