跳到主要内容

超越 Autolog:为新 LLM 提供商添加 MLflow 追踪

·阅读时间 17 分钟
Daniel Liden
Databricks 开发者布道师

在本文中,我们将演示如何通过为 Ollama Python SDK 的 chat 方法添加跟踪支持,从而为新的 LLM 提供商添加 MLflow Tracing。

MLflow Tracing 是 MLflow 中的一个可观测性工具,用于捕获 GenAI 应用程序和工作流的详细执行轨迹。除了捕获单个调用的输入、输出和元数据外,MLflow Tracing 还可以捕获中间步骤,如工具调用、推理步骤、检索步骤或其他自定义步骤。

MLflow 为许多流行的 LLM 提供商和编排框架提供了内置的 Tracing 支持。如果您正在使用这些提供商之一,只需一行代码即可启用跟踪:mlflow.<provider>.autolog()。虽然 MLflow 的自动记录功能涵盖了许多广泛使用的 LLM 提供商和编排框架,但有时您可能需要为不受支持的提供商添加跟踪,或者在自动记录提供的功能之外进行自定义跟踪。本文通过以下方式展示了 MLflow Tracing 的灵活性和可扩展性:

  • 为不受支持的提供商(Ollama Python SDK)添加基本的跟踪支持
  • 展示如何捕获简单的补全和更复杂的工具调用工作流
  • 阐明如何在对现有代码进行最少更改的情况下添加跟踪

我们将以 Ollama Python SDK 为例,这是一个用于 Ollama LLM 平台的开源 Python SDK。我们将逐步完成整个过程,展示如何在与提供商 SDK 保持清晰集成的情况下,使用 MLflow Tracing 捕获关键信息。请注意,MLflow *确实* 对 Ollama 有自动记录支持,但目前仅限于通过 OpenAI 客户端使用,而不是直接使用 Ollama Python SDK。

为新提供商添加 MLflow Tracing:通用原则

MLflow 文档有一份优秀的指南,介绍了如何为 MLflow Tracing 做贡献。虽然在本例中我们不会直接为 MLflow 本身做贡献,但我们将遵循相同的通用原则。

本文假设您对 MLflow Tracing 是什么以及其工作原理有基本的了解。如果您是初学者,或者需要复习一下,请查看Tracing 概念指南。

为新提供商添加跟踪涉及几个关键考虑因素:

  1. 了解提供商的关键功能:我们首先需要了解需要跟踪哪些 API 方法,才能获得我们想要的跟踪信息。对于 LLM 推理提供商,这通常涉及聊天补全、工具调用或嵌入生成等操作。在编排框架中,这可能涉及检索、推理、路由或各种自定义步骤。在我们的 Ollama 示例中,我们将重点关注聊天补全 API。这一步会因提供商的不同而有很大差异。

  2. 将操作映射到跨度 (span):MLflow Tracing 使用不同的*跨度类型*来表示不同类型的操作。您可以在这里找到内置跨度类型的描述。不同的跨度类型在 MLflow UI 中显示方式不同,并且可以启用特定功能。在跨度内部,我们还希望将提供商的输入和输出映射到 MLflow 期望的格式。MLflow 提供了用于记录聊天和工具输入输出的实用工具,这些内容随后会在 MLflow UI 中以格式化消息的形式显示。

    Chat Messages

    在为新提供商添加跟踪时,我们的主要任务是将提供商的 API 方法映射到具有适当跨度类型的 MLflow Tracing 跨度。

  3. 构建和保留关键数据:对于我们想要跟踪的每个操作,我们需要确定想要保留的关键信息,并确保它以有用的方式被捕获和显示。例如,我们可能想要捕获控制操作行为的输入和配置数据、解释结果的输出和元数据、导致操作提前终止的错误等。查看类似提供商的轨迹和跟踪实现可以为如何构建和保留这些数据提供一个很好的起点。

为 Ollama Python SDK 添加跟踪

现在我们对为新提供商添加跟踪的关键步骤有了高层次的理解,让我们来实际操作,为 Ollama Python SDK 添加跟踪。

步骤 1:安装并测试 Ollama Python SDK

首先,我们需要安装 Ollama Python SDK,并确定在添加跟踪支持时需要关注哪些方法。您可以使用 pip install ollama-python 来安装 Ollama Python SDK。

如果您使用过 OpenAI Python SDK,那么 Ollama Python SDK 会让您感觉非常熟悉。以下是我们如何使用它来进行聊天补全调用:

