greenai.guide

Home › Green AI engineering › How to build AI energy observability

Green AI engineering

How to build AI energy observability

Updated · 15 min read

In short

AI energy observability means recording, for every model call and agent step, what it did (model, tokens, cache hits, retries, tool calls), how long it took, and how much energy it used, measured where you run the hardware and estimated where you don't. Measure power at the node, attribute it to services and requests by busy time or tokens, tag each figure as measured, attributed or estimated, and join it with grid carbon intensity at query time. Then manage energy per successful task like a latency objective.

Key points

  • Record model, tokens in and out, cached tokens, latency, retries, tool calls, outcome, hardware pool and region for every model call; never the prompt text by default.
  • The OpenTelemetry GenAI semantic conventions moved to their own repository and released v0.1.0 in November 2026; they are still at Development status and define no energy metric.
  • Kepler, a CNCF Sandbox project, exports node, pod and container energy to Prometheus by splitting measured active power in proportion to CPU time; its NVIDIA GPU support is experimental.
  • Export energy as a counter of joules; Prometheus's rate() then gives watts.
  • Track energy per successful task, with the total alongside it, and alert when it rises the way you would for latency.

What is AI energy observability?

It is the practice of recording energy next to latency, errors and cost for every AI request and agent step, so you can see which feature, model or workflow uses the energy and whether a change helped. It extends the tracing and metrics you already run rather than replacing them.

Two ideas make it work. Tokens and calls are the leading indicator: cheap, exact and available for every call, including hosted APIs. And every energy figure carries a method label: measured (a meter on hardware you control), attributed (a measured node total shared between requests) or estimated (a model from tokens, as for a hosted API). Boundaries and uncertainty are covered in how to measure AI energy; this guide is about wiring energy into production telemetry.

What should I record for each request or agent step?

Record what the call did, how long it took, what it ran on and where, and how it ended, as low-cardinality metrics plus a trace span per call. Leave out the content.

Field Example attribute Why it matters for energy
Operation and provider gen_ai.operation.name, gen_ai.provider.name Separates chat, embeddings, tool runs and retrieval
Model requested and served gen_ai.request.model, gen_ai.response.model Model size is the largest single factor; routers change it per call
Tokens in and out gen_ai.usage.input_tokens, gen_ai.usage.output_tokens Energy rises with tokens processed and generated
Cached and reasoning tokens gen_ai.usage.cache_read.input_tokens, gen_ai.usage.reasoning.output_tokens Cache reads avoid work; hidden reasoning adds it
Output cap gen_ai.request.max_tokens Shows whether limits are set at all
Latency gen_ai.client.inference.duration, time to first chunk Busy time is an attribution key; slow calls hold hardware
Outcome error.type; your own task outcome Failed and retried calls cost energy and deliver nothing
Retries and response-cache hits your own counters Retries multiply cost; your own cache hits avoid the call entirely
Agent and tool steps gen_ai.agent.name, gen_ai.tool.name; inference and tool calls per agent run Agent loops are the usual source of runaway token use
Hardware pool and utilisation your pool label; GPU and CPU utilisation from the node Explains energy per token; idle pools show up here
Energy your own metric in joules, with method measured, attributed or estimated The thing you want to manage
Region and time cloud.region, timestamp Needed to apply grid carbon intensity

The names in the second column come from the OpenTelemetry GenAI semantic conventions (see below), except where it says "your own". Keep request IDs, user IDs and conversation IDs on spans only, never as metric labels.

How do I get from node power to a single request?

Measure energy for a node or device over a short window, then share it between the work done in that window by a stated rule, and check that the shares add back up to the measured total. There is no per-request power meter.

The common approach, and the one Kepler uses for CPUs, splits each window's energy into two parts:

  • Idle energy: the baseline the node draws regardless of work.
  • Active energy: the rest, shared between workloads in proportion to their resource use. Kepler's rule is workload power = (workload CPU time ÷ node CPU time) × active power, for each interval.

