MLflow
MLflow 是一個多功能、開放原始碼平台,用於管理機器學習和生成式 AI 生命週期中的工作流程和工件。它內建與許多流行的 AI 和 ML 函式庫的整合,但可以與任何函式庫、演算法或部署工具一起使用。
MLflow 的 LangChain 整合 提供以下功能
- 追蹤:透過一行程式碼 (
mlflow.langchain.autolog()
) 可視化資料流經 LangChain 組件的路徑 - 實驗追蹤:記錄 LangChain 執行中的工件、程式碼和指標
- 模型管理:對 LangChain 應用程式進行版本控制和部署,並追蹤依賴關係
- 評估:衡量 LangChain 應用程式的效能
注意:MLflow 追蹤功能在 MLflow 2.14.0 及更高版本中可用。
本簡短指南重點介紹 MLflow 用於 LangChain 和 LangGraph 應用程式的追蹤功能。您將了解如何使用一行程式碼啟用追蹤,並檢視應用程式的執行流程。如需 MLflow 其他功能以及探索其他教學課程的相關資訊,請參閱 LangChain 的 MLflow 文件。如果您是 MLflow 的新手,請查看 MLflow 入門 指南。
設定
若要開始使用 LangChain 的 MLflow 追蹤功能,請安裝 MLflow Python 套件。我們也將使用 langchain-openai
套件。
%pip install mlflow langchain-openai langgraph -qU
接下來,設定 MLflow 追蹤 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 追蹤
MLflow 的追蹤功能可協助您視覺化 LangChain 應用程式的執行流程。以下說明如何啟用它。
import mlflow
# Optional: Set an experiment to organize your traces
mlflow.set_experiment("LangChain MLflow Integration")
# Enable tracing
mlflow.langchain.autolog()
範例:追蹤 LangChain 應用程式
以下是一個完整的範例,展示 LangChain 的 MLflow 追蹤
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 參考:tool | create_react_agent
若要檢視追蹤,請在您的終端機中執行 mlflow ui
,並導覽至 MLflow UI 中的「Traces」標籤頁。
資源
如需有關搭配 LangChain 使用 MLflow 的更多資訊,請造訪