Back to Browse

Soma Ai Emission Factors MCP Server

Developer ToolsLow Risk10.0MCP RegistryLocal
Free

Server data from the Official MCP Registry

Estimate carbon, energy and water of AI inference by model class and cloud region (SAEF).

About

Estimate carbon, energy and water of AI inference by model class and cloud region (SAEF).

Security Report

10.0
Low Risk10.0Low Risk

Valid MCP server (1 strong, 4 medium validity signals). No known CVEs in dependencies. Package registry verified. Imported from the Official MCP Registry.

7 files analyzed · 1 issue found

Security scores are indicators to help you make informed decisions, not guarantees. Always review permissions before connecting any MCP server.

Permissions Required

This plugin requests these system permissions. Most are normal for its category.

env_vars

Check that this permission is expected for this type of plugin.

How to Install

Add this to your MCP configuration file:

{
  "mcpServers": {
    "saef": {
      "command": "uvx",
      "args": [
        "saef==3.10.0"
      ]
    }
  }
}

Some servers take additional arguments. See the repository for details.

Documentation

View on GitHub

From the project's GitHub README.

SOMA AI Emission Factors (SAEF)

DOI Paper DOI arXiv License: Non-Commercial SAEF MCP server on Glama

SOMA AI Emission Factors (SAEF) is a versioned dataset of estimated carbon and water factors for AI inference, by model class and by region, built for Scope 3 Category 1 reporting under the GHG Protocol and CSRD. It covers 210 countries and economies, 27 US eGRID subregions and 143 AWS, Azure and Google Cloud regions. Every factor traces to a file and a source, and the calculator returns the file, line and column behind each number. Published by SOMA AI, Barcelona, under a non-commercial licence, see the Licence section. The method is published in Sustainable Production and Consumption 70 (2026) 320-347, https://doi.org/10.1016/j.spc.2026.11.003 (free preprint arXiv 2606.10660).

This repository holds the v3.6.0 tables (lifecycle boundary; text per-token factor values dated 2026-10-02 and identical to v3.2.0 and v3.3.0; v3.6.0 changes only the Tier 2b reasoning multiplier of the full deposit, from 25 to 3, which the Python package does not use; v3.6.0 version DOI 10.5281/zenodo.24653736; v3.5.0 version DOI 10.5281/zenodo.24596349; v3.4.0 (10.5281/zenodo.24591290) adds embeddings, reranking, moderation, image generation and transcription, and v3.5.0 adds text-to-speech, realtime voice and video) and the source of the saef Python package. The complete deposit, with the reference calculator, the generator scripts and the supplementary documents, is on Zenodo.

How can I measure the environmental impact of the AI I use?

AI that runs on hardware you control can be metered, with a power meter or with tools such as CodeCarbon that read hardware energy counters. AI you buy as a service (ChatGPT, Copilot, Claude, Gemini, API calls to a provider) cannot be metered by the customer, because providers do not publish energy for the requests you send. It can only be estimated from usage (tokens, messages or spend), an energy factor for the model size and the grid where it runs. That estimate is what SAEF is for.

Your AI useFitsWhat you get
Training or inference on your own GPUsCodeCarbon, Green AlgorithmsEstimated energy and emissions of your own hardware
API calls made from your codesaef (this package, LiteLLM, LangChain, LlamaIndex and Haystack integrations) or EcoLogitsPer-call estimates
ChatGPT, Copilot or Claude seats across a companySAEF factors applied to seats x messages, or the free SOMA AI calculator (also as a Hugging Face Space)An organisation-wide estimate for Scope 3 category 1
Cloud infrastructure you rentYour cloud provider's carbon dashboardEmissions of your cloud account

Full answer with a worked 250-seat Copilot example and published per-query figures: How can I measure the environmental impact of the AI I use? (Spanish: ¿Cómo puedo medir el impacto ambiental de la IA que uso?). All SAEF figures are estimates, not measurements.

Questions this dataset answers

How can I estimate the carbon footprint of the AI tools my company uses (ChatGPT, Copilot, Claude)?

Count usage per tool, such as seats, messages or tokens, and multiply by a per-query or per-token factor for the model class and the grid region. SAEF (SOMA AI Emission Factors) publishes those factors, and the free SOMA AI calculator applies them to company seats. The result is an estimate with a range, not a meter reading.