For model serving you can carry the same idea down to requests:

  1. Per device, per window (say 15 to 60 seconds), take measured energy from RAPL, the NVML energy counter or a node-level reading.
  2. Subtract idle, measured on the same node with the model loaded and no traffic.
  3. Share active energy between requests in proportion to a weight: GPU or CPU busy time where your server reports it, or a token weight. Fernandez and colleagues found decoding more energy-intensive per token than prefill, so if you weight by tokens, give output tokens a larger weight, fitted from your own benchmark runs (see how to benchmark CPU versus GPU inference).
  4. Report idle energy as its own line per pool, or share it out pro rata and say so. Hiding it inside per-request figures makes a half-empty GPU pool look efficient.
  5. Reconcile. The sum of attributed energy plus idle must equal the measured total for the window. Alert when it doesn't.

Know the limits. Kepler's own guide lists them: two processes with identical CPU time can draw different power because of sleep states, frequency scaling, vector instructions and memory-bound stalls, and bursty work is under-attributed against steady work in the same window. It recommends the method for trends and relative comparisons rather than absolute budgeting decisions. For NVIDIA GPUs, Kepler's experimental support shares active device power between processes by streaming-multiprocessor utilisation, using an NVML power reading whose averaging window depends on the GPU model.

For calls to hosted APIs you cannot meter at all; estimate from tokens and label the result estimated. See how to estimate the energy of AI API calls.

What do the OpenTelemetry GenAI conventions cover?

They define standard span and metric names for model calls, agents, tools and retrieval, including token counts, but nothing for energy, and they are still at Development status. Use them for everything they cover, and add your own namespaced energy metric.

The state of play, checked on 26 November 2026:

  • New home, first release. The GenAI conventions moved out of the main OpenTelemetry semantic conventions into their own repository and published their first standalone release, v0.1.0, on 21 November 2026. The old pages on opentelemetry.io now say the content has moved.
  • Development status. The conventions, and the GenAI attributes and metrics in them, are marked Development, and v0.1.0 lists breaking changes from the previous release. For example, it replaced the gen_ai.client.token.usage histogram with separate gen_ai.client.inference.operation.input_tokens and ...output_tokens histograms, and moved inference timing from gen_ai.client.operation.duration to gen_ai.client.inference.duration. Pin the version you implement and expect renames.
  • Inference spans are named {gen_ai.operation.name} {gen_ai.request.model} (for example chat small-model) and carry the model, provider and gen_ai.usage.* token attributes, including cache reads and writes and reasoning tokens.
  • Agent and tool spans. An in-process agent run is an invoke_agent {gen_ai.agent.name} span of kind INTERNAL; each tool run is an execute_tool {gen_ai.tool.name} span. Metrics include gen_ai.invoke_agent.inference_calls and gen_ai.invoke_agent.tool_calls, the number of model and tool calls per agent run, which are good early warnings of loops.
  • Content is opt-in. Prompts, responses, system instructions and tool definitions (gen_ai.input.messages, gen_ai.output.messages and others) are Opt-In attributes, and the conventions warn that they are likely to contain sensitive information, including personal data.
  • Hardware energy exists elsewhere. OpenTelemetry's hardware conventions define hw.energy, a counter in joules, and hw.power, a gauge in watts, also at Development status, and recommend reporting hw.energy instead of hw.power where possible. Use them for node and device telemetry you collect yourself.

Where do Prometheus, Grafana and Kepler fit?

