Skip to main content

saef

Python access to SAEF, the SOMA AI Emission Factors. SAEF is a versioned dataset of estimated carbon and water factors for AI inference, by model class and region, built for Scope 3 Category 1 reporting under the GHG Protocol and CSRD. This package bundles the CSV files and gives you a small API and command line on top of them. It has no dependencies beyond the standard library.

Use it to track the estimated carbon and water footprint of OpenAI, Anthropic and other LLM API calls from the token usage each response already reports, with a LiteLLM callback, a LangChain handler, an MCP server, or one function call on a response object. The method is peer reviewed, published in Sustainable Production and Consumption 70 (2026) 320-347 (https://doi.org/10.1016/j.spc.2026.11.003).

Every number comes with the file, column and row it was read from, so you can trace an estimate back to the dataset.

Install

pip install saef

For pandas users, pip install "saef[pandas]" adds the optional extra. The framework integrations below use saef[litellm], saef[langchain], saef[llamaindex] and saef[haystack].

Track OpenAI and Anthropic API calls

from saef.integrations.openai import estimate_from_response

resp = client.chat.completions.create(model="gpt-4o-mini", messages=[...])  # or client.messages.create(...) with Anthropic
e = estimate_from_response(resp, region="eu-west-1")
print(e.kg_co2e, e.kg_co2e_high_case, e.water_ml)  # kg CO2e central and high case, water in mL

No SDK import is needed, so the same call works on OpenAI Chat Completions, OpenAI Responses and Anthropic Messages objects, or the same shapes as dicts. Running totals per model and a JSON lines log are covered under Integrations below.

Example

import saef

print(saef.model_class_for("gpt-4o"))             # B
print(saef.factor("B", "eu-west-1")["kg_co2e_per_1m_billed_tokens"])

r = saef.estimate(tokens=1_000_000, model="gpt-4o-mini", region="eu-west-1")
print(r.kg_co2e, r.kg_co2e_high_case)             # central and conservative high case, kg CO2e
print(r.water_ml)                                 # mL, or None where the region has no water factor
for s in r.provenance[:3]:
    print(s["file"], s["line"], s["column"])      # the file, line and column behind each number
print(len(saef.regions()), saef.__version__, saef.DATASET_VERSION)  # 143 cloud regions, 3.7.0, 3.3.0
print(saef.citation())

Command line:

saef estimate --tokens 1000000 --model gpt-4o-mini --region eu-west-1
saef estimate --output-tokens 2e6 --input-tokens 10e6 --model gpt-4o --provider azure --region swedencentral
saef factor --model-class B --region us-east-1
saef regions --provider aws
saef cite

Integrations

The core package has no dependencies. The integrations below estimate carbon and water for each call from the token usage your framework already reports. The region comes from the region argument, then from the SAEF_REGION environment variable, then falls back to the global average. All of them keep running totals and can append one JSON line per call with log_path=.

LiteLLM, installed with pip install "saef[litellm]". The estimate is also attached to response._hidden_params["saef"].

import time
import litellm
from saef.integrations.litellm import SaefLogger

logger = SaefLogger(region="eu-west-1")
litellm.callbacks = [logger]
resp = litellm.completion(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}], mock_response="Hi there")
time.sleep(1)  # LiteLLM runs success callbacks in a background thread
t = logger.totals()
print(t["calls"], t["input_tokens"], t["output_tokens"])
print(f"{t['kg_co2e']:.3e} kg CO2e, {t['kg_co2e_high_case']:.3e} high case, {t['water_ml']:.4f} mL")
1 10 20
3.905e-07 kg CO2e, 6.250e-07 high case, 0.0018 mL

LangChain, installed with pip install "saef[langchain]". This example uses a fake chat model so it runs offline. With a real model you pass the same handler in callbacks.

from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from saef.integrations.langchain import SaefCallbackHandler

handler = SaefCallbackHandler(region="eu-west-1")
reply = AIMessage(
    content="Hi there",
    response_metadata={"model_name": "gpt-4o"},
    usage_metadata={"input_tokens": 1200, "output_tokens": 300, "total_tokens": 1500, "input_token_details": {"cache_read": 800}},
)
llm = GenericFakeChatModel(messages=iter([reply]))
llm.invoke("Hello", config={"callbacks": [handler]})
t = handler.totals()
print(t["calls"], t["input_tokens"], t["cached_input_tokens"], t["output_tokens"])
print(f"{t['kg_co2e']:.3e} kg CO2e, {t['kg_co2e_high_case']:.3e} high case")
1 400 800 300
2.894e-05 kg CO2e, 4.433e-05 high case

LangChain v1 agents can use middleware instead of a callback. SaefMiddleware hooks wrap_model_call and awrap_model_call, records one estimate per model call, and with attach=True also writes the estimate to AIMessage.response_metadata["saef"]. It needs the langchain package, which the langchain extra installs. The example again uses a fake chat model.

from langchain.agents import create_agent
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langchain_core.messages import AIMessage
from saef.integrations.langchain import SaefMiddleware

reply = AIMessage(
    content="Hi there",
    response_metadata={"model_name": "gpt-4o"},
    usage_metadata={"input_tokens": 1200, "output_tokens": 300, "total_tokens": 1500, "input_token_details": {"cache_read": 800}},
)
llm = GenericFakeChatModel(messages=iter([reply]))
mw = SaefMiddleware(region="eu-west-1", attach=True)
agent = create_agent(llm, tools=[], middleware=[mw])
out = agent.invoke({"messages": [("user", "Hello")]})
t = mw.totals()
print(t["calls"], t["input_tokens"], t["cached_input_tokens"], t["output_tokens"])
print(f"{t['kg_co2e']:.3e} kg CO2e, {t['kg_co2e_high_case']:.3e} high case")
print(out["messages"][-1].response_metadata["saef"]["kg_co2e"])
1 400 800 300
2.894e-05 kg CO2e, 4.433e-05 high case
2.894105237117252e-05

LlamaIndex, installed with pip install "saef[llamaindex]". SaefEventHandler listens to LlamaIndex's instrumentation events and records one estimate per finished chat or completion call, reading token usage from the provider's raw response. The model name comes from the raw response, then from the call's start event. Streaming calls count only if the last chunk carries usage. This example uses a fake LLM so it runs offline. With a real LLM you register the handler once and call it as usual.

from llama_index.core.base.llms.types import ChatMessage, ChatResponse, LLMMetadata
from llama_index.core.llms import CustomLLM
from llama_index.core.llms.callbacks import llm_chat_callback
from saef.integrations.llamaindex import SaefEventHandler


class FakeLLM(CustomLLM):
    @property
    def metadata(self):
        return LLMMetadata(model_name="gpt-4o")

    @llm_chat_callback()
    def chat(self, messages, **kwargs):
        raw = {"model": "gpt-4o", "usage": {"prompt_tokens": 1200, "completion_tokens": 300, "prompt_tokens_details": {"cached_tokens": 800}}}
        return ChatResponse(message=ChatMessage(role="assistant", content="Hi there"), raw=raw)

    def complete(self, prompt, formatted=False, **kwargs): ...
    def stream_complete(self, prompt, formatted=False, **kwargs): ...


handler = SaefEventHandler(region="eu-west-1").register()
FakeLLM().chat([ChatMessage(role="user", content="Hello")])
t = handler.totals()
print(t["calls"], t["input_tokens"], t["cached_input_tokens"], t["output_tokens"])
print(f"{t['kg_co2e']:.3e} kg CO2e, {t['kg_co2e_high_case']:.3e} high case")
1 400 800 300
2.894e-05 kg CO2e, 4.433e-05 high case

Haystack 2.x, installed with pip install "saef[haystack]". SaefTracker is a pass-through component. Connect replies from a ChatGenerator, which carries the model and usage in each reply's meta. For a text Generator such as OpenAIGenerator, also connect its meta output to meta. It outputs the replies unchanged plus saef, one estimate dict per reply with a model name and token usage, and keeps running totals. This example uses a fake generator so it runs offline. With a real one you add, for example, OpenAIChatGenerator in its place.

from typing import List
from haystack import Pipeline, component
from haystack.dataclasses import ChatMessage
from saef.integrations.haystack import SaefTracker


@component
class FakeChatGenerator:
    @component.output_types(replies=List[ChatMessage])
    def run(self, prompt: str):
        meta = {"model": "gpt-4o", "usage": {"prompt_tokens": 1200, "completion_tokens": 300, "prompt_tokens_details": {"cached_tokens": 800}}}
        return {"replies": [ChatMessage.from_assistant("Hi there", meta=meta)]}