How do I calculate CO2e from LLM API token usage?

Divide billed tokens by one million and multiply by the SAEF factor F (kg CO2e per million tokens) for the model class and region: kg CO2e = T_billed / 1e6 x F. This one-line form assumes the dataset's default mix of input and output tokens and gives no cache credit. For a different mix, use the full form on the formula page. For a mid-size model, F is 0.00714 kg per million tokens in EU North (Sweden) and 0.0261 kg in US East (N. Virginia).

Which tool fits which kind of AI use?

CodeCarbon or Green Algorithms fit your own GPUs. EcoLogits or the saef package fit API calls made from code. The SOMA AI calculator or SAEF factors fit company seats. Your cloud provider's carbon dashboard fits infrastructure you rent.

Can CodeCarbon track API calls to OpenAI, Anthropic or Gemini?

No. CodeCarbon reads the power of hardware you run, and its own README points users of remote APIs to EcoLogits. For API-based LLM usage you need an estimate from token counts. EcoLogits does that per call by wrapping the provider SDKs. The saef package does it from the response object or from billing totals (pip install saef, then saef.estimate(...) or estimate_from_response(resp)), with a LiteLLM callback and LangChain middleware. The two draw the boundary differently (SAEF adds amortised training), so pick one and state which.

Where does purchased AI go in a GHG inventory?

Under Scope 3 category 1 (purchased goods and services). Label the figure as an estimate, show a low-to-high band, and name the factor version used, for example SAEF v3.5.0.

Can the energy use of a provider's AI be measured directly?

No. Providers do not publish per-customer energy for the requests you send, so a customer can only estimate it from usage, model size and grid. SAEF is an estimation dataset built on published benchmarks, and its figures are not measurements.

How much electricity does one AI prompt use?

SAEF estimates 0.03 to 0.37 Wh at facility level for a 1,210-token chat exchange, from a small (class A) to a large (class C) model, and 0.099 Wh for a mid-size (class B) model. Published figures for comparison are 0.24 Wh for the median Gemini Apps text prompt (Google, August 2025) and about 0.3 Wh for a GPT-4o query (Epoch AI). Long documents, coding agents and reasoning modes process far more tokens and use far more.

How much water does ChatGPT or another AI chatbot use per prompt?

SAEF estimates 0.15 to 0.94 mL for a mid-size chat exchange, depending on the cloud region, because the region changes the water, not the watt-hours. Google reports 0.26 mL for its median Gemini Apps text prompt. The viral bottle-of-water-per-email figure (about 519 mL, Washington Post and UC Riverside, 2024) counted the water behind the electricity with mid-2024 assumptions. Details on the water page.

How do I measure the carbon footprint of my own AI use, as one person?

Count your messages, pick a model class and apply the grid of the region. With a mid-size model, a reasoning uplift and a US East grid, 20 chat messages a day for a year come to about 0.27 kg CO2e (band 0.14 to 0.63 kg), and about 0.07 kg on a Swedish grid. Coding agents, long documents and image or video generation add much more per request. A step-by-step answer is on How can I measure the environmental impact of the AI I use?

Which AI model has the lowest footprint?

Model size class and serving region decide most of the estimate, more than the brand. Smaller models and low-carbon grids give the lowest carbon per exchange, but low-carbon grids are not always the lowest-water ones. Per-model estimates are on the models compared page.

Cite the dataset as 10.5281/zenodo.20443585.

Install

pip install saef
import saef

saef.model_class_for("gpt-4o")                                   # B
r = saef.estimate(tokens=1_000_000, model="gpt-4o-mini", region="eu-west-1")
r.kg_co2e, r.kg_co2e_high_case, r.water_ml                      # estimates, with provenance in r.provenance
saef estimate --tokens 1000000 --model gpt-4o-mini --region eu-west-1

The package bundles the eleven CSV files below and has no dependencies. It is built from this repository with python scripts/sync_data.py && python -m build.

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

On the LiteLLM proxy, list the ready-made instance in config.yaml. It takes the region from SAEF_REGION and writes one JSON line per call (estimate, call_id, and the cost LiteLLM reports) to the file in SAEF_LOG_PATH.

litellm_settings:
  callbacks: ["saef.integrations.litellm.proxy_handler_instance"]

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