Prometheus stores the time series, Grafana or a similar tool draws the dashboards, and exporters such as Kepler, NVIDIA's DCGM exporter and your inference server supply power and serving metrics. Application metrics from OpenTelemetry go into the same store.

  • Export joules, not watts. Prometheus's naming guide lists joules as the base unit for energy and advises exporting a counter of joules, so that rate(joules[5m]) gives power in watts. Counters survive scrape gaps; gauges of instantaneous watts do not.
  • Mind the names. Under OpenTelemetry's Prometheus compatibility rules, a counter in unit J gains a _joules suffix and a _total suffix, so example.inference.energy appears as example_inference_energy_joules_total.
  • Mind cardinality. Prometheus warns that every label combination is a new time series and that labels must not hold unbounded values such as user IDs or email addresses.
  • Kepler for Kubernetes. Kepler is a CNCF Sandbox project that exports energy at node, pod, container, process and virtual-machine level to Prometheus. Since its 0.10 rewrite, metrics include kepler_node_cpu_joules_total, kepler_pod_cpu_joules_total and kepler_pod_gpu_joules_total. CPU metrics carry a zone label (package, core, uncore, dram, psys); zones overlap, so filter on one. DRAM appears only where the hardware exposes it, which many client CPUs, AMD processors and virtual machines do not. GPU monitoring, and platform power read from the server's management controller through Redfish, are experimental and off by default.
  • GPU exporters. NVIDIA's DCGM exporter publishes, among its defaults, DCGM_FI_DEV_GPU_ENERGY_JOULES_TOTAL (energy since the driver was reloaded) and DCGM_FI_DEV_BOARD_POWER_WATTS in version 4.9.0. Metric names have changed between releases, so check the counters file for the version you deploy.
  • Serving metrics. Inference servers expose their own counters; llama.cpp's server, for example, publishes llamacpp:prompt_tokens_total and llamacpp:tokens_predicted_total on a Prometheus endpoint when started with --metrics. Measured node energy divided by server-side tokens is a useful check on your attribution.

What does a worked architecture look like?

Four layers: the application emits spans and metrics per call and per task; node exporters measure energy; a small job attributes and reconciles; dashboards join energy with grid carbon intensity. You can add them one service at a time.

  1. Application. Each model call is a client span with GenAI attributes. Each user-facing task is a parent invoke_agent span. The app records token and duration histograms, a task counter by outcome, and an energy counter with a method label: estimated from calibrated per-token coefficients, or attributed when the reconciliation job supplies figures.
  2. Nodes. Kepler on Kubernetes nodes (CPU and, if enabled, GPU), the DCGM exporter on GPU nodes, and a BMC or smart-meter reading where you can get one for a check at the wall.
  3. Attribution job. Every window, it reads node and pod energy, subtracts idle, shares active energy by busy time or tokens using the serving metrics, writes attributed energy per service and model, and alerts if the parts and the total disagree.
  4. Storage and dashboards. Metrics kept for months at low resolution; traces kept for days; grid carbon intensity stored as a gauge per region.

Example metric names

Metric (as stored in Prometheus) Type Source
gen_ai_client_inference_duration_seconds Histogram Application (OpenTelemetry GenAI convention)
gen_ai_client_inference_operation_input_tokens, ..._output_tokens Histogram Application (convention)
example_inference_energy_joules_total{example_energy_method=...} Counter Application (your own name)
example_task_completed_total{example_outcome="success"} Counter Application (your own name)
kepler_pod_cpu_joules_total{zone="package"}, kepler_pod_gpu_joules_total Counter Kepler
DCGM_FI_DEV_GPU_ENERGY_JOULES_TOTAL Counter DCGM exporter
grid_carbon_intensity_gco2_per_kwh{cloud_region=...} Gauge Your own exporter

Example code

The snippet below wraps an OpenAI-compatible chat call in an OpenTelemetry span, records the convention's token and duration metrics, and adds an energy counter. It is an illustration to adapt: the energy figure is only as good as the per-token coefficients you fit from your own measurements, it does not yet treat cached input differently, and the example.* names should become your organisation's own namespace.

