MLflow for ML lifecycle management - experiment tracking, LLM/GenAI tracing, model registry, and deployment with GenAI and MCP support
Expert guidance for ML lifecycle management with MLflow, including GenAI/LLM tracking and MCP integration.
MLflow is an open-source platform for managing the ML lifecycle with four main components:
import mlflow
# Set tracking URI
mlflow.set_tracking_uri("http://localhost:5000")
# Set experiment
mlflow.set_experiment("my-experiment")
MLflow provides automatic logging for major frameworks:
import mlflow
# Scikit-learn
mlflow.sklearn.autolog()
# PyTorch
mlflow.pytorch.autolog()
# TensorFlow/Keras
mlflow.tensorflow.autolog()
import mlflow
# OpenAI
mlflow.openai.autolog()
# Anthropic
mlflow.anthropic.autolog()
# LangChain
mlflow.langchain.autolog()
What gets logged automatically:
import mlflow
with mlflow.start_run():
# Log parameters
mlflow.log_param("learning_rate", 0.01)
mlflow.log_params({"batch_size": 32, "epochs": 100})
# Log metrics
mlflow.log_metric("train_loss", 0.5)
# Log metrics with steps
for epoch in range(num_epochs):
train_loss = train_model()
mlflow.log_metric("train_loss", train_loss, step=epoch)
# Log model
mlflow.sklearn.log_model(model, name="model")
import mlflow
@mlflow.trace
def my_llm_app(question: str) -> str:
"""Traced LLM application"""
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": question}]
)
return response.choices[0].message.content
# Trace is automatically logged
result = my_llm_app("What is MLflow?")
# Access trace
trace_id = mlflow.get_last_active_trace_id()
trace = mlflow.get_trace(trace_id=trace_id)
# Add production context to traces
mlflow.update_current_trace(
tags={
"mlflow.trace.session": session_id,
"mlflow.trace.user": user_id,
"environment": "production"
}
)
import mlflow
from mlflow import MlflowClient
client = MlflowClient()
# Register during training
with mlflow.start_run():
mlflow.sklearn.log_model(
model,
name="model",
registered_model_name="MyModel"
)
# Set alias for deployment
client.set_registered_model_alias(
name="MyModel",
alias="champion",
version=1
)
# Load model by alias
model = mlflow.pyfunc.load_model("models:/MyModel@champion")
# Load specific version
model = mlflow.pyfunc.load_model("models:/MyModel/2")
# Load by stage
model = mlflow.pyfunc.load_model("models:/MyModel/Production")
# Transition model stage
client.transition_model_version_stage(
name="MyModel",
version=2,
stage="Production"
)
MLflow has MCP support for trace operations:
# Install as UV tool (recommended)
uv tool install "mlflow[genai,mcp]>=2.19.0"
# Or add to project
uv add "mlflow[genai,mcp]>=2.19.0"
# Run directly (after uv tool install)
mlflow mcp run
# With custom tracking URI
MLFLOW_TRACKING_URI=sqlite:///mlruns.db mlflow mcp run
.mcp.json (project configuration):
{
"mcpServers": {
"mlflow": {
"command": "mlflow",
"args": ["mcp", "run"],
"env": {
"MLFLOW_TRACKING_URI": "sqlite:///mlruns.db"
}
}
}
}
| Variable | Required | Description |
|----------|----------|-------------|
| MLFLOW_TRACKING_URI | Yes | MLflow tracking server URL or sqlite path |
| MLFLOW_EXPERIMENT_ID | No | Default experiment ID |
| DATABRICKS_HOST | For Databricks | Workspace URL |
| DATABRICKS_TOKEN | For Databricks | Personal access token |
The MLflow MCP server exposes these tools:
| Tool | Purpose |
|------|---------|
| search_traces | Search traces with filters (experiment_id, tags, timestamps) |
| get_trace | Get detailed trace info including spans, inputs, outputs |
| log_feedback | Log feedback scores (accuracy, quality, custom) |
| log_expectation | Log expected values for trace evaluation |
| evaluate_traces | Run automated evaluation with scorers |
| list_scorers | List available evaluation scorers |
| register_llm_judge | Create custom LLM-based scorer |
| set_trace_tag / delete_trace_tag | Manage trace metadata |
| delete_traces | Clean up traces by criteria |
Workflow Example:
1. search_traces → Find traces to evaluate
2. evaluate_traces → Run built-in scorers (Correctness, Safety, etc.)
3. log_feedback → Add human feedback
4. get_trace → Inspect detailed results
Build interactive experiment dashboards:
import marimo as mo
import mlflow
# Experiment selector
experiments = mlflow.search_experiments()
exp_select = mo.ui.dropdown(
options={e.name: e.experiment_id for e in experiments},
label="Select Experiment"
)
# Display runs with filtering
runs_df = mlflow.search_runs(experiment_ids=[exp_select.value])
mo.ui.table(runs_df, selection="single", label="Experiment Runs")
Track physics-informed neural network training:
import mlflow
from pina import Trainer
from pina.callbacks import MetricTracker
mlflow.set_experiment("pina-experiments")
with mlflow.start_run():
mlflow.log_params({"layers": [64, 64], "activation": "Tanh"})
trainer = Trainer(solver, max_epochs=1000, callbacks=[MetricTracker()])
trainer.train()
# Log PINA metrics
for key, value in trainer.callback_metrics.items():
mlflow.log_metric(key, value)
mlflow.pytorch.log_model(solver.model, "pinn")
Query up-to-date MLflow documentation directly:
# context7 Library IDs (no resolve needed):
# - /mlflow/mlflow (official docs, 9559 snippets)
# - /websites/mlflow (website docs, 36205 snippets)
# Example: query-docs("/mlflow/mlflow", "mlflow.trace decorator usage")
✅ Use MLflow when:
❌ Don't use MLflow when:
For detailed guides, see the references folder:
Ready-to-use templates in the examples folder:
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer