BerriAI/litellm · error · ValueError

STABILITY_API_KEY is not set. Please set it via environment

Error message

STABILITY_API_KEY is not set. Please set it via environment variable or pass api_key parameter.

What it means

Before sending a Stability AI image-edit request, LiteLLM resolves the API key from the explicit api_key argument or the STABILITY_API_KEY environment variable (via get_secret_str). If both are empty it raises this ValueError during validate_environment, so no request reaches Stability. It is a configuration error, not an HTTP error from the provider.

Source

Thrown at litellm/llms/stability/image_edit/transformations.py:159

        endpoint: Final = self._get_model_endpoint(model)
        return f"{base_url}{endpoint}"

    def validate_environment(
        self,
        headers: dict,
        model: str,
        api_key: str | None = None,
        litellm_params: dict | None = None,
        api_base: str | None = None,
    ) -> dict:
        """
        Validate environment and set up headers for Stability AI.
        """
        final_api_key: Final[str | None] = api_key or get_secret_str("STABILITY_API_KEY")

        if not final_api_key:
            raise ValueError(
                "STABILITY_API_KEY is not set. Please set it via environment variable or pass api_key parameter."
            )

        headers["Authorization"] = f"Bearer {final_api_key}"
        headers["Accept"] = "application/json"
        return headers

    def transform_image_edit_request(
        self,
        model: str,
        prompt: str | None,
        image: FileTypes | None,
        image_edit_optional_request_params: dict,
        litellm_params: GenericLiteLLMParams,
        headers: dict,
    ) -> tuple[dict, RequestFiles]:
        """
        Transform OpenAI-style request to Stability AI request format.

View on GitHub (pinned to 77b7c6c40c)

Solutions

  1. Export the variable in the runtime environment: export STABILITY_API_KEY=<your-key> (add to .env / CI secrets / Docker env).
  2. Pass the key explicitly per call: litellm.image_edit(..., api_key="<your-key>") or configure it on the Router deployment.
  3. Verify with a quick check that the key is visible to the process (e.g. env | grep STABILITY) before retrying.
  4. If using litellm proxy, set the key in the model deployment's litellm_params.api_key or the environment of the proxy process.

Example fix

# before
resp = litellm.image_edit(model="stability/stability-image-edit", prompt="...", image=fp)
# -> ValueError: STABILITY_API_KEY is not set...

# after
import os
resp = litellm.image_edit(
    model="stability/stability-image-edit",
    prompt="...",
    image=fp,
    api_key=os.environ["STABILITY_API_KEY"],
)
# or: export STABILITY_API_KEY=... in the shell / container
Defensive patterns

Strategy: validation

Validate before calling

import os


def stability_edit_ready(**kwargs) -> bool:
    """True when a Stability image-edit call has credentials."""
    return bool(kwargs.get("api_key") or os.environ.get("STABILITY_API_KEY"))


if not stability_edit_ready():
    raise RuntimeError("configure STABILITY_API_KEY before accepting image-edit jobs")

Try / catch

try:
    resp = litellm.image_edit(model="stability/...", prompt=p, image=fp)
except ValueError as e:
    if "STABILITY_API_KEY is not set" in str(e):
        # config error — surface to operator, do not retry
        alert_ops("missing STABILITY_API_KEY")
        raise
    raise

Prevention

When it happens

Trigger: Calling litellm.image_edit(model="stability/...", ...) in a shell/process where STABILITY_API_KEY is not exported and no api_key="sk-..." kwarg is passed. Also when the variable exists but is empty, or is set in .env but never loaded before the call.

Common situations: CI jobs, Docker containers, or cron environments that don't inherit your interactive shell env; deploying code that worked locally because the key lived in ~/.bashrc; typos in the variable name (STABILITY_KEY, STABILITYAI_API_KEY); expecting the key from a different provider's env var to be reused.

Understand the failure class

Background: "API key is required" / "API key not found" / "No API key was set": the missing-api-key error family across 16 libraries — this error's family across 16 libraries.

Related errors


AI-assisted analysis of BerriAI/litellm@77b7c6c40c (2026-08-18). Data as JSON: /api/errors/1a4a7e3a99f580af. Report an issue: GitHub.