# 如何构建 AI 能耗可观测性

> 用 OpenTelemetry、Prometheus 和 Kepler 记录每个 AI 请求和智能体步骤的 token、延迟、能耗和电网碳强度，并设定能耗预算。

Source: https://greenai.guide/zh/工程/如何构建-ai-能耗可观测性/  
Updated: 2026-11-26

## 简而言之

AI 能耗可观测性是指为每次模型调用和每个智能体步骤记录它做了什么（模型、token、缓存命中、重试、工具调用）、用了多长时间，以及用了多少能源：在您运行硬件的地方测量，在您不运行硬件的地方估算。在节点上测量功率，按忙碌时间或 token 把它分配到服务和请求，把每个数字标记为实测、分摊或估算，并在查询时与电网碳强度关联。然后像管理延迟目标一样管理每项成功任务的能耗。

## 要点

- 为每次模型调用记录模型、输入和输出 token、缓存 token、延迟、重试、工具调用、结果、硬件池和区域；默认绝不记录提示词文本。
- OpenTelemetry GenAI 语义约定已迁至独立仓库，并于 2026 年 11 月发布 v0.1.0；它们仍处于 Development 状态，且没有定义能耗指标。
- CNCF Sandbox 项目 Kepler 把节点、pod 和容器的能耗导出到 Prometheus，方法是按 CPU 时间比例分配实测的活动功率；它对 NVIDIA GPU 的支持仍是实验性的。
- 把能耗导出为以焦耳计的计数器；Prometheus 的 rate() 随后即可得到瓦特。
- 跟踪每项成功任务的能耗，并同时显示总量；当它上升时，像对待延迟一样发出警报。

## 什么是 AI 能耗可观测性？ {#what-is-ai-energy-observability}

**它是一种做法：为每个 AI 请求和智能体步骤，把能耗与延迟、错误和成本记录在一起，让您能看到是哪个功能、模型或工作流在消耗能源，以及某项改动是否有帮助。**它扩展的是您已经在运行的追踪和指标，而不是取代它们。

有两个理念让它行之有效。**token 和调用次数是领先指标**：成本低、精确，每次调用都能获得，包括托管 API。而且**每个能耗数字都带有方法标签**：*实测*（在您掌控的硬件上用电表测量）、*分摊*（把实测的节点总量分给各个请求）或*估算*（根据 token 建模，例如托管 API）。边界和不确定性在[如何测量 AI 能耗](/zh/良好实践/如何测量-ai-的能耗和碳排放/)中介绍；本指南讲的是如何把能耗接入生产环境的遥测。

## 每个请求或智能体步骤应该记录什么？ {#what-should-i-record-for-each-request-or-agent-step}

**记录这次调用做了什么、用了多长时间、在什么上运行、在哪里运行，以及如何结束，形式是低基数的指标加上每次调用一个追踪 span。**不要记录内容。

| 字段 | 示例属性 | 为什么对能耗重要 |
|---|---|---|
| 操作和提供商 | `gen_ai.operation.name`, `gen_ai.provider.name` | 区分聊天、嵌入、工具运行和检索 |
| 请求的模型和实际提供服务的模型 | `gen_ai.request.model`, `gen_ai.response.model` | 模型规模是最大的单一因素；路由器会按调用改变它 |
| 输入和输出 token | `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens` | 能耗随处理和生成的 token 增加 |
| 缓存 token 和推理 token | `gen_ai.usage.cache_read.input_tokens`, `gen_ai.usage.reasoning.output_tokens` | 缓存读取省去了工作；隐藏的推理则增加了工作 |
| 输出上限 | `gen_ai.request.max_tokens` | 显示是否设置了限制 |
| 延迟 | `gen_ai.client.inference.duration`，首个数据块的时间 | 忙碌时间是分摊依据；慢调用会占用硬件 |
| 结果 | `error.type`；您自己的任务结果 | 失败和重试的调用耗费能源却毫无产出 |
| 重试和响应缓存命中 | 您自己的计数器 | 重试会使成本成倍增加；您自己的缓存命中则完全避免了调用 |
| 智能体和工具步骤 | `gen_ai.agent.name`, `gen_ai.tool.name`；每次智能体运行中的推理和工具调用次数 | 智能体循环通常是 token 用量失控的根源 |
| 硬件池和利用率 | 您的硬件池标签；来自节点的 GPU 和 CPU 利用率 | 解释每个 token 的能耗；闲置的硬件池会在这里显现 |
| 能耗 | 您自己的以焦耳计的指标，附带实测、分摊或估算的方法标签 | 您想要管理的对象 |
| 区域和时间 | `cloud.region`，时间戳 | 应用电网碳强度时需要 |

