{"record":{"id":"693f73921b60258c","repo":"BerriAI/litellm","slug":"xai-api-key-is-required-set-api-key-litellm-xai","errorCode":null,"errorMessage":"XAI API key is required. Set api_key, litellm.xai_key, litellm.api_key, XAI_API_KEY, or use_xai_oauth=True.","messagePattern":"XAI API key is required\\. Set api_key, litellm\\.xai_key, litellm\\.api_key, XAI_API_KEY, or use_xai_oauth=True\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"litellm/llms/xai/responses/transformation.py","lineNumber":217,"sourceCode":"        if not api_key:\n            from litellm.llms.xai.oauth import (\n                XAIOAuthAuthenticator,\n                XAIOAuthError,\n                should_use_xai_oauth,\n            )\n\n            if should_use_xai_oauth(litellm_params.model_dump()):\n                try:\n                    api_key = XAIOAuthAuthenticator().get_access_token()\n                except XAIOAuthError as exc:\n                    raise AuthenticationError(\n                        model=model,\n                        llm_provider=self.custom_llm_provider.value,\n                        message=str(exc),\n                    ) from exc\n\n        if not api_key:\n            raise ValueError(\n                \"XAI API key is required. Set api_key, litellm.xai_key, \"\n                \"litellm.api_key, XAI_API_KEY, or use_xai_oauth=True.\"\n            )\n\n        headers.update(\n            {\n                \"Authorization\": f\"Bearer {api_key}\",\n            }\n        )\n        return headers\n\n    def get_complete_url(\n        self,\n        api_base: str | None,\n        litellm_params: dict,\n    ) -> str:\n        \"\"\"\n        Get the complete URL for XAI Responses API endpoint.","sourceCodeStart":199,"sourceCodeEnd":235,"githubUrl":"https://github.com/BerriAI/litellm/blob/77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8/litellm/llms/xai/responses/transformation.py#L199-L235","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Export XAI_API_KEY with a key from console.x.ai before calling xai models","Or pass api_key explicitly / set litellm.xai_key = '<key>'","Or run `litellm xai-oauth login` once and call with use_xai_oauth=True","Verify the env var is actually visible to the process (print os.environ.get('XAI_API_KEY'))"],"exampleFix":"# before\nresp = litellm.responses(model='xai/grok-4', input='hi')  # ValueError\n\n# after\nimport os\nos.environ['XAI_API_KEY'] = 'xai-...'\nresp = litellm.responses(model='xai/grok-4', input='hi')","handlingStrategy":"validation","validationCode":"import os\n\ndef xai_credentials_present(use_oauth: bool) -> bool:\n    return use_oauth or bool(os.getenv('XAI_API_KEY'))\n\nif not xai_credentials_present(use_oauth=False):\n    raise SystemExit('Set XAI_API_KEY or enable use_xai_oauth before calling xai models')","typeGuard":"def has_xai_auth(api_key: str | None, use_oauth: bool) -> bool:\n    return use_oauth or isinstance(api_key, str) and bool(api_key.strip())","tryCatchPattern":"try:\n    resp = litellm.completion(model='xai/grok-4', messages=m)\nexcept ValueError as e:\n    if 'XAI API key is required' in str(e):\n        raise RuntimeError('xAM credentials missing: configure XAI_API_KEY or OAuth') from e\n    raise","preventionTips":["Fail fast at startup: assert XAI_API_KEY (or completed OAuth) before serving traffic","Centralize key resolution in one config module so every call site inherits the same env checks","In Docker/CI, add a container healthcheck that verifies required env vars are non-empty","Prefer the model='xai/...' prefix so provider inference cannot silently pick another provider"],"tags":["xai","api-key","authentication","env-var","litellm"],"backgroundTag":"missing-api-key","analyzedSha":"77b7c6c40c0c5aa5fbcb1d6a1825ac39ca8829b8","analyzedAt":"2026-08-18T11:44:31.656Z","schemaVersion":2},"datasetVersion":"2026-08-21T13:17:26.733Z"}