{"record":{"id":"f3efe1b2355afc62","repo":"xai-org/x-algorithm","slug":"api-key-is-required-set-eapimodelconfig-api-key-o","errorCode":null,"errorMessage":"API key is required: set EapiModelConfig.api_key or the XAI_API_KEY environment variable.","messagePattern":"API key is required: set EapiModelConfig\\.api_key or the XAI_API_KEY environment variable\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"critical","filePath":"grox/libs/grok_sampler/eapi_sampler.py","lineNumber":68,"sourceCode":"\nclass EapiSampler:\n    _cached_clients: dict[tuple[int, str, str], AsyncClient] = {}\n\n    def __init__(self, eapi_config: EapiModelConfig):\n        self.model: str = eapi_config.model\n        self.temperature: float = eapi_config.temperature\n        self.timeout: int = eapi_config.timeout\n        self.max_tokens = eapi_config.max_resp_len\n        self.api_key = eapi_config.api_key\n        self.api_host = eapi_config.api_host\n        self.log_reasoning_trace: bool = eapi_config.log_reasoning_trace\n        self.enable_search: bool = eapi_config.enable_search\n        self.reasoning_effort: str | None = eapi_config.reasoning_effort\n\n        api_key = self.api_key or os.getenv(\"XAI_API_KEY\")\n\n        if not api_key:\n            raise ValueError(\n                \"API key is required: set EapiModelConfig.api_key or the XAI_API_KEY environment variable.\"\n            )\n\n        self.client_kwargs = {\n            \"api_key\": api_key,\n            \"timeout\": self.timeout,\n            \"channel_options\": [(\"grpc.enable_retries\", 0)],\n        }\n\n        if self.api_host:\n            self.client_kwargs[\"api_host\"] = self.api_host\n\n    def _get_client(self) -> AsyncClient:\n        loop_id = get_loop_id()\n        key = (loop_id, self.model, self.api_host)\n        if key in self._cached_clients:\n            client = self._cached_clients[key]\n            return client","sourceCodeStart":50,"sourceCodeEnd":86,"githubUrl":"https://github.com/xai-org/x-algorithm/blob/24c60942c5c5fdad3a6addffb4c6e6d2f228f04f/grox/libs/grok_sampler/eapi_sampler.py#L50-L86","documentation":"EapiSampler requires an API key before it can construct its xAI client. In __init__, it falls back from EapiModelConfig.api_key to the XAI_API_KEY environment variable and raises ValueError if both are empty/None. This is a fail-fast guard so the sampler never gets constructed with unusable credentials.","triggerScenarios":"Instantiating EapiSampler (or an orchestrator that builds it) with an EapiModelConfig where api_key is None/empty AND os.getenv('XAI_API_KEY') is also unset or empty in the process environment.","commonSituations":"Deploying to a new environment (container, CI, k8s pod) where XAI_API_KEY was never injected; passing api_key='' instead of a real key; running locally with the var only set in a different shell or virtualenv activation; .env file not loaded before sampler construction.","solutions":["Set the XAI_API_KEY environment variable in the runtime environment (export XAI_API_KEY=... or inject via your deployment secrets).","Alternatively pass api_key explicitly: EapiModelConfig(api_key='...', ...) so the code does not depend on env.","Check for typos/whitespace: an empty-string or whitespace-only value still fails; verify with python -c \"import os;print(repr(os.getenv('XAI_API_KEY')))\").","If using .env files, ensure the loader (dotenv/settings) runs before EapiSampler is created."],"exampleFix":"# before\nsampler = EapiSampler(EapiModelConfig())  # ValueError: API key is required\n\n# after\nsampler = EapiSampler(EapiModelConfig(api_key=os.environ['XAI_API_KEY']))","handlingStrategy":"validation","validationCode":"api_key = cfg.api_key or os.getenv('XAI_API_KEY')\nif not api_key:\n    raise SystemExit('XAI_API_KEY not set; refusing to start')","typeGuard":null,"tryCatchPattern":"try:\n    sampler = EapiSampler(cfg)\nexcept ValueError as e:\n    if 'API key is required' in str(e):\n        logger.error('Missing xAI credentials; check secret injection')\n    raise","preventionTips":["Inject XAI_API_KEY via your secret manager rather than hardcoding","Add a startup preflight that asserts required env vars exist","Never default api_key to '' — treat empty as unset"],"tags":["api-key","authentication","configuration","env-var","xai"],"backgroundTag":"missing-api-key","analyzedSha":"24c60942c5c5fdad3a6addffb4c6e6d2f228f04f","analyzedAt":"2026-08-28T11:40:14.686Z","schemaVersion":2},"datasetVersion":"2026-08-28T16:17:29.566Z"}