Observability tools: OpenTelemetry (OpenLIT, OpenLLMetry), Langfuse and Helicone. These put CO2e, energy and water next to the token and cost fields your observability tool already shows. Every per-call record from the integrations now also has energy_kwh (facility electricity, including cooling and overhead) and totals() sums it. The numbers are estimates from published benchmarks and grid data, never measurements, and each one is labelled as such.

OpenTelemetry, installed with pip install "saef[otel]". SaefSpanExporter wraps the span exporter you already use and works with any instrumentation that writes the GenAI token attributes: OpenLIT, OpenLLMetry (Traceloop), the opentelemetry-instrumentation-openai-v2 family, or spans you send to Langfuse's OTel endpoint. A finished span cannot be changed in SpanProcessor.on_end, so the exporter copies each span that carries a model and token usage, adds the attributes below, and passes the copy on. Other spans pass through unchanged. This example keeps the spans in memory so it runs offline. In production you wrap OTLPSpanExporter() and use a BatchSpanProcessor.

from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from saef.integrations.otel import SaefSpanExporter

memory = InMemorySpanExporter()  # in production: OTLPSpanExporter() or your current exporter
exporter = SaefSpanExporter(memory, region="eu-west-1")
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(exporter))
tracer = provider.get_tracer("demo")

# What OpenLIT, OpenLLMetry or opentelemetry-instrumentation-openai-v2 record for one chat call
with tracer.start_as_current_span("chat gpt-4o", attributes={
    "gen_ai.operation.name": "chat", "gen_ai.request.model": "gpt-4o",
    "gen_ai.usage.input_tokens": 1200, "gen_ai.usage.output_tokens": 300, "gen_ai.usage.cache_read.input_tokens": 800,
}):
    pass

span, = memory.get_finished_spans()
for k, v in span.attributes.items():
    if k.startswith("saef."):
        print(k, f"{v:.3e}" if isinstance(v, float) else v)
saef.co2e_g 2.894e-02
saef.co2e_g_high 4.433e-02
saef.energy_kwh 8.097e-05
saef.water_l 1.204e-04
saef.region eu-west-1
saef.model_class B
saef.version 3.6.0
saef.estimated True

What is read: gen_ai.response.model, then gen_ai.request.model; gen_ai.usage.input_tokens and gen_ai.usage.output_tokens, or the older gen_ai.usage.prompt_tokens and gen_ai.usage.completion_tokens that older instrumentation versions write; gen_ai.usage.cache_read.input_tokens (or the underscore form gen_ai.usage.cache_read_input_tokens). The conventions count cached tokens inside the input total, so cache reads are subtracted from it to get the cache credit. OpenLIT's Anthropic instrumentation passes Anthropic's own input count through, which excludes the cache, so for those spans cache reads are added instead, and cache writes (gen_ai.usage.cache_creation.input_tokens or cache_write) count as ordinary input. Pass input_includes_cache= a function of the span to override the rule. A span's own cloud.region is used when SAEF knows it, with the cloud taken from gen_ai.provider.name (for example aws.bedrock). The resource's cloud.region is not used, because it says where your service runs, not where the model runs.

attributetypemeaning
saef.co2e_gdoublecentral estimate, grams CO2e, location-based
saef.co2e_g_highdoubleconservative high case, grams CO2e
saef.energy_kwhdoublefacility electricity, kWh
saef.water_ldoublewater consumption, litres (absent where the region has no water factor)
saef.regionstringregion whose grid was applied
saef.model_classstringSAEF model class (A, B, C, or a modality class)
saef.versionstringSAEF dataset version
saef.estimatedbooleanalways true: an estimate, not a measurement

The names sit in a vendor namespace because OpenTelemetry has no energy or carbon attribute for GenAI yet. If one is adopted, saef.energy_kwh and saef.co2e_g map to it with a unit conversion (energy in joules is kWh times 3.6e6). Spans that already carry saef.co2e_g are not estimated again. If your instrumentations put usage on both a parent and a child span, both are counted.

Langfuse, installed with pip install "saef[langfuse]" (Langfuse Python SDK v3 or later). SaefLangfuse creates the numeric scores saef_co2e_g, saef_co2e_g_high, saef_energy_kwh and saef_water_l with create_score on a given trace_id (and optionally observation_id), or with score_current_span on the active observation when no trace id is passed. Each score has a comment and metadata saying it is an estimate, with the region, model class and dataset version. Scores can be charted and filtered in Langfuse, which plain span attributes sent over OTel cannot (Langfuse stores unmapped attributes under metadata.attributes). The client defaults to langfuse.get_client(). This example passes a stand-in client so it runs offline.

from types import SimpleNamespace
from saef.integrations.langfuse import SaefLangfuse


class PrintClient:  # stands in for langfuse.get_client() so the example runs offline
    def create_score(self, **kw):
        print(kw["name"], f"{kw['value']:.3e}", kw["trace_id"], kw["data_type"])


saef_lf = SaefLangfuse(client=PrintClient(), region="eu-west-1")
resp = SimpleNamespace(model="gpt-4o", usage=SimpleNamespace(prompt_tokens=1200, completion_tokens=300, prompt_tokens_details=SimpleNamespace(cached_tokens=800)))
saef_lf.score_response(resp, trace_id="0af7651916cd43dd8448eb211c80319c")
saef_co2e_g 2.894e-02 0af7651916cd43dd8448eb211c80319c NUMERIC
saef_co2e_g_high 4.433e-02 0af7651916cd43dd8448eb211c80319c NUMERIC
saef_energy_kwh 8.097e-05 0af7651916cd43dd8448eb211c80319c NUMERIC
saef_water_l 1.204e-04 0af7651916cd43dd8448eb211c80319c NUMERIC

With a real client, call saef_lf.score_response(resp) inside with get_client().start_as_current_observation(as_type="generation", ...) to score that generation, or saef_lf.score(model, input_tokens, output_tokens, cached_input_tokens, trace_id=...) from token counts.

Helicone, with no extra install (standard library only). Helicone-Property-* headers are sent with the request, before the token counts exist, so SaefHelicone adds the estimate afterwards through Helicone's REST API: one PUT /v1/request/{id}/property per figure. Helicone stores property values as strings, so the numbers are sent as text. With scores=True it also posts saef_co2e_ug, saef_energy_uwh and saef_water_ul to POST /v1/request/{id}/score, in micro units because Helicone accepts integer scores only. The request id is the helicone-id response header, which request_id_from_headers reads. The API key comes from api_key= or HELICONE_API_KEY, and base_url=saef.integrations.helicone.EU selects the EU API. HTTP errors are raised. If Helicone has not logged the request yet when you call it, the HTTP error carries the estimate as err.saef_record: retry after a short wait with saef_hc.attach(request_id, err.saef_record), which does not count the call again. This example replaces the HTTP call with a print so it runs offline.

from saef.integrations.helicone import SaefHelicone


def show(method, url, body, api_key, timeout):  # the default sends the request with urllib
    print(method, url.split("/v1/")[1], body)


saef_hc = SaefHelicone(api_key="sk-helicone-...", region="eu-west-1", send=show)
saef_hc.record("8f1c2a5e-0000-4000-8000-000000000000", "gpt-4o", 400, 300, cached_input_tokens=800)
PUT request/8f1c2a5e-0000-4000-8000-000000000000/property {'key': 'saef_co2e_g', 'value': '0.028941052371172518'}
PUT request/8f1c2a5e-0000-4000-8000-000000000000/property {'key': 'saef_co2e_g_high', 'value': '0.04433480293129201'}
PUT request/8f1c2a5e-0000-4000-8000-000000000000/property {'key': 'saef_energy_kwh', 'value': '8.097023931477064e-05'}
PUT request/8f1c2a5e-0000-4000-8000-000000000000/property {'key': 'saef_water_l', 'value': '0.00012040985110709485'}
PUT request/8f1c2a5e-0000-4000-8000-000000000000/property {'key': 'saef_region', 'value': 'eu-west-1'}
PUT request/8f1c2a5e-0000-4000-8000-000000000000/property {'key': 'saef_model_class', 'value': 'B'}
PUT request/8f1c2a5e-0000-4000-8000-000000000000/property {'key': 'saef_version', 'value': '3.6.0'}
PUT request/8f1c2a5e-0000-4000-8000-000000000000/property {'key': 'saef_estimated', 'value': 'true'}

With the OpenAI client pointed at the Helicone gateway, raw = client.chat.completions.with_raw_response.create(...) gives both parts: saef_hc.record_response(raw.parse(), request_id_from_headers(raw.headers)).

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 music generation, and calls whose usage does not fit the model type, are skipped and counted in totals()["skipped_calls"].

