BerriAI/litellm · error · ValueError

XAI API key is required. Set api_key, litellm.xai_key, litel

Error message

XAI API key is required. Set api_key, litellm.xai_key, litellm.api_key, XAI_API_KEY, or use_xai_oauth=True.

What it means

ValueError raised in the xAI responses transformation when no API key could be resolved from any source: the api_key argument, litellm.xai_key, litellm.api_key, the XAI_API_KEY environment variable, or the OAuth path (use_xai_oauth=True). It fires right before the Authorization header is built, so the request never leaves the process.

Source

Thrown at litellm/llms/xai/responses/transformation.py:217

        if not api_key:
            from litellm.llms.xai.oauth import (
                XAIOAuthAuthenticator,
                XAIOAuthError,
                should_use_xai_oauth,
            )

            if should_use_xai_oauth(litellm_params.model_dump()):
                try:
                    api_key = XAIOAuthAuthenticator().get_access_token()
                except XAIOAuthError as exc:
                    raise AuthenticationError(
                        model=model,
                        llm_provider=self.custom_llm_provider.value,
                        message=str(exc),
                    ) from exc

        if not api_key:
            raise ValueError(
                "XAI API key is required. Set api_key, litellm.xai_key, "
                "litellm.api_key, XAI_API_KEY, or use_xai_oauth=True."
            )

        headers.update(
            {
                "Authorization": f"Bearer {api_key}",
            }
        )
        return headers

    def get_complete_url(
        self,
        api_base: str | None,
        litellm_params: dict,
    ) -> str:
        """
        Get the complete URL for XAI Responses API endpoint.

View on GitHub (pinned to 77b7c6c40c)

Solutions

  1. Export XAI_API_KEY with a key from console.x.ai before calling xai models
  2. Or pass api_key explicitly / set litellm.xai_key = '<key>'
  3. Or run `litellm xai-oauth login` once and call with use_xai_oauth=True
  4. Verify the env var is actually visible to the process (print os.environ.get('XAI_API_KEY'))

Example fix

# before
resp = litellm.responses(model='xai/grok-4', input='hi')  # ValueError

# after
import os
os.environ['XAI_API_KEY'] = 'xai-...'
resp = litellm.responses(model='xai/grok-4', input='hi')
Defensive patterns

Strategy: validation

Validate before calling

import os

def xai_credentials_present(use_oauth: bool) -> bool:
    return use_oauth or bool(os.getenv('XAI_API_KEY'))

if not xai_credentials_present(use_oauth=False):
    raise SystemExit('Set XAI_API_KEY or enable use_xai_oauth before calling xai models')

Type guard

def has_xai_auth(api_key: str | None, use_oauth: bool) -> bool:
    return use_oauth or isinstance(api_key, str) and bool(api_key.strip())

Try / catch

try:
    resp = litellm.completion(model='xai/grok-4', messages=m)
except ValueError as e:
    if 'XAI API key is required' in str(e):
        raise RuntimeError('xAM credentials missing: configure XAI_API_KEY or OAuth') from e
    raise

Prevention

When it happens

Trigger: Calling responses/completion with an xai/ model while XAI_API_KEY is unset, no api_key argument is passed, and use_xai_oauth is not enabled; or setting use_xai_oauth but the OAuth authenticator raised earlier and the key is still empty.

Common situations: Missing XAI_API_KEY in CI, Docker, or serverless env; key set under a wrong name (e.g. GROK_API_KEY); intending OAuth but forgetting use_xai_oauth=True; .env file not loaded before import.

Related errors


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