{"record":{"id":"0e34ba269c625455","repo":"mem0ai/mem0","slug":"xai-api-key-is-required","errorCode":null,"errorMessage":"xAI API key is required","messagePattern":"xAI API key is required","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"mem0-ts/src/oss/src/llms/xai.ts","lineNumber":18,"sourceCode":"import { OpenAILLM } from \"./openai\";\nimport { LLMConfig, Message } from \"../types\";\nimport { LLMResponse } from \"./base\";\n\n/**\n * xAI (Grok) LLM provider.\n *\n * xAI's Grok API is OpenAI-compatible, so this simply reuses {@link OpenAILLM}\n * and overrides the connection defaults — mirroring `mem0/llms/xai.py` in the\n * Python SDK. The API key resolves from `config.apiKey` or the `XAI_API_KEY`\n * env var, and the base URL from `config.baseURL`, `XAI_API_BASE`, else\n * `https://api.x.ai/v1`.\n */\nexport class XAILLM extends OpenAILLM {\n  constructor(config: LLMConfig) {\n    const apiKey = config.apiKey || process.env.XAI_API_KEY;\n    if (!apiKey) {\n      throw new Error(\"xAI API key is required\");\n    }\n    super({\n      ...config,\n      apiKey,\n      baseURL:\n        config.baseURL || process.env.XAI_API_BASE || \"https://api.x.ai/v1\",\n      model: config.model || \"grok-4.3\",\n    });\n  }\n\n  async generateResponse(\n    messages: Message[],\n    responseFormat?: { type: string },\n    tools?: any[],\n  ): Promise<string | LLMResponse> {\n    try {\n      return await super.generateResponse(messages, responseFormat, tools);\n    } catch (err) {","sourceCodeStart":1,"sourceCodeEnd":36,"githubUrl":"https://github.com/mem0ai/mem0/blob/001c235229be8795e3834520467bd0d661ed8f34/mem0-ts/src/oss/src/llms/xai.ts#L1-L36","documentation":"Thrown by the XAILLM constructor when neither config.apiKey nor the XAI_API_KEY environment variable is present. xAI's Grok API requires authentication, so the constructor fails fast instead of letting every request fail later with a 401. This mirrors the Python SDK's mem0/llms/xai.py behavior.","triggerScenarios":"Constructing Memory with llm.provider 'xai' (or instantiating XAILLM directly) without passing apiKey in config.llm.config and without XAI_API_KEY exported in the process environment. Throws synchronously at construction time, before any memory operation runs.","commonSituations":"Env var set in a shell but not in the deployment (Docker/CI/serverless where env must be declared), .env file present but not loaded before import, typo in the variable name (XAI_KEY, X_AI_API_KEY), or assuming the SDK reads a differently-named variable.","solutions":["Export XAI_API_KEY in the environment where Node runs: export XAI_API_KEY=... (or add it to your deployment's env config).","Or pass the key explicitly: new Memory({ llm: { provider: 'xai', config: { apiKey: process.env.XAI_API_KEY } } }).","If using .env, ensure dotenv (or the runtime's env loading) runs before the Memory/XAILLM constructor executes.","Verify with a quick check before constructing: if (!process.env.XAI_API_KEY) throw new Error('XAI_API_KEY missing');"],"exampleFix":"// before\nconst memory = new Memory({\n  llm: { provider: 'xai', config: {} }, // throws: xAI API key is required\n});\n\n// after\nconst memory = new Memory({\n  llm: {\n    provider: 'xai',\n    config: { apiKey: process.env.XAI_API_KEY }, // or export XAI_API_KEY\n  },\n});","handlingStrategy":"validation","validationCode":"const xaiKey = process.env.XAI_API_KEY;\nif (!xaiKey) {\n  throw new Error('XAI_API_KEY is not set — add it to the environment before constructing Memory');\n}","typeGuard":"function hasXaiCredentials(config: { apiKey?: string } | undefined): boolean {\n  return Boolean(config?.apiKey || process.env.XAI_API_KEY);\n}","tryCatchPattern":"try {\n  memory = new Memory({ llm: { provider: 'xai', config: { apiKey: process.env.XAI_API_KEY } } });\n} catch (err) {\n  if (err instanceof Error && err.message === 'xAI API key is required') {\n    // fail startup with an operator-actionable message\n    process.exitCode = 1;\n    throw new Error('Missing XAI_API_KEY: set it in the deployment environment');\n  }\n  throw err;\n}","preventionTips":["Declare XAI_API_KEY in Docker/CI/serverless env specs so it is never silently absent.","Assert required env vars at process start with a single config-validation module.","Add a startup self-test that constructs Memory once, so key errors surface at boot, not mid-request."],"tags":["llm","xai","api-key","configuration","typescript"],"backgroundTag":null,"analyzedSha":"001c235229be8795e3834520467bd0d661ed8f34","analyzedAt":"2026-08-15T01:55:42.685Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}