第二列中的名称来自 OpenTelemetry GenAI 语义约定（见下文），注明“您自己的”除外。请求 ID、用户 ID 和对话 ID 只放在 span 上，绝不作为指标标签。

## 如何从节点功率得到单个请求的能耗？ {#how-do-i-get-from-node-power-to-a-single-request}

**在一个短窗口内测量节点或设备的能耗，然后按说明的规则把它分给该窗口内完成的工作，并检查各份额加起来是否等于实测总量。**并不存在针对单个请求的功率计。

常见的做法（也是 Kepler 对 CPU 使用的做法）把每个窗口的能耗分成两部分：

- **空闲能耗**：无论有没有工作，节点都要消耗的基线。
- **活动能耗**：其余部分，按资源使用比例在工作负载之间分配。Kepler 的规则是，在每个时间间隔内，工作负载功率 = （工作负载 CPU 时间 ÷ 节点 CPU 时间）× 活动功率。

对于模型服务，您可以把同样的思路延伸到请求层面：

1. **按设备、按窗口**（例如 15 到 60 秒），从 RAPL、NVML 能耗计数器或节点级读数中获取实测能耗。
2. **减去空闲能耗**，空闲能耗在同一节点上加载模型、无流量的情况下测量。
3. **在请求之间分配活动能耗**，按某个权重的比例：服务器报告的 GPU 或 CPU 忙碌时间，或者 token 权重。Fernandez 等人发现，解码每个 token 的能耗高于预填充，所以如果按 token 加权，要给输出 token 更大的权重，权重根据您自己的基准测试运行拟合（参见[如何对 CPU 与 GPU 推理的能耗进行基准测试](/zh/工程/如何对-cpu-与-gpu-推理的能耗进行基准测试/)）。
4. **把空闲能耗作为每个硬件池的单独一行报告**，或者按比例分摊并加以说明。把它藏在每个请求的数字里，会让一个半空的 GPU 池看起来很高效。
5. **对账。**分摊的能耗加上空闲能耗之和，必须等于该窗口的实测总量。不相等时发出警报。

**了解其局限。**Kepler 自己的指南列出了这些局限：两个 CPU 时间相同的进程，可能因为休眠状态、频率调节、向量指令和受内存限制的停顿而消耗不同的功率；在同一窗口内，突发性工作相对于稳定工作会被少分摊。它建议把这种方法用于趋势和相对比较，而不是绝对的预算决策。对于 NVIDIA GPU，Kepler 的实验性支持按流式多处理器利用率在进程之间分配设备的活动功率，所用的 NVML 功率读数的平均窗口取决于 GPU 型号。

对于调用托管 API，您根本无法计量；请根据 token 进行估算，并把结果标记为*估算*。参见[如何估算 AI API 调用的能耗](/zh/如何/如何估算-ai-api-调用的能耗/)。

<!-- figure: Attribution flow: measured node energy per window splits into idle energy (reported per pool) and active energy, which is divided between requests by busy time or token weight, with a reconciliation check that the parts sum to the measured total. -->

## OpenTelemetry GenAI 约定涵盖什么？ {#what-do-the-opentelemetry-genai-conventions-cover}

**它们为模型调用、智能体、工具和检索定义了标准的 span 和指标名称，包括 token 计数，但没有任何关于能耗的内容，而且仍处于 Development 状态。**凡是它们涵盖的都使用它们，再加上您自己带命名空间的能耗指标。

截至 2026 年 11 月 26 日核查时的情况：

- **新家，首个版本。**GenAI 约定已从 OpenTelemetry 主语义约定中迁出，进入独立的仓库，并于 2026 年 11 月 21 日发布了首个独立版本 v0.1.0。opentelemetry.io 上的旧页面现在注明内容已迁移。
- **Development 状态。**这些约定以及其中的 GenAI 属性和指标都被标记为 Development，而且 v0.1.0 列出了相对于上一版本的破坏性变更。例如，它用单独的 `gen_ai.client.inference.operation.input_tokens` 和 `...output_tokens` 直方图取代了 `gen_ai.client.token.usage` 直方图，并把推理计时从 `gen_ai.client.operation.duration` 移到了 `gen_ai.client.inference.duration`。请锁定您实现的版本，并预期会有重命名。
- **推理 span** 命名为 `{gen_ai.operation.name} {gen_ai.request.model}`（例如 `chat small-model`），并带有模型、提供商和 `gen_ai.usage.*` token 属性，包括缓存读写和推理 token。
- **智能体和工具 span。**进程内的一次智能体运行是一个类型为 INTERNAL 的 `invoke_agent {gen_ai.agent.name}` span；每次工具运行是一个 `execute_tool {gen_ai.tool.name}` span。指标包括 `gen_ai.invoke_agent.inference_calls` 和 `gen_ai.invoke_agent.tool_calls`，即每次智能体运行中的模型和工具调用次数，它们是循环的良好早期预警。
- **内容需主动开启。**提示词、响应、系统指令和工具定义（`gen_ai.input.messages`、`gen_ai.output.messages` 等）是 Opt-In 属性，约定提醒其中很可能包含敏感信息，包括个人数据。
- **硬件能耗另有定义。**OpenTelemetry 的硬件约定定义了 `hw.energy`（以焦耳计的计数器）和 `hw.power`（以瓦特计的仪表），同样处于 Development 状态，并建议在可能时报告 `hw.energy` 而不是 `hw.power`。请把它们用于您自己采集的节点和设备遥测。

## Prometheus、Grafana 和 Kepler 各自扮演什么角色？ {#where-do-prometheus-grafana-and-kepler-fit}

**Prometheus 存储时间序列，Grafana 或类似工具绘制仪表板，而 Kepler、NVIDIA 的 DCGM exporter 和您的推理服务器等导出器提供功率和服务指标。**来自 OpenTelemetry 的应用指标也进入同一个存储。

- **导出焦耳，而不是瓦特。**Prometheus 的命名指南把焦耳列为能量的基本单位，并建议导出以焦耳计的计数器，这样 `rate(joules[5m])` 就能给出以瓦特计的功率。计数器能扛过抓取间隙；瞬时瓦特数的仪表则不能。
- **注意名称。**根据 OpenTelemetry 的 Prometheus 兼容性规则，单位为 `J` 的计数器会加上 `_joules` 后缀和 `_total` 后缀，所以 `example.inference.energy` 会显示为 `example_inference_energy_joules_total`。
- **注意基数。**Prometheus 提醒，每一种标签组合都是一条新的时间序列，标签中不得包含用户 ID 或电子邮件地址等无界的值。
- **用于 Kubernetes 的 Kepler。**Kepler 是一个 CNCF Sandbox 项目，把节点、pod、容器、进程和虚拟机层面的能耗导出到 Prometheus。自 0.10 版重写以来，指标包括 `kepler_node_cpu_joules_total`、`kepler_pod_cpu_joules_total` 和 `kepler_pod_gpu_joules_total`。CPU 指标带有 `zone` 标签（`package`、`core`、`uncore`、`dram`、`psys`）；这些区域相互重叠，所以请只筛选其中一个。DRAM 只在硬件提供时才出现，而许多客户端 CPU、AMD 处理器和虚拟机并不提供。GPU 监控，以及通过 Redfish 从服务器管理控制器读取的平台功率，都是实验性的，默认关闭。
- **GPU 导出器。**在 4.9.0 版本中，NVIDIA 的 DCGM exporter 的默认指标包括 `DCGM_FI_DEV_GPU_ENERGY_JOULES_TOTAL`（自驱动程序重新加载以来的能耗）和 `DCGM_FI_DEV_BOARD_POWER_WATTS`。指标名称在不同版本之间有过变化，所以请查看您所部署版本的计数器文件。
- **服务指标。**推理服务器会公开自己的计数器；例如，llama.cpp 的服务器在以 `--metrics` 启动时，会在 Prometheus 端点上发布 `llamacpp:prompt_tokens_total` 和 `llamacpp:tokens_predicted_total`。用实测的节点能耗除以服务器端的 token 数，是检验您分摊结果的有用方法。

## 一个完整的架构示例是什么样的？ {#what-does-a-worked-architecture-look-like}

**四层：应用按调用和按任务发出 span 和指标；节点导出器测量能耗；一个小作业负责分摊和对账；仪表板把能耗与电网碳强度关联起来。**您可以逐个服务地添加它们。

1. **应用。**每次模型调用是一个带有 GenAI 属性的客户端 span。每项面向用户的任务是一个父级 `invoke_agent` span。应用记录 token 和时长直方图、按结果统计的任务计数器，以及一个带方法标签的能耗计数器：根据校准过的每 token 系数得出的*估算*值，或者在对账作业提供数据时的*分摊*值。
2. **节点。**Kubernetes 节点上的 Kepler（CPU，以及在启用时的 GPU）、GPU 节点上的 DCGM exporter，以及在能获取时用于墙插处核对的 BMC 或智能电表读数。
3. **分摊作业。**在每个窗口，它读取节点和 pod 的能耗，减去空闲能耗，利用服务指标按忙碌时间或 token 分配活动能耗，写出每个服务和模型的分摊能耗，并在各部分与总量不一致时发出警报。
4. **存储和仪表板。**指标以低分辨率保留数月；追踪保留数天；电网碳强度按区域存储为仪表。

<!-- figure: Worked architecture: application services emit OpenTelemetry spans and metrics to a collector; Kepler, the DCGM exporter and BMC readings feed Prometheus; an attribution job reconciles node energy with per-request tokens; a carbon-intensity exporter adds a gauge per region; Grafana shows energy per task, idle share and carbon. -->

### 示例指标名称 {#example-metric-names}

| 指标（存储在 Prometheus 中的名称） | 类型 | 来源 |
|---|---|---|
| `gen_ai_client_inference_duration_seconds` | 直方图 | 应用（OpenTelemetry GenAI 约定） |
| `gen_ai_client_inference_operation_input_tokens`, `..._output_tokens` | 直方图 | 应用（约定） |
| `example_inference_energy_joules_total{example_energy_method=...}` | 计数器 | 应用（您自己的名称） |
| `example_task_completed_total{example_outcome="success"}` | 计数器 | 应用（您自己的名称） |
| `kepler_pod_cpu_joules_total{zone="package"}`, `kepler_pod_gpu_joules_total` | 计数器 | Kepler |
| `DCGM_FI_DEV_GPU_ENERGY_JOULES_TOTAL` | 计数器 | DCGM exporter |
| `grid_carbon_intensity_gco2_per_kwh{cloud_region=...}` | 仪表 | 您自己的导出器 |

### 示例代码 {#example-code}

下面的代码片段把一次兼容 OpenAI 的聊天调用包装在一个 OpenTelemetry span 中，记录约定中的 token 和时长指标，并加上一个能耗计数器。它是供改编的示例：能耗数字的好坏取决于您根据自己的测量拟合出的每 token 系数；它还没有对缓存输入做区别处理；`example.*` 名称应改为您组织自己的命名空间。

```python
"""Illustrative: record tokens, latency and an energy figure for each model call with OpenTelemetry.

Adapt before use. Attribute and metric names under gen_ai.* follow the OpenTelemetry GenAI
semantic conventions (v0.1.0, status Development); names under example.* are our own,
because the conventions define no energy metric for model calls.
"""
import json
import time
from contextlib import contextmanager

from opentelemetry import metrics, trace
from opentelemetry.trace import SpanKind, Status, StatusCode

tracer = trace.get_tracer("example.inference")
meter = metrics.get_meter("example.inference")

input_tokens = meter.create_histogram(
    "gen_ai.client.inference.operation.input_tokens", unit="{token}",
    description="Input tokens per inference operation")
output_tokens = meter.create_histogram(
    "gen_ai.client.inference.operation.output_tokens", unit="{token}",
    description="Output tokens per inference operation")
duration = meter.create_histogram(
    "gen_ai.client.inference.duration", unit="s",
    description="Inference operation duration")
tasks = meter.create_counter(
    "example.task.completed", unit="{task}",
    description="User-facing tasks finished, by outcome")
energy = meter.create_counter(
    "example.inference.energy", unit="J",
    description="Energy attributed to inference operations (see example.energy.method)")

# Joules per input and output token for each model on each hardware pool, fitted from your
# own benchmark runs. Never ship made-up coefficients: no entry means no estimate.
with open("energy_coefficients.json") as f:
    COEFFICIENTS = json.load(f)  # {"model@pool": {"j_per_input": ..., "j_per_output": ...}}


def estimate_joules(model, pool, tokens_in, tokens_out):
    c = COEFFICIENTS.get(f"{model}@{pool}")
    if c is None:
        return None
    return c["j_per_input"] * tokens_in + c["j_per_output"] * tokens_out


def chat(client, model, messages, *, provider, pool, region, feature, max_tokens=300):
    """Call an OpenAI-compatible chat endpoint inside a span; never record the prompt itself."""
    base = {"gen_ai.operation.name": "chat", "gen_ai.provider.name": provider,
            "gen_ai.request.model": model}
    # Low-cardinality labels only: no user IDs, request IDs or prompt text on metrics.
    labels = {**base, "example.pool": pool, "cloud.region": region, "example.feature": feature}
    with tracer.start_as_current_span(f"chat {model}", kind=SpanKind.CLIENT,
                                      attributes={**base, "gen_ai.request.max_tokens": max_tokens}) as span:
        start = time.monotonic()
        try:
            response = client.chat.completions.create(model=model, messages=messages,
                                                      max_tokens=max_tokens)
        except Exception as exc:
            error = {**labels, "error.type": type(exc).__qualname__}
            span.set_status(Status(StatusCode.ERROR))
            span.set_attribute("error.type", type(exc).__qualname__)
            duration.record(time.monotonic() - start, error)
            input_tokens.record(0, error)   # the conventions ask for 0 when usage is missing
            output_tokens.record(0, error)
            raise
        usage = response.usage
        details = getattr(usage, "prompt_tokens_details", None)
        cached = getattr(details, "cached_tokens", None) or 0
        span.set_attributes({
            "gen_ai.response.model": response.model,
            "gen_ai.usage.input_tokens": usage.prompt_tokens,
            "gen_ai.usage.output_tokens": usage.completion_tokens,
            "gen_ai.usage.cache_read.input_tokens": cached,
        })
        duration.record(time.monotonic() - start, labels)
        input_tokens.record(usage.prompt_tokens, labels)
        output_tokens.record(usage.completion_tokens, labels)
        joules = estimate_joules(model, pool, usage.prompt_tokens, usage.completion_tokens)
        if joules is not None:
            span.set_attribute("example.energy.joules", joules)
            span.set_attribute("example.energy.method", "estimated")
            energy.add(joules, {**labels, "example.energy.method": "estimated"})
        return response


@contextmanager
def task(agent_name, feature):
    """One user-facing task: every model call inside it becomes a child span of this one."""
    with tracer.start_as_current_span(f"invoke_agent {agent_name}", kind=SpanKind.INTERNAL, attributes={
            "gen_ai.operation.name": "invoke_agent", "gen_ai.agent.name": agent_name}):
        result = {"outcome": "failure"}  # the caller sets "success" once the task's check passes
        try:
            yield result
        finally:
            tasks.add(1, {"example.feature": feature, "example.outcome": result["outcome"]})
```

用法如下：

```python
with task("ticket-tagger", feature="support-tagging") as t:
    reply = chat(client, "small-model", messages, provider="openai",
                 pool="cpu-pool-a", region="eu-west-2", feature="support-tagging")
    if passes_schema_check(reply):
        t["outcome"] = "success"
```

### 示例查询 {#example-queries}

```promql
# Power drawn by inference, per feature (watts)
sum by (example_feature) (rate(example_inference_energy_joules_total[5m]))

# Energy per successful task over a day (joules): all energy, including failures, over successes
sum(increase(example_inference_energy_joules_total[1d]))
  / sum(increase(example_task_completed_total{example_outcome="success"}[1d]))

# Calibration check: estimated energy for a pool against Kepler's measured pod energy
sum(rate(example_inference_energy_joules_total{example_pool="gpu-pool-a"}[1h]))
  / (sum(rate(kepler_pod_gpu_joules_total{pod_namespace="inference"}[1h]))
     + sum(rate(kepler_pod_cpu_joules_total{pod_namespace="inference", zone="package"}[1h])))

# Grams of CO2 per hour by region: J/s x 3,600 s/h / 3,600,000 J/kWh x gCO2/kWh
sum by (cloud_region) (rate(example_inference_energy_joules_total[1h])) * 3600 / 3.6e6
  * on (cloud_region) group_left grid_carbon_intensity_gco2_per_kwh
```

## 如何像设定 SLO 一样设定能耗预算？ {#how-do-i-set-energy-budgets-like-slos}

**为每个功能选择一个指标，即每项成功任务的能耗，根据您自己的基线设定预算，并把持续上升当作延迟回归来处理。**同时也要关注总量。

