跳到主内容

🔁 MLflow - 开源 LLM 可观测性和评估

什么是 MLflow?

MLflow 是一个端到端的开源 MLOps 平台,用于实验追踪模型管理评估可观测性(追踪)部署。MLflow 使团队能够高效地协作开发和完善 LLM 应用程序。

MLflow 与 LiteLLM 的集成支持与 OpenTelemetry 兼容的高级可观测性。

入门

安装 MLflow

pip install mlflow

启用 LiteLLM 的 MLflow 自动追踪功能

import mlflow

mlflow.litellm.autolog()

# Alternative, you can set the callback manually in LiteLLM
# litellm.callbacks = ["mlflow"]

由于 MLflow 是开源免费的,记录追踪数据无需注册或 API 密钥!

import litellm
import os

# Set your LLM provider's API key
os.environ["OPENAI_API_KEY"] = ""

# Call LiteLLM as usual
response = litellm.completion(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "Hi 👋 - i'm openai"}
]
)

打开 MLflow UI,然后转到“Traces”选项卡查看记录的追踪数据

mlflow ui

追踪工具调用

MLflow 与 LiteLLM 的集成除了支持追踪消息外,还支持追踪工具调用。

import mlflow

# Enable MLflow auto-tracing for LiteLLM
mlflow.litellm.autolog()

# Define the tool function.
def get_weather(location: str) -> str:
if location == "Tokyo":
return "sunny"
elif location == "Paris":
return "rainy"
return "unknown"

# Define function spec
get_weather_tool = {
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current weather in a given location",
"parameters": {
"properties": {
"location": {
"description": "The city and state, e.g., San Francisco, CA",
"type": "string",
},
},
"required": ["location"],
"type": "object",
},
},
}

# Call LiteLLM as usual
response = litellm.completion(
model="gpt-4o-mini",
messages=[
{"role": "user", "content": "What's the weather like in Paris today?"}
],
tools=[get_weather_tool]
)

评估

MLflow LiteLLM 集成允许您对 LLM 进行定性评估,以评估和/或监控您的生成式 AI 应用程序。

请访问评估 LLM 教程,获取关于如何使用 LiteLLM 和 MLflow 运行评估套件的完整指南。

导出追踪数据到 OpenTelemetry 收集器

MLflow 追踪数据与 OpenTelemetry 兼容。您可以通过在环境变量中设置端点 URL,将追踪数据导出到任何 OpenTelemetry 收集器(例如 Jaeger、Zipkin、Datadog、New Relic)。

# Set the endpoint of the OpenTelemetry Collector
os.environ["OTEL_EXPORTER_OTLP_TRACES_ENDPOINT"] = "http://localhost:4317/v1/traces"
# Optionally, set the service name to group traces
os.environ["OTEL_SERVICE_NAME"] = "<your-service-name>"

请参阅MLflow 文档了解更多详情。

将 LiteLLM 追踪数据与您的应用程序追踪数据相结合

LiteLLM 通常是大型 LLM 应用程序的一部分,例如代理模型。MLflow Tracing 允许您对自定义 Python 代码进行插装,然后可以将其与 LiteLLM 追踪数据相结合。

import litellm
import mlflow
from mlflow.entities import SpanType

# Enable MLflow auto-tracing for LiteLLM
mlflow.litellm.autolog()


class CustomAgent:
# Use @mlflow.trace to instrument Python functions.
@mlflow.trace(span_type=SpanType.AGENT)
def run(self, query: str):
# do something

while i < self.max_turns:
response = litellm.completion(
model="gpt-4o-mini",
messages=messages,
)

action = self.get_action(response)
...

@mlflow.trace
def get_action(llm_response):
...

这种方法生成一个统一的追踪数据,将您的自定义 Python 代码与 LiteLLM 调用相结合。

支持