pipe = Pipeline()
pipe.add_component("llm", FakeChatGenerator())
pipe.add_component("saef", SaefTracker(region="eu-west-1"))
pipe.connect("llm.replies", "saef.replies")
result = pipe.run({"llm": {"prompt": "Hello"}})
print(result["saef"]["saef"][0]["kg_co2e"])
t = pipe.get_component("saef").totals()
print(t["calls"], t["input_tokens"], t["cached_input_tokens"], t["output_tokens"])
print(f"{t['kg_co2e']:.3e} kg CO2e, {t['kg_co2e_high_case']:.3e} high case")
2.894105237117252e-05
1 400 800 300
2.894e-05 kg CO2e, 4.433e-05 high case

All figures are estimates from token counts, not measurements.

Response objects, with no extra install and no SDK import. estimate_from_response reads OpenAI Chat Completions, OpenAI Responses and Anthropic Messages objects, or the same shapes as dicts. Cache reads get the cache credit and cache writes count as ordinary input.

from types import SimpleNamespace
from saef.integrations.openai import estimate_from_response

resp = SimpleNamespace(
    type="message", model="claude-sonnet-4-5",
    usage=SimpleNamespace(input_tokens=200, output_tokens=150, cache_read_input_tokens=1800, cache_creation_input_tokens=0),
)
e = estimate_from_response(resp, region="eu-west-1")
print(e.model_class, f"{e.kg_co2e:.3e}", f"{e.kg_co2e_high_case:.3e}", f"{e.water_ml:.4f}")
B 2.231e-05 3.235e-05 0.0785

Every figure is an estimate. Models the dataset treats as out of scope, such as embeddings, are skipped and counted in totals()["skipped_calls"].

Cost and carbon side by side

Cost and carbon side by side. If your team optimises AI cost as well as carbon, saef can put both on the same record. saef does not price tokens and has no price table. It takes the cost the framework already reports. With LiteLLM that is response_cost, in USD, and the logger stores it as cost and cost_currency next to the estimate. Calls where LiteLLM reports no cost simply have no cost fields.

import time
import litellm
from saef.integrations.litellm import SaefLogger