- **指标。**在一个滚动窗口（例如 28 天）内的每项成功任务能耗（全部能耗，包括失败的尝试和重试，除以通过检查的任务数）。如果您只有 token 数据，就使用每项成功任务的 token 数；它会率先变化。
- **预算。**根据实测的[基线](/zh/如何/如何设定基线来证明-ai-节能效果/)而不是猜测来设定，并在更小的模型或缓存等改动腾出余量时收紧预算。
- **警报。**在相对于基线持续上升、每次智能体运行的模型或工具调用次数突增（循环）、GPU 池中空闲占比，以及对账失败时发出警报。
- **为改动设关卡。**当固定任务超出其 token 或能耗预算时，让 CI 构建失败；参见[在 CI 中进行能耗测试](/zh/工程/如何在-ci-cd-中加入能效测试/)。
- **关注总量。**每项任务能耗下降而总能耗上升，就是[反弹效应](/zh/术语表/#rebound-effect)。请在同一个仪表板上同时显示两者；参见[如何为 AI 能耗和排放设定目标](/zh/如何/如何为-ai-能耗和排放设定目标/)。


<!-- figure: An energy budget panel: energy per successful task for one feature over 28 days against its budget line, with total energy on a second axis and markers where a model change and a cache release moved the curve. -->
## 如何追踪智能体和分布式工作流？ {#how-do-i-trace-agents-and-distributed-workflows}

**为每项面向用户的任务分配一条追踪，在服务和队列之间传播它，并把能耗从模型调用 span 汇总到任务。**智能体让按调用的数字产生误导；按任务的数字才是用户的真实体验。

- **传播上下文。**OpenTelemetry SDK 在服务之间传播追踪上下文，默认使用 W3C Trace Context 和 Baggage 格式。除了 HTTP，还要让它贯穿消息队列和后台任务，否则跨多个服务的任务会断裂成互不相关的追踪。
- **组织追踪结构。**每项任务或子智能体一个 `invoke_agent` span，每次模型调用一个推理 span，每次工具调用一个 `execute_tool` span。检索和嵌入调用也有各自的 span。
- **从指标而不是采样的追踪中汇总。**如果您对追踪进行采样，采样后的追踪就无法给出总量。请把能耗和 token 作为每次调用的指标记录下来，用追踪来解释个别昂贵的任务。
- **关注循环指标。**每次智能体运行的模型和工具调用次数分布，以及每项任务的 token 分布，会在账单之前暴露失控的智能体。参见[如何阻止 AI 智能体浪费 token](/zh/如何/如何防止-ai-智能体浪费-token/)和[智能体 AI 与 token 浪费](/zh/文章/智能体-ai-与-token-浪费/)。
- **明确统计重试和缓存命中。**一次重试就是第二次调用；一次响应缓存命中就是避免了一次调用。参见[如何缓存 LLM 调用](/zh/如何/如何用缓存降低大语言模型调用的能耗/)。

<!-- figure: One agent task as a trace tree: an invoke_agent span containing chat spans for each model call, execute_tool spans for tool calls and a retried call, each labelled with tokens and joules, with the task total rolled up at the root. -->

## 如何加入碳排放？ {#how-do-i-add-carbon}

**在查询时用能耗乘以所在区域和时段的电网碳强度，并把能耗保留为主要数字。**碳排放取决于电网；能耗取决于您的代码。

绿色软件基金会的软件碳强度规范把得分表示为 SCI = ((E × I) + M) per R，其中 E 是能耗，I 是特定区域的碳强度，M 是隐含排放，R 是功能单位，并且排除了基于市场的措施。在实践中：

- 运行一个小型导出器，把每个区域的碳强度发布为仪表。在大不列颠，Carbon Intensity API 以 gCO2/kWh 为单位提供各地区的预测和估算；Electricity Maps 汇集了许多其他国家的历史、实时和预测电网数据。参见[如何查找电网碳强度数据](/zh/如何/如何查到所在电网的碳强度/)。
- 用 `cloud.region`（或您数据中心的位置）标记能耗，并在查询中进行关联，如上面的示例所示。
- 如果隐含排放在您的边界之内，请单独加上；参见[如何为 AI 功能计算 SCI 得分](/zh/如何/如何计算一项-ai-功能的软件碳强度-sci-得分/)。

## 隐私和数据保留怎么办？ {#what-about-privacy-and-retention}

**记录计数，而不是内容；详细追踪的保留时间要短于汇总指标。**能耗需要的是 token 数、模型、时间和硬件，这些都不需要提示词。

- **内容默认关闭。**OpenTelemetry 约定把提示词和响应属性设为 Opt-In，并提醒其中很可能包含个人数据。在生产环境中请保持关闭。如果为了调试必须采集内容，请在访问控制下单独存储，并按约定中 `*_ref` 属性允许的方式通过 URI 引用它，设置较短的过期时间。
- **最小化。**欧盟 GDPR 和英国 GDPR 的第 5 条都要求个人数据仅限于必要的范围，保存时间不超过必要的期限。除非确有需要，请对 span 中的用户标识符进行哈希处理或删除。
- **分层保留。**汇总指标（如果标签选择得当，其中不含个人数据）要保留足够长的时间以看出趋势和季节性；追踪保留数天或数周。
- **遥测本身也有足迹。**对追踪进行采样，对指标进行汇总，删除您从不查询的标签。

## 下一步做什么 {#what-to-do-next}

1. 为每次模型调用加上 OpenTelemetry GenAI 属性和 token 指标，锁定为 v0.1.0，并关闭提示词采集。
2. 加上任务 span 和任务结果计数器，并为一个功能绘制每项成功任务的能耗（或 token）图表。
3. 安装 Kepler，或在您的推理节点上读取 RAPL、NVML 和 DCGM，并记录每个硬件池的空闲功耗。
4. 根据基准测试运行拟合每 token 能耗系数（参见 [CPU 与 GPU 推理](/zh/工程/如何对-cpu-与-gpu-推理的能耗进行基准测试/)），并每周把估算值与实测的节点能耗进行对账。
5. 为每个区域加上碳强度仪表，并在能耗面板旁边加上碳排放面板。
6. 根据基线设定预算，对回归发出警报，并在 CI 中加入能耗测试。

## 常见问题

### 有没有关于 AI 能耗的 OpenTelemetry 标准？

针对模型调用的还没有。OpenTelemetry GenAI 语义约定涵盖推理、智能体和工具的 span 和指标，包括 token 计数，但没有定义能耗属性。OpenTelemetry 的硬件约定为部件定义了以焦耳计的 hw.energy。在约定出现之前，请为每次调用的能耗使用您自己带命名空间的指标。

### 如果我只能对整台服务器计量，如何得到每个请求的能耗？

进行分摊。把一个时间窗口内测得的能耗，按忙碌时间或 token 的比例分给该窗口内服务的请求，并单独报告空闲能耗，或按说明的规则分摊。检查分摊的各部分加起来是否等于测得的总量。

### 为了算出能耗，我应该记录提示词吗？

不应该。能耗取决于 token 数、模型、硬件和时间，而不是文字内容。OpenTelemetry 约定把提示词和响应内容设为需主动开启（opt-in），并提醒其中很可能包含个人数据。记录计数，而不是内容。

### 什么是 Kepler？

Kepler（Kubernetes-based Efficient Power Level Exporter）是一个 CNCF Sandbox 项目，把 Kubernetes 节点、pod 和容器的能耗和功率指标导出到 Prometheus。它读取 RAPL 等硬件计数器，并按 CPU 时间把活动功率分配给工作负载。

### 如何在仪表板上把能耗换算成碳排放？

在查询时（而不是在应用中）用能耗乘以其使用时所在区域和时段的电网碳强度。数据来源包括大不列颠的 GB Carbon Intensity API 以及其他地区的 Electricity Maps。请把能耗保留为主要指标，因为碳排放会随电网变化。

## 来源

- [OpenTelemetry GenAI semantic conventions (repository and v0.1.0 changelog)](https://github.com/open-telemetry/semantic-conventions-genai), OpenTelemetry (2026)
- [Semantic conventions for generative AI client inference (v0.1.0)](https://github.com/open-telemetry/semantic-conventions-genai/blob/v0.1.0/docs/gen-ai/client-inference.md), OpenTelemetry (2026)
- [Semantic conventions for generative AI agent spans (v0.1.0)](https://github.com/open-telemetry/semantic-conventions-genai/blob/v0.1.0/docs/gen-ai/gen-ai-agent-spans.md), OpenTelemetry (2026)
- [Semantic conventions for generative AI metrics (v0.1.0)](https://github.com/open-telemetry/semantic-conventions-genai/blob/v0.1.0/docs/gen-ai/gen-ai-metrics.md), OpenTelemetry (2026)
- [Semantic conventions for hardware metrics (hw.energy, hw.power)](https://github.com/open-telemetry/semantic-conventions/blob/main/docs/hardware/common.md), OpenTelemetry (2026)
- [Prometheus and OpenMetrics compatibility](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/compatibility/prometheus_and_openmetrics.md), OpenTelemetry specification (2026)
- [SDK environment variables (OTEL_PROPAGATORS)](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md), OpenTelemetry specification (2026)
- [Metric and label naming](https://prometheus.io/docs/practices/naming/), Prometheus documentation (2026)
- [Kepler: Kubernetes-based Efficient Power Level Exporter](https://github.com/sustainable-computing-io/kepler), Kepler project, CNCF (2026)
- [Kepler metrics (v0.14.0)](https://github.com/sustainable-computing-io/kepler/blob/v0.14.0/docs/user/metrics.md), Kepler project, CNCF (2026)
- [Kepler power attribution guide (v0.14.0)](https://github.com/sustainable-computing-io/kepler/blob/v0.14.0/docs/developer/power-attribution-guide.md), Kepler project, CNCF (2026)
- [Kepler configuration (v0.14.0): experimental GPU and Redfish options](https://github.com/sustainable-computing-io/kepler/blob/v0.14.0/docs/user/configuration.md), Kepler project, CNCF (2026)
- [DCGM exporter default counters (4.9.0)](https://github.com/NVIDIA/dcgm-exporter/blob/4.9.0/etc/default-counters.csv), NVIDIA (2026)
- [NVML API reference: device queries](https://docs.nvidia.com/deploy/nvml-api/api/group__nvmlDeviceQueries.html), NVIDIA (2026)
- [llama.cpp HTTP server (/metrics)](https://github.com/ggml-org/llama.cpp/blob/master/tools/server/README.md), llama.cpp project (2026)
- [Energy considerations of large language model inference and efficiency optimizations](https://arxiv.org/abs/2504.17674), Fernandez et al. (arXiv 2504.17674) (2025)
- [Software Carbon Intensity (SCI) specification](https://sci.greensoftware.foundation/), Green Software Foundation (2024)
- [Carbon Intensity API](https://carbonintensity.org.uk/), National Energy System Operator (2026)
- [Electricity Maps](https://www.electricitymaps.com/), Electricity Maps (2026)
- [General Data Protection Regulation, Article 5](https://gdpr-info.eu/art-5-gdpr/), Regulation (EU) 2016/679, via gdpr-info.eu (2016)
- [A guide to the data protection principles (UK GDPR)](https://ico.org.uk/for-organisations/uk-gdpr-guidance-and-resources/data-protection-principles/a-guide-to-the-data-protection-principles/), Information Commissioner's Office (2026)