from ollama import chat
from rich import print

response = chat(model="llama3.2",
messages = [
{"role": "user", "content": "Briefly describe the components of an MLflow model"}
]
)

print(response)

它将返回:

ChatResponse(
model='llama3.2',
created_at='2025-01-30T15:57:39.097119Z',
done=True,
done_reason='stop',
total_duration=7687553708,
load_duration=823704250,
prompt_eval_count=35,
prompt_eval_duration=3414000000,
eval_count=215,
eval_duration=3447000000,
message=Message(
role='assistant',
content="In MLflow, a model consists of several key components:\n\n1. **Model Registry**: A centralized
storage for models, containing metadata such as the model's name, version, and description.\n2. **Model Version**:
A specific iteration of a model, represented by a unique version number. This can be thought of as a snapshot of
the model at a particular point in time.\n3. **Model Artifacts**: The actual model code, parameters, and data used
to train the model. These artifacts are stored in the Model Registry and can be easily deployed or reused.\n4.
**Experiment**: A collection of runs that use the same hyperparameters and model version to train and evaluate a
model. Experiments help track progress, provide reproducibility, and facilitate collaboration.\n5. **Run**: An
individual instance of training or testing a model using a specific experiment. Runs capture the output of each
run, including metrics such as accuracy, loss, and more.\n\nThese components work together to enable efficient
model management, version control, and reproducibility in machine learning workflows.",
images=None,
tool_calls=None
)
)

我们已经验证了 Ollama Python SDK 已设置并正常工作。我们也知道了在添加跟踪支持时需要关注的方法:ollama.chat

步骤 2:编写一个跟踪装饰器

有几种方法可以为 Ollama 的 SDK 添加跟踪——我们可以直接修改 SDK 代码,创建一个包装类,或者使用 Python 的方法修补 (method patching) 功能。在本例中,我们将使用一个装饰器来修补 SDK 的 chat 方法。这种方法让我们可以在不修改 SDK 代码或创建额外包装类的情况下添加跟踪,但它确实需要理解 Python 的装饰器模式和 MLflow Tracing 的工作原理。

import mlflow
from mlflow.entities import SpanType
from mlflow.tracing.utils import set_span_chat_messages
from functools import wraps
from ollama import chat as ollama_chat

def _get_span_type(task_name: str) -> str:
span_type_mapping = {
"chat": SpanType.CHAT_MODEL,
}
return span_type_mapping.get(task_name, SpanType.UNKNOWN)

def trace_ollama_chat(func):
@wraps(func)
def wrapper(*args, **kwargs):
with mlflow.start_span(
name="ollama.chat",
span_type=_get_span_type("chat"),
) as span:
# Set model name as a span attribute
model_name = kwargs.get("model", "")
span.set_attribute("model_name", model_name)

# Log the inputs
input_messages = kwargs.get("messages", [])
span.set_inputs({
"messages": input_messages,
"model": model_name,
})

# Set input messages
set_span_chat_messages(span, input_messages)

# Make the API call
response = func(*args, **kwargs)

# Log the outputs
if hasattr(response, 'to_dict'):
output = response.to_dict()
else:
output = response
span.set_outputs(output)

output_message = response.message

# Append the output message
set_span_chat_messages(span, [{"role": output_message.role, "content": output_message.content}], append=True)

return response
return wrapper

让我们分解一下代码,看看它是如何工作的。

  1. 我们首先定义一个辅助函数 _get_span_type,它将 Ollama 的方法映射到 MLflow 的跨度类型。虽然我们目前只跟踪 chat 函数,这并非严格必要,但它展示了一种可以应用于其他方法的模式。这遵循了跟踪贡献指南中推荐的 Anthropic 提供商的参考实现。

  2. 我们使用 functools.wraps 定义一个装饰器 trace_ollama_chat,来修补 chat 函数。这里有几个关键步骤:

    1. 我们使用 mlflow.start_span 启动一个新的跨度。跨度名称设置为 "ollama.chat",跨度类型设置为 _get_span_type 返回的值。

    2. 我们使用 span.set_attributemodel_name 设置为跨度的一个属性。这并非严格必要,因为模型名称也会被记录在输入中,但它展示了如何为跨度设置任意属性。

    3. 我们使用 span.set_inputs 将消息作为输入记录到跨度中。我们通过访问 kwargs 字典从 messages 参数中获取这些消息。这些消息将被记录到 MLflow UI 中跨度的 "inputs" 部分。我们还将模型名称作为输入记录下来,同样是为了说明如何记录任意输入。

      Inputs

    4. 我们使用 MLflow 的 set_span_chat_messages 实用函数来格式化输入消息,使其在 MLflow UI 的聊天面板中能良好地显示。这个辅助函数确保消息被正确格式化,并为每个消息角色应用适当的样式。

    5. 我们使用 func(*args, **kwargs) 调用原始函数。这就是 Ollama 的 chat 函数。

    6. 我们使用 span.set_outputs 将函数的输出作为跨度属性记录下来。这会获取 Ollama API 的响应,并将其设置为跨度的一个属性。这些输出将被记录到 MLflow UI 中跨度的 "outputs" 部分。

      Outputs

    7. 我们从响应中提取输出消息,并再次使用 set_span_chat_messages 将其附加到聊天历史中,确保它出现在 MLflow UI 的聊天面板中。

      Messages Panel

    8. 最后,我们返回 API 调用的响应,不做任何更改。现在,当我们用 trace_ollama_chat 修补 chat 函数时,该函数将被跟踪,但其行为将与正常情况一样。

有几点需要注意:

  • 这个实现使用了一个简单的装饰器模式,它在不修改底层 Ollama SDK 代码的情况下添加了跟踪。这使得它成为一种轻量级且易于维护的方法。
  • 使用 set_span_chat_messages 确保输入和输出消息都能在 MLflow UI 的聊天面板中以用户友好的方式显示,从而可以轻松地跟踪对话流程。
  • 我们还有其他几种方法可以实现这种跟踪行为。我们可以编写一个包装类,或者使用一个简单的包装函数来用 @mlflow.trace 装饰 chat 函数。一些编排框架可能需要更复杂的方法,比如回调或 API 钩子。有关更多详细信息,请参阅 MLflow Tracing 贡献指南

步骤 3:修补 chat 方法并进行尝试

现在我们有了跟踪装饰器,可以修补 Ollama 的 chat 方法并进行尝试了。

original_chat = ollama_chat
chat = trace_ollama_chat(ollama_chat)

这段代码有效地修补了当前作用域中的 ollama.chat 函数。我们首先将原始函数存储在 original_chat 中以备不时之需,然后将 chat 重新赋值为装饰后的版本。这意味着我们代码中后续对 chat() 的任何调用都将使用被跟踪的版本,同时仍保留其原始功能。

现在,当我们调用 chat() 时,该方法将被跟踪,结果将记录到 MLflow UI 中:

mlflow.set_experiment("ollama-tracing")

response = chat(model="llama3.2",
messages = [
{"role": "user", "content": "Briefly describe the components of an MLflow model"}
]
)

Tracing results

跟踪工具和工具调用

Ollama Python SDK 支持工具调用。我们希望记录两件主要的事情:

  1. LLM 可用的工具
  2. 实际的工具调用,包括具体的工具和传递给它的参数。

请注意,“工具调用”指的是 LLM 指定使用哪个工具以及传递什么参数,而不是该工具的实际执行。当 LLM 进行工具调用时,它实际上是在说“应该用这些参数运行这个工具”,而不是自己运行这个工具。工具的实际执行是分开进行的,通常在应用程序代码中。

以下是更新后的跟踪代码,修补了 Ollama 的 chat 方法,用于记录可用工具并捕获工具调用:

from mlflow.entities import SpanType
from mlflow.tracing.utils import set_span_chat_messages, set_span_chat_tools
from functools import wraps
from ollama import chat as ollama_chat
import json
from uuid import uuid4

def _get_span_type(task_name: str) -> str:
span_type_mapping = {
"chat": SpanType.CHAT_MODEL,
}
return span_type_mapping.get(task_name, SpanType.UNKNOWN)

def trace_ollama_chat(func):
@wraps(func)
def wrapper(*args, **kwargs):
with mlflow.start_span(
name="ollama.chat",
span_type=_get_span_type("chat"),
) as span:
# Set model name as a span attribute
model_name = kwargs.get("model", "")
span.set_attribute("model_name", model_name)

# Log the inputs
input_messages = kwargs.get("messages", [])
tools = kwargs.get("tools", [])
span.set_inputs({
"messages": input_messages,
"model": model_name,
"tools": tools,
})