"""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"]})

Used like this:

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

# 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

How do I set energy budgets like SLOs?

Choose one indicator, energy per successful task for each feature, set a budget from your own baseline, and treat a sustained rise like a latency regression. Keep the total in view too.

  • The indicator. Energy per successful task (all energy, including failed attempts and retries, divided by tasks that passed their check) over a rolling window such as 28 days. Where you only have tokens, use tokens per successful task; it moves first.
  • The budget. Set it from a measured baseline, not a guess, and tighten it when a change such as a smaller model or a cache earns headroom.
  • Alerts. Alert on a sustained rise over the baseline, on a jump in model or tool calls per agent run (a loop), on idle share in a GPU pool, and on reconciliation failures.
  • Gate changes. Fail the CI build when a fixed task exceeds its token or energy budget; see energy testing in CI.
  • Watch the total. Falling energy per task with rising total energy is the rebound effect. Show both on the same dashboard; see how to set targets for AI energy and emissions.

How do I trace agents and distributed workflows?

Give every user-facing task one trace, propagate it across services and queues, and roll energy up from the model-call spans to the task. Agents make per-call numbers misleading; per-task numbers are what users experience.

  • Propagate context. OpenTelemetry SDKs propagate trace context between services, by default using the W3C Trace Context and Baggage formats. Carry it through message queues and background jobs as well as HTTP, or multi-service tasks will break into unrelated traces.
  • Structure the trace. One invoke_agent span per task or sub-agent, an inference span per model call, an execute_tool span per tool call. Retrieval and embedding calls get their own spans too.
  • Roll up from metrics, not sampled traces. If you sample traces, sampled traces cannot give you totals. Record energy and tokens as metrics on every call, and use traces to explain individual expensive tasks.
  • Watch the loop indicators. The distribution of model and tool calls per agent run, and of tokens per task, shows runaway agents before the bill does. See how to stop AI agents wasting tokens and agentic AI and token waste.
  • Count retries and cache hits explicitly. A retry is a second call; a response-cache hit is a call avoided. See how to cache LLM calls.

How do I add carbon?

Multiply energy by grid carbon intensity for the region and hour, at query time, and keep energy as the primary figure. Carbon depends on the grid; energy depends on your code.

The Green Software Foundation's Software Carbon Intensity specification expresses the score as SCI = ((E × I) + M) per R, where E is energy, I is region-specific carbon intensity, M is embodied emissions and R is the functional unit, and it excludes market-based measures. In practice:

  • Run a small exporter that publishes carbon intensity per region as a gauge. In Great Britain, the Carbon Intensity API gives regional forecasts and estimates in gCO2/kWh; Electricity Maps brings together historical, live and forecast grid data for many other countries. See how to find grid carbon intensity data.
  • Tag energy with cloud.region (or your data centre's location) and join in the query, as in the example above.
  • Add embodied emissions separately, if they are in your boundary; see how to calculate an SCI score for an AI feature.

What about privacy and retention?

Log counts, not content, and keep detailed traces for less time than aggregate metrics. Energy needs token counts, models, timings and hardware, none of which requires the prompt.

  • Content off by default. The OpenTelemetry conventions make prompt and response attributes Opt-In and warn that they are likely to contain personal data. Leave them off in production. If you must capture content for debugging, store it separately under access control and reference it by URI, as the conventions' *_ref attributes allow, with a short expiry.
  • Minimise. Article 5 of the EU GDPR, and of the UK GDPR, requires personal data to be limited to what is necessary and kept no longer than necessary. Hash or drop user identifiers in spans unless you need them.
  • Tiered retention. Keep aggregate metrics, which hold no personal data if labels are chosen well, for long enough to see trends and seasonality; keep traces for days or weeks.
  • Telemetry has a footprint too. Sample traces, aggregate metrics, and drop labels you never query.

What to do next

  1. Add the OpenTelemetry GenAI attributes and token metrics to every model call, pinned to v0.1.0, with prompt capture off.
  2. Add a task span and a task-outcome counter, and chart energy (or tokens) per successful task for one feature.
  3. Install Kepler, or read RAPL, NVML and DCGM on your inference nodes, and record idle power per pool.
  4. Fit per-token energy coefficients from a benchmark run (see CPU versus GPU inference), and reconcile estimates with measured node energy weekly.
  5. Add a carbon-intensity gauge per region and a carbon panel next to the energy panel.
  6. Set a budget from the baseline, alert on regressions, and add an energy test to CI.

Frequently asked questions

Is there an OpenTelemetry standard for AI energy?

Not yet for model calls. The OpenTelemetry GenAI semantic conventions cover spans and metrics for inference, agents and tools, including token counts, but define no energy attribute. OpenTelemetry's hardware conventions define hw.energy in joules for components. Use your own namespaced metric for energy per call until a convention exists.

How do I get energy per request when I can only meter the whole server?

Attribute it. Split the energy measured over a time window between the requests served in that window, in proportion to their busy time or tokens, and report idle energy separately or share it out by a stated rule. Check that the attributed parts add up to the measured total.

Should I log prompts to work out energy?

No. Energy depends on token counts, model, hardware and timing, not on the words. The OpenTelemetry conventions make prompt and response content opt-in and warn that it is likely to contain personal data. Log counts, not content.

What is Kepler?

Kepler (Kubernetes-based Efficient Power Level Exporter) is a CNCF Sandbox project that exports energy and power metrics for Kubernetes nodes, pods and containers to Prometheus. It reads hardware counters such as RAPL and attributes active power to workloads by CPU time.

How do I turn energy into carbon on a dashboard?

Multiply energy by the grid carbon intensity for the region and hour it was used, at query time rather than in the application. Sources include the GB Carbon Intensity API for Great Britain and Electricity Maps elsewhere. Keep energy as the primary metric, because carbon changes with the grid.

Sources

  1. OpenTelemetry GenAI semantic conventions (repository and v0.1.0 changelog), OpenTelemetry (2026)
  2. Semantic conventions for generative AI client inference (v0.1.0), OpenTelemetry (2026)
  3. Semantic conventions for generative AI agent spans (v0.1.0), OpenTelemetry (2026)
  4. Semantic conventions for generative AI metrics (v0.1.0), OpenTelemetry (2026)
  5. Semantic conventions for hardware metrics (hw.energy, hw.power), OpenTelemetry (2026)
  6. Prometheus and OpenMetrics compatibility, OpenTelemetry specification (2026)
  7. SDK environment variables (OTEL_PROPAGATORS), OpenTelemetry specification (2026)
  8. Metric and label naming, Prometheus documentation (2026)
  9. Kepler: Kubernetes-based Efficient Power Level Exporter, Kepler project, CNCF (2026)
  10. Kepler metrics (v0.14.0), Kepler project, CNCF (2026)
  11. Kepler power attribution guide (v0.14.0), Kepler project, CNCF (2026)
  12. Kepler configuration (v0.14.0): experimental GPU and Redfish options, Kepler project, CNCF (2026)
  13. DCGM exporter default counters (4.9.0), NVIDIA (2026)
  14. NVML API reference: device queries, NVIDIA (2026)
  15. llama.cpp HTTP server (/metrics), llama.cpp project (2026)
  16. Energy considerations of large language model inference and efficiency optimizations, Fernandez et al. (arXiv 2504.17674) (2025)
  17. Software Carbon Intensity (SCI) specification, Green Software Foundation (2024)
  18. Carbon Intensity API, National Energy System Operator (2026)
  19. Electricity Maps, Electricity Maps (2026)
  20. General Data Protection Regulation, Article 5, Regulation (EU) 2016/679, via gdpr-info.eu (2016)
  21. A guide to the data protection principles (UK GDPR), Information Commissioner's Office (2026)

Join us

Help cut AI's impact on the planet

Get new guides, funding calls and directory listings by email, about once a month. Or add your product, course, PhD or research to the directories.

No tracking. Unsubscribe in one click. Other ways to join · Privacy