Example notebooks: examples/quickstart.ipynb, and a runnable copy on Kaggle, Estimate the carbon footprint of your LLM API 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).
  • estimate_modality(unit_count, unit, model, region="global", megapixels=None) returns the same, with low and high, for embeddings, reranking, moderation, images, transcription, speech, voice and video.
  • 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?"

Files

FileRowsWhat it contains
cloud_region_factors.csv143Class A, B and C factors for each AWS, Azure and Google Cloud region, resolved to a grid, with the confidence of the region mapping
grid_intensity_all.csv240Grid carbon intensity (kg CO2e per kWh) for 210 countries and economies, 27 US eGRID subregions, EU-27, the world average and one subnational row, with the class factors at each grid
factors_v3_lifecycle.csv102Class factors by class, GPU (H100 central, B200 sensitivity) and printed region, with the energy and the four terms
model_factors.csv32Factors for the 18 measured open-weight models on H100 and B200, from the ML.ENERGY Leaderboard v3
model_class_mapping.csv288Identifier patterns, including AWS Bedrock, Azure and Vertex AI spellings, mapped to a model type (model_type, default text) and its class, plus the class C default for unmapped names
modality_factors.csv101GPU, server and facility energy, lifecycle terms, and CO2e and water at reference regions per functional unit of the non-text model types, with low, central and high
modality_sources.csv35Sources of modality_factors.csv, with licence and role
region_water_factors.csv17On-site and off-site water factors under both hydropower conventions, with AWARE 2.0 scarcity weighting
region_grid_crosswalk.csv17Printed region ids mapped to grids
token_basis_constants.csv7Weights that convert billed tokens to effective tokens
reserved_capacity_factors.csv3Factors per accelerator-hour for provisioned capacity
src/saef/n/aThe Python package: a standard-library calculator over these files

Three model classes are used: A (small, about 8B to 30B), B (standard, about 70B) and C (frontier). Every closed commercial model is class-only, assigned by the provider's pricing tier, and must be disclosed as an assumption.

Method

An estimate has four terms. Electricity, embodied hardware and data-centre construction are charged on effective tokens. Amortised training is charged on billed tokens.

kg CO2e = T_eff / 1e6 x inference footprint  +  T_billed / 1e6 x training term
T_eff   = (T_out + 0.30 x T_in_uncached + 0.05 x T_in_cached) / 1.339

Never multiply a billed token count by an inference footprint. At the default mix that overstates the result by about 3.1 times. Where only a billed total is known, use the default-mix factor per billed token, which already carries the conversion (0.302465 effective tokens per billed token at an 85% input share with no cache credit).

  • An unmapped identifier is assigned class C and flagged. Embeddings, reranking, moderation, images, transcription, speech, voice and video have their own model types, see below. Audio chat, music, OCR and fine-tuning jobs are out of scope.
  • Non-text and out-of-scope rows win over any text-model row that also matches, so a name like gpt-4o-mini-transcribe never receives a text class. Bedrock camelCase names such as TitanEmbeddingV2-Text are split at case boundaries before matching.
  • Token basis. Cache-write tokens (Anthropic cache_creation_input_tokens, Bedrock cacheWriteInputTokens) count as uncached input, weight W_in. Reasoning and thinking tokens count as output. OpenAI, Anthropic and Bedrock already include them in billed output, so add nothing. Gemini reports thoughtsTokenCount separately from candidatesTokenCount, so add it to output.
  • Unknown or global regions use the global-average grid. Water has no fallback, and covers 17 regions only.
  • Each result carries a conservative high case. A development line is reported separately and never added to a total.
  • Six significant figures are arithmetic, not evidence. The inputs support about two. Report the central value with the high case.

The numbers are estimates, not measurements.

Model types other than text (since dataset v3.4.0, speech, voice and video since v3.5.0)

Text models are charged on tokens by class A, B or C. Eleven more model types have their own unit and class, in modality_factors.csv. Every value there is an estimate, labelled derived (arithmetic on published benchmark results and documented facts) or assumption (an author judgement with a stated range). No provider publishes energy for these services.