# Set input messages and tools
set_span_chat_messages(span, input_messages)
if tools:
set_span_chat_tools(span, tools)

# Make the API call
response = func(*args, **kwargs)

# Log the outputs
if hasattr(response, "to_dict"):
output = response.to_dict()
else:
output = response
span.set_outputs(output)

output_message = response.message

# Prepare the output message for span
output_span_message = {
"role": output_message.role,
"content": output_message.content,
}

# Handle tool calls if present
if output_message.tool_calls:
tool_calls = []
for tool_call in output_message.tool_calls:
tool_calls.append({
"id": str(uuid4()),
"type": "function",
"function": {
"name": tool_call.function.name,
"arguments": json.dumps(tool_call.function.arguments),
}
})
output_span_message["tool_calls"] = tool_calls

# Append the output message
set_span_chat_messages(span, [output_span_message], append=True)

return response

return wrapper

这里的关键变化是:

  • 我们使用 tools = kwargs.get("tools", [])tools 参数中提取了可用工具列表,将它们作为输入记录下来,并使用 set_span_chat_tools 来捕获它们,以便包含在聊天面板中。
  • 我们在输出消息中为工具调用添加了特殊处理,确保按照 ToolCall 规范对其进行格式化。

现在让我们用一个简单的小费计算工具来测试一下。工具是根据OpenAI 规范定义的,用于工具调用。

chat = trace_ollama_chat(ollama_chat)

tools = [
{
"type": "function",
"function": {
"name": "calculate_tip",
"description": "Calculate the tip amount based on the bill amount and tip percentage",
"parameters": {
"type": "object",
"properties": {
"bill_amount": {
"type": "number",
"description": "The total bill amount"
},
"tip_percentage": {
"type": "number",
"description": "The percentage of the bill to be given as a tip, given as a whole number."
}
},
"required": ["bill_amount", "tip_percentage"]
}
}
}
]

response = chat(
model="llama3.2",
messages=[
{"role": "user", "content": "What is the tip for a $187.32 bill with a 22% tip?"}
],
tools=tools,
)

我们可以在 MLflow UI 中检查轨迹,现在可用工具和工具调用结果都已显示:

Tool Call Results

编排:构建一个工具调用循环

到目前为止,Ollama 的例子只在每次进行聊天补全时生成一个跨度。但许多 GenAI 应用程序包含多个 LLM 调用、检索步骤、工具执行和其他自定义步骤。虽然我们在这里不会详细讨论如何为编排框架添加跟踪,但我们将通过定义一个基于我们之前定义的工具的工具调用循环来阐述一些关键概念。

工具调用循环将遵循以下模式:

  1. 将用户提示作为输入
  2. 以一个或多个工具调用作为响应
  3. 对于每个工具调用,执行该工具并存储结果
  4. 将工具调用结果以 tool 角色追加到消息历史记录中
  5. 再次调用 LLM,传入工具调用结果,提示它为用户的提示提供最终答案

以下是一个只有一个工具调用的实现。

class ToolExecutor:
def __init__(self):
self.tools = [
{
"type": "function",
"function": {
"name": "calculate_tip",
"description": "Calculate the tip amount based on the bill amount and tip percentage",
"parameters": {
"type": "object",
"properties": {
"bill_amount": {
"type": "number",
"description": "The total bill amount"
},
"tip_percentage": {
"type": "number",
"description": "The percentage of the bill to be given as a tip, represented as a whole number."
}
},
"required": ["bill_amount", "tip_percentage"]
}
}
}
]

# Map tool names to their Python implementations
self.tool_implementations = {
"calculate_tip": self._calculate_tip
}

def _calculate_tip(self, bill_amount: float, tip_percentage: float) -> float:
"""Calculate the tip amount based on the bill amount and tip percentage."""
bill_amount = float(bill_amount)
tip_percentage = float(tip_percentage)
return round(bill_amount * (tip_percentage / 100), 2)
def execute_tool_calling_loop(self, messages):
"""Execute a complete tool calling loop with tracing."""
with mlflow.start_span(
name="ToolCallingLoop",
span_type="CHAIN",
) as parent_span:
# Set initial inputs
parent_span.set_inputs({
"initial_messages": messages,
"available_tools": self.tools
})

# Set input messages
set_span_chat_messages(parent_span, messages)

# First LLM call (already traced by our chat method patch)
response = chat(
messages=messages,
model="llama3.2",
tools=self.tools,
)

messages.append(response.message)