logger = SaefLogger(region="eu-west-1")
litellm.callbacks = [logger]
resp = litellm.completion(model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello"}], mock_response="Hi there")
time.sleep(1)
rec = resp._hidden_params["saef"]
print(rec["kg_co2e"], rec["cost"], rec["cost_currency"])
t = logger.totals()
print(f"{t['cost']:.6f} {t['cost_currency']}, {t['g_co2e_per_usd']:.4f} g CO2e per USD")

g_co2e_per_usd is the central estimate in grams divided by the cost, over the calls that have a cost, and is None when the total cost is zero. To total records you logged or stored yourself, use saef.summarize(records), which accepts the per-call dicts or Estimate objects and returns the same cost fields.

MCP server

SAEF ships an MCP server so an AI agent can estimate the carbon, energy and water of AI usage on request. It runs locally over stdio and needs the optional mcp extra. The core package stays dependency-free.

pip install "saef[mcp]"

Claude Code.

claude mcp add saef -- saef-mcp

Claude Desktop, in claude_desktop_config.json.

{
  "mcpServers": {
    "saef": { "command": "saef-mcp" }
  }
}

Cursor, in .cursor/mcp.json.

{
  "mcpServers": {
    "saef": { "command": "saef-mcp" }
  }
}

If saef-mcp is not on your PATH, use uvx --from "saef[mcp]" saef-mcp as the command instead.

Tools.

  • estimate_footprint(tokens, model, region="global") returns carbon in kg and g CO2e with a central and a high case, facility energy in Wh, water in mL where the region has a water factor, the model class, the region used, the dataset version and a provenance trail.
  • estimate_chat_usage(messages, model, region="global") returns the same for chat exchanges, using the dataset's short-chat default of 1,210 tokens per exchange (928 input, 282 output).
  • model_class(model) returns the class letter (A small, B mid-size, C large) and a description.
  • list_regions() returns the accepted region codes, with names for cloud regions and countries.
  • compare_regions(tokens, model, regions) returns carbon and water per region, sorted from lowest to highest carbon.

The server also exposes the resource saef://about with the licence, DOI and method paper. Every figure is an estimate, not a measurement.

Example prompt, "Using SAEF, what is the carbon and water footprint of 2 million gpt-4o tokens a month in eu-north-1 compared with us-east-1?"

What the numbers are

The factors follow the v3 lifecycle boundary. An estimate has four terms: electricity, embodied hardware and data-centre construction (charged on effective tokens) and amortised training (charged on billed tokens).

  • Effective tokens are output tokens plus weighted input tokens, divided by a reference-mix normaliser. Pass tokens for a billed total, which applies the default input share of 85% and no cache credit. Pass output_tokens, input_tokens and cached_input_tokens when your billing export gives the split.
  • Never multiply a billed token count by a per-effective-token footprint yourself. Use estimate, or the kg_co2e_per_1m_billed_tokens value from factor.
  • A model maps to class A, B or C through 220 identifier patterns, including AWS Bedrock, Azure and Vertex AI spellings. Closed models are class proxies by pricing tier, and the result says so in warnings. An unmapped identifier is assigned the conservative class C and flagged. Embeddings, image, audio and video models are out of scope and raise an error.
  • region can be a cloud region id (143 AWS, Azure and Google Cloud regions), an ISO-3 country code (210 countries and economies), a US eGRID subregion, eu-27, or None for the global average. A region that matches nothing raises saef.SaefError with suggestions.
  • Water covers 17 regions, under two hydropower conventions (water_ml and water_ml_excl_hydro). Elsewhere water_ml is None, by design.
  • kg_co2e_high_case is a conservative bound. The development line is reported separately and is never added to kg_co2e.

Estimates, not measurements

These figures are modelled estimates built from published benchmarks, grid averages and lifecycle studies. They are not measurements of any provider's infrastructure. The tables carry six significant figures as arithmetic, but the inputs support about two. Report the central value with the high case, and read the methodology before quoting them.

This package bundles the SAEF v3.3.0 tables (same values as v3.2.0, licence change only; dataset date 2026-10-02 for the values) and covers the H100 central case. Reserved accelerator-hour factors, the B200 sensitivity and the Tier 2b seat-based estimates in the full deposit are not exposed by this API.

Licence

The dataset is licensed under the SOMA AI Emission Factors Data Licence 1.0 (Non-Commercial), see LICENSE, from dataset v3.3.0. The Python code is licensed under PolyForm Noncommercial 1.0.0, see LICENSE-CODE. Free for personal use, academic and non-profit research, journalism, charities and government. Any use by a company or freelancer, including internal ESG/CSRD reporting, needs a commercial licence: https://somaai.earth/licensing (guillermollopis@somaai.earth). Versions up to v3.2.0 (package 3.6.0 and earlier) remain under CC BY 4.0 (data) and MIT (code). Attribution for the data is required, see the citation below.

Citation

Dataset (concept DOI, always the latest version): https://doi.org/10.5281/zenodo.20443585

@misc{llopis2026somafactors,
  author    = {Llopis-Garcia, Guillermo},
  title     = {{SOMA AI Emission Factors (SAEF)}},
  year      = {2026},
  publisher = {Zenodo},
  doi       = {10.5281/zenodo.20443585}
}

Method paper: Llopis-Garcia, G. (2026), Accounting for Purchased Artificial Intelligence Inference in Corporate Greenhouse Gas Inventories, a Token-Based Method. Sustainable Production and Consumption 70 (2026) 320-347. https://doi.org/10.1016/j.spc.2026.11.003

mcp-name: io.github.guillermollopis/saef

Metadata

Release files for saef 3.7.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for saef 3.7.0
File Size Uploaded Provenance Actions
saef-3.7.0.tar.gz 220.0 kB With provenance Details for saef-3.7.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for saef 3.7.0
File Interpreter ABI Platform Actions
saef-3.7.0-py3-none-any.whl Python 3 none any Details for saef-3.7.0-py3-none-any.whl

Total release size: 347.8 kB

Release files / saef-3.7.0.tar.gz

Download URL saef-3.7.0.tar.gz
Size 220.0 kB
Tags Source
SHA-256 checksum
How to use checksums
1ace39cbc15026044f374ebcce3b6b7c236b2e17bf348a2024a5118a5c831e5c
BLAKE2b-256 checksum
How to use checksums
a9bf855e89598eff7b769b3edc24c301255749a404d63f915f802f5f500d8887
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Release files / saef-3.7.0-py3-none-any.whl

Download URL saef-3.7.0-py3-none-any.whl
Size 127.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ad61430b1ea52b64bf8655918bc5dbe0bc0e1b4c2ffd0ad1df2544759d969c5f
BLAKE2b-256 checksum
How to use checksums
81ee232ad07da700ef1b2606a264ada31e67d42f5cbe30a6183243cfbf44384f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Security for saef 3.7.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for saef-3.7.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page