跳到主要内容

追踪 AutoGen

AutoGen tracing via autolog

AutoGen AgentChat 是一个开源框架,用于构建对话式单代理和多代理应用程序。

MLflow Tracing 为 AutoGen AgentChat 提供了自动追踪能力。通过调用 mlflow.autogen.autolog() 函数启用 AutoGen 的自动追踪后,MLflow 将在代理执行时捕获嵌套追踪并将其记录到当前的 MLflow 实验中。

import mlflow

mlflow.autogen.autolog()
注意

请注意,mlflow.autogen.autolog() 应该在导入被追踪的 AutoGen 类之后调用。ChatCompletionClient 的子类(例如 OpenAIChatCompletionClientAnthropicChatCompletionClient)以及 BaseChatAgent 的子类(例如 AssistantAgentCodeExecutorAgent)应该在调用 mlflow.autogen.autolog() 之前导入。另请注意,此集成适用于 AutoGen 0.4.9 或更高版本。如果您使用的是 AutoGen 0.2,请改用 AG2 集成

MLflow 捕获关于 AutoGen 代理的以下信息

  • 传递给代理的消息,包括图片
  • 来自代理的响应
  • 每个代理发出的 LLM 和工具调用
  • 延迟
  • 如果抛出任何异常

支持的 API

MLflow 支持以下 AutoGen API 的自动追踪。它不支持异步生成器的追踪。异步流式 API,例如 run_streamon_messages_stream,不被追踪。

  • ChatCompletionClient.create
  • BaseChatAgent.run
  • BaseChatAgent.on_messages

基本示例

import os

# Imports of autogen classes should happen before calling autolog.
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient

import mlflow

# Turn on auto tracing for AutoGen
mlflow.autogen.autolog()

# Optional: Set a tracking URI and an experiment
mlflow.set_tracking_uri("https://:5000")
mlflow.set_experiment("AutoGen")

model_client = OpenAIChatCompletionClient(
model="gpt-4.1-nano",
# api_key="YOUR_API_KEY",
)

agent = AssistantAgent(
name="assistant",
model_client=model_client,
system_message="You are a helpful assistant.",
)

result = await agent.run(task="Say 'Hello World!'")
print(result)

工具代理

import os

# Imports of autogen classes should happen before calling autolog.
from autogen_agentchat.agents import AssistantAgent
from autogen_ext.models.openai import OpenAIChatCompletionClient

import mlflow

# Turn on auto tracing for AutoGen
mlflow.autogen.autolog()

# Optional: Set a tracking URI and an experiment
mlflow.set_tracking_uri("https://:5000")
mlflow.set_experiment("AutoGen")

model_client = OpenAIChatCompletionClient(
model="gpt-4.1-nano",
# api_key="YOUR_API_KEY",
)


def add(a: int, b: int) -> int:
"""add two numbers"""
return a + b


agent = AssistantAgent(
name="assistant",
model_client=model_client,
system_message="You are a helpful assistant.",
tools=[add],
)

await agent.run(task="1+1")

禁用自动跟踪

AutoGen 的自动追踪可以通过调用 mlflow.autogen.autolog(disable=True)mlflow.autolog(disable=True) 来全局禁用。