tool_calls = response.message.tool_calls
tool_results = []

# Execute tool calls
for tool_call in tool_calls:
with mlflow.start_span(
name=f"ToolExecution_{tool_call.function.name}",
span_type="TOOL",
) as tool_span:
# Parse tool inputs
tool_inputs = tool_call.function.arguments
tool_span.set_inputs(tool_inputs)

# Execute tool
func = self.tool_implementations.get(tool_call.function.name)
if func is None:
raise ValueError(f"No implementation for tool: {tool_call.function.name}")

result = func(**tool_inputs)
tool_span.set_outputs({"result": result})

tool_results.append({
"tool_call_id": str(uuid4()),
"output": str(result)
})

messages.append({
"role": "tool",
"tool_call_id": str(uuid4()),
"content": str(result)
})

# Prepare messages for final response
messages.append({
"role": "user",
"content": "Answer the initial question based on the tool call results. Do not refer to the tool call results in your response. Just give a direct answer."
})

# Final LLM call (already traced by our chat method patch)
final_response = chat(
messages=messages,
model="llama3.2"
)

# Set the final output for the parent span
parent_span.set_outputs({
"final_response": final_response.message.content,
"tool_results": tool_results
})

print(final_response)

# set output messages
set_span_chat_messages(parent_span, [final_response.message.model_dump()], append=True)

return final_response

以下是我们在这个工具调用循环中处理跟踪的方式:

  1. 我们首先使用 mlflow.start_span 为工具调用循环设置一个父跨度。我们将跨度名称设置为 "ToolCallingLoop",跨度类型设置为 "CHAIN",表示一个操作链。
  2. 我们将初始消息和可用工具作为输入记录到跨度中。这有助于未来的调试,因为它允许我们验证工具是否可用并正确配置。
  3. 我们使用我们修补过的 chat 函数进行第一次 LLM 调用。这个调用已经被我们的装饰器跟踪了,所以我们不需要做任何特殊操作来跟踪它。
  4. 我们遍历工具调用,执行每个工具并存储结果。每个工具执行都用一个新的跨度进行跟踪,该跨度以工具函数名命名。输入和输出作为属性记录在跨度上。
  5. 我们将工具调用结果以 tool 角色追加到消息历史中。这允许 LLM 在后续请求中看到工具调用的结果。它也允许我们在 MLflow UI 中看到工具调用的结果。
  6. 我们为最终响应准备消息,包括一个提示,要求根据工具调用结果回答最初的问题。
  7. 我们使用我们修补过的 chat 函数进行最后的 LLM 调用。同样,因为我们使用的是修补过的函数,所以这个调用已经被跟踪了。
  8. 我们为父跨度设置最终输出,包括来自 LLM 的最终响应和工具结果。
  9. 最后,我们使用 set_span_chat_messages 将最终响应追加到 MLflow UI 的聊天历史中。请注意,为了保持整洁和简单,我们只用 set_span_chat_messages 将用户的初始查询和最终响应记录到父跨度。我们可以点击进入嵌套的跨度来查看工具调用结果和其他细节。

这个过程创建了整个工具调用循环的全面轨迹,从最初的请求到工具执行和最终的响应。

我们可以按如下方式执行。但请注意,在没有完全理解它将在您的系统上做什么之前,您*不应该*运行由 LLM 生成或调用的任意代码。

executor = ToolExecutor()
response = executor.execute_tool_calling_loop(
messages=[
{"role": "user", "content": "What is the tip for a $235.32 bill with a 22% tip?"}
]
)

结果生成以下轨迹:

Tool Calling Loop

结论

本文展示了如何将 MLflow Tracing 扩展到其内置提供商支持之外。我们从一个简单的例子开始——为 Ollama Python SDK 的 chat 方法添加跟踪——并看到了如何通过一个轻量级的补丁,捕获每次聊天补全的详细信息。然后,我们在此基础上构建了一个更复杂的工具执行循环的跟踪。

关键要点是:

  • MLflow Tracing 高度可定制,可以适应那些没有提供自动记录 (autologging) 的提供商。
  • 添加基本的跟踪支持通常只需最少的代码更改。在本例中,我们修补了 Ollama Python SDK 的 chat 方法,并编写了几行代码来添加跟踪支持。
  • 用于简单 API 调用的相同原则可以扩展到具有多个步骤的复杂工作流。在本例中,我们跟踪了一个包含多个步骤和工具调用的工具调用循环。