跳到主要内容

跟踪 Gemini

Gemini Tracing via autolog

MLflow 跟踪为 Google Gemini 提供自动跟踪功能。通过调用 mlflow.gemini.autolog() 函数启用 Gemini 的自动跟踪,MLflow 将捕获嵌套跟踪并在调用 Gemini Python SDK 时将它们记录到活动的 MLflow 实验中。在 Typescript 中,您可以使用 tracedGemini 函数来包装 Gemini 客户端。

MLflow 跟踪自动捕获有关 Gemini 调用的以下信息

  • 提示和完成响应
  • 延迟
  • 模型名称
  • 如果指定,还包括额外的元数据,如 temperaturemax_tokens
  • Token 用量(输入、输出和总 Token 数)
  • 如果响应中返回函数调用
  • 如果抛出任何异常

开始使用

1

安装依赖项

bash
pip install 'mlflow[genai]' google-generativeai
2

启动 MLflow 服务器

如果您有本地 Python 环境 >= 3.10,您可以使用 mlflow CLI 命令在本地启动 MLflow 服务器。

bash
mlflow server
3

启用跟踪并进行 API 调用

使用 mlflow.gemini.autolog() 启用跟踪,并像往常一样进行 API 调用。

python
import mlflow
import google.generativeai as genai
import os

# Enable auto-tracing for Gemini
mlflow.gemini.autolog()

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

# Configure your API key
genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))

# Use Gemini as usual - traces will be automatically captured
model = genai.GenerativeModel("gemini-2.5-flash")
response = model.generate_content("What is the capital of France?")
print(response.text)
4

在 MLflow UI 中查看跟踪

浏览到 MLflow UI,网址为 https://:5000(或您的 MLflow 服务器 URL),您应该会看到 Gemini API 调用的跟踪。

→ 查看 后续步骤,了解有关更多 MLflow 功能(如用户反馈跟踪、提示管理和评估)的信息。

注意

当前的 MLflow 跟踪集成支持新的 Google GenAI SDK 和旧的 Google AI Python SDK。但是,MLflow 可能会在不通知的情况下停止支持旧包,强烈建议您将用例迁移到新的 Google GenAI SDK。

支持的 API

MLflow 支持对以下 Gemini API 进行自动跟踪

Python

文本生成聊天函数调用流式传输异步图像视频
-✅ (*1)--

(*1) 异步支持已在 MLflow 3.2.0 中添加。

TypeScript / JavaScript

内容生成聊天函数调用流式传输异步
-✅ (*2)-

(*2) 仅支持 models.generateContent()。捕获响应中的函数调用,并可以在 MLflow UI 中渲染。TypeScript SDK 本质上是异步的。

如需支持更多 API,请在 GitHub 上提交 功能请求

示例

基本文本生成

python
import mlflow
import google.genai as genai
import os

# Turn on auto tracing for Gemini
mlflow.gemini.autolog()

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


# Configure the SDK with your API key.
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])

# Use the generate_content method to generate responses to your prompts.
response = client.models.generate_content(
model="gemini-1.5-flash", contents="The opposite of hot is"
)

多轮聊天交互

MLflow 支持跟踪与 Gemini 的多轮对话

python
import mlflow

mlflow.gemini.autolog()

chat = client.chats.create(model="gemini-1.5-flash")
response = chat.send_message(
"In one sentence, explain how a computer works to a young child."
)
print(response.text)
response = chat.send_message(
"Okay, how about a more detailed explanation to a high schooler?"
)
print(response.text)

异步

MLflow 跟踪自 MLflow 3.2.0 起支持 Gemini SDK 的异步 API。用法与同步 API 相同。

python
# Configure the SDK with your API key.
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])

# Async API is invoked through the `aio` namespace.
response = await client.aio.models.generate_content(
model="gemini-1.5-flash", contents="The opposite of hot is"
)

Embeddings

MLflow 对 Gemini SDK 的跟踪支持嵌入式 API(仅限 Python)

python
result = client.models.embed_content(model="text-embedding-004", contents="Hello world")

Token 用量

MLflow >= 3.4.0 支持 Gemini 的 Token 使用量跟踪。每次 LLM 调用的 Token 使用量将记录在 mlflow.chat.tokenUsage 属性中。跟踪信息对象中的 token_usage 字段将显示整个跟踪过程中的总 Token 使用量。

python
import json
import mlflow

mlflow.gemini.autolog()

client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])

# Use the generate_content method to generate responses to your prompts.
response = client.models.generate_content(
model="gemini-1.5-flash", contents="The opposite of hot is"
)

# Get the trace object just created
trace = mlflow.get_trace(mlflow.get_last_active_trace_id())

# Print the token usage
total_usage = trace.info.token_usage
print("== Total token usage: ==")
print(f" Input tokens: {total_usage['input_tokens']}")
print(f" Output tokens: {total_usage['output_tokens']}")
print(f" Total tokens: {total_usage['total_tokens']}")

# Print the token usage for each LLM call
print("\n== Detailed usage for each LLM call: ==")
for span in trace.data.spans:
if usage := span.get_attribute("mlflow.chat.tokenUsage"):
print(f"{span.name}:")
print(f" Input tokens: {usage['input_tokens']}")
print(f" Output tokens: {usage['output_tokens']}")
print(f" Total tokens: {usage['total_tokens']}")
bash
== Total token usage: ==
Input tokens: 5
Output tokens: 2
Total tokens: 7

== Detailed usage for each LLM call: ==
Models.generate_content:
Input tokens: 5
Output tokens: 2
Total tokens: 7
Models._generate_content:
Input tokens: 5
Output tokens: 2
Total tokens: 7

Token 使用量跟踪同时支持 Python 和 TypeScript/JavaScript 实现。

禁用自动跟踪

可以通过调用 mlflow.gemini.autolog(disable=True)mlflow.autolog(disable=True) 全局禁用 Gemini 的自动跟踪。

后续步骤