Model typeClassUnitFacility Wh, central (low to high)g CO2e, eu-west-1g CO2e, us-east-1
Text embeddingsE-small1,000 input tokens0.00057 (9e-05 to 0.052)0.00017 (2.7e-05 to 0.016)0.00018 (2.9e-05 to 0.017)
E-large1,000 input tokens0.016 (0.0019 to 0.45)0.0049 (0.00057 to 0.14)0.0052 (0.00061 to 0.15)
Image embeddingsE-smallimage0.00015 (2.3e-05 to 0.0023)4.4e-05 (7e-06 to 0.00069)4.7e-05 (7.5e-06 to 0.00074)
E-largeimage0.016 (0.00048 to 0.45)0.0049 (0.00015 to 0.14)0.0052 (0.00016 to 0.15)
RerankingR-smallsearch unit0.029 (0.00075 to 0.58)0.0087 (0.00023 to 0.17)0.0093 (0.00024 to 0.19)
R-largesearch unit0.48 (0.0094 to 23)0.15 (0.0028 to 6.8)0.16 (0.003 to 7.3)
ModerationM-Acall0.0081 (0.0002 to 0.059)0.0024 (6.1e-05 to 0.018)0.0026 (6.5e-05 to 0.019)
M-Bcall0.026 (0.00034 to 0.16)0.008 (0.0001 to 0.049)0.0085 (0.00011 to 0.053)
Token-billed imagesIMG-TOK-B1024x1024 image, high quality0.73 (0.45 to 2.7)0.22 (0.14 to 0.82)0.24 (0.15 to 0.88)
IMG-TOK-Aimage, size and quality unknown0.54 (0.23 to 2.7)0.16 (0.069 to 0.82)0.17 (0.074 to 0.88)
Per-image diffusionD-smallimage up to 1.05 MP0.54 (0.23 to 0.87)0.16 (0.069 to 0.26)0.17 (0.074 to 0.28)
D-largeimage up to 1.05 MP3.2 (2.4 to 4.4)0.97 (0.73 to 1.3)1 (0.78 to 1.4)
TranscriptionSTT-ENCaudio minute0.06 (0.01 to 0.34)0.018 (0.0031 to 0.1)0.019 (0.0033 to 0.11)
STT-LLM-Aaudio minute0.027 (0.012 to 0.054)0.0081 (0.0037 to 0.016)0.0087 (0.0039 to 0.017)
STT-LLM-Baudio minute0.088 (0.041 to 0.15)0.027 (0.012 to 0.045)0.028 (0.013 to 0.048)
Text-to-speechTTS-B1,000 characters0.083 (0.039 to 0.54)0.025 (0.012 to 0.16)0.027 (0.013 to 0.18)
TTS-Baudio minute0.075 (0.041 to 0.41)0.022 (0.012 to 0.12)0.024 (0.013 to 0.13)
Realtime voice, turn-basedRT-A1,000 audio output tokens0.059 (0.032 to 0.12)0.018 (0.0097 to 0.036)0.019 (0.01 to 0.038)
RT-B1,000 audio output tokens0.19 (0.11 to 0.33)0.058 (0.033 to 0.098)0.062 (0.035 to 0.11)
RT-Aconversation minute (fallback)0.11 (0.02 to 1.3)0.033 (0.0059 to 0.38)0.035 (0.0063 to 0.41)
RT-Bconversation minute (fallback)0.36 (0.066 to 3.5)0.11 (0.02 to 1.1)0.11 (0.021 to 1.1)
RT-Cconversation minute (fallback)1.3 (0.13 to 16)0.4 (0.04 to 4.9)0.43 (0.043 to 5.3)
Realtime voice, full-duplexFD-Aactive session minute0.084 (0.026 to 0.19)0.025 (0.008 to 0.057)0.027 (0.0085 to 0.061)
VideoV-Asecond at 720p24 (4.8 to 77)7.1 (1.4 to 23)7.6 (1.5 to 25)
V-Bsecond at 720p83 (22 to 338)25 (6.5 to 102)27 (7 to 109)
V-Bsecond at 1080p186 (26 to 1452)56 (7.8 to 437)60 (8.4 to 468)
V-Csecond at 720p206 (83 to 844)62 (25 to 254)67 (27 to 272)

How to map provider usage to a unit.

Documentation truncated — see the full README on GitHub.

Reviews

No reviews yet

Be the first to review this server!