Skip to main content
Open In ColabOpen on GitHub

MLflow

MLflow 是一个多功能、开源的平台,用于管理机器学习和生成式 AI 生命周期中的工作流和构件(artifacts)。它内置了与许多流行的 AI 和 ML 库的集成,但也可与任何库、算法或部署工具配合使用。

MLflow 的 LangChain 集成提供了以下功能:

注意:MLflow 追踪功能在 MLflow 2.14.0 及更高版本中可用。

本简短指南将重点介绍 MLflow 对 LangChain 和 LangGraph 应用程序的追踪功能。您将了解如何通过一行代码启用追踪,并查看应用程序的执行流程。有关 MLflow 的其他功能以及探索更多教程的信息,请参阅 MLflow LangChain 文档。如果您是 MLflow 新手,请查看 MLflow 入门指南

设置

要开始使用 LangChain 的 MLflow 追踪,请安装 MLflow Python 包。我们还将使用 langchain-openai 包。

%pip install mlflow langchain-openai langgraph -qU

接下来,设置 MLflow tracking URI 和 OpenAI API 密钥。

import os

# Set MLflow tracking URI if you have MLflow Tracking Server running
os.environ["MLFLOW_TRACKING_URI"] = ""
os.environ["OPENAI_API_KEY"] = ""

MLflow Tracing

MLflow 的 tracing 功能可以帮助您可视化 LangChain 应用程序的执行流程。以下是启用它的方法。

import mlflow

# Optional: Set an experiment to organize your traces
mlflow.set_experiment("LangChain MLflow Integration")

# Enable tracing
mlflow.langchain.autolog()

示例:追踪 LangChain 应用

这是一个展示 MLflow 追踪与 LangChain 集成的完整示例:

import mlflow
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

# Enable MLflow tracing
mlflow.langchain.autolog()

# Create a simple chain
llm = ChatOpenAI(model_name="gpt-4o")

prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful assistant that translates {input_language} to {output_language}.",
),
("human", "{input}"),
]
)

chain = prompt | llm | StrOutputParser()

# Run the chain
result = chain.invoke(
{
"input_language": "English",
"output_language": "German",
"input": "I love programming.",
}
)

要在终端中运行 mlflow ui 来查看跟踪信息,请在 MLflow UI 中导航到 Traces 选项卡。

示例:跟踪 LangGraph 应用

MLflow 还支持跟踪 LangGraph 应用:

import mlflow
from langchain_core.tools import tool
from langgraph.prebuilt import create_react_agent

# Enable MLflow tracing
mlflow.langchain.autolog()


# Define a tool
@tool
def count_words(text: str) -> str:
"""Counts the number of words in a text."""
word_count = len(text.split())
return f"This text contains {word_count} words."


# Create a LangGraph agent
llm = ChatOpenAI(model="gpt-4o")
tools = [count_words]
graph = create_react_agent(llm, tools)

# Run the agent
result = graph.invoke(
{"messages": [{"role": "user", "content": "Write me a 71-word story about a cat."}]}
)
API Reference:tool | create_react_agent

要在本地找到日志文件,请在您的终端中运行 mlflow ui 命令,然后在 MLflow UI 的 Traces 选项卡中找到相应日志。

资源

有关将 MLflow 与 LangChain n 使用的信息,请访问: