{"record":{"id":"e528a4760150980e","repo":"rohitg00/agentmemory","slug":"missing-required-environment-variable-key-set","errorCode":null,"errorMessage":"Missing required environment variable: ${key}. Set it in ~/.agentmemory/.env or as an environment variable.","messagePattern":"Missing required environment variable: (.+?)\\. Set it in ~/\\.agentmemory/\\.env or as an environment variable\\.","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"src/providers/index.ts","lineNumber":21,"sourceCode":"  ProviderConfig,\n  FallbackConfig,\n} from \"../types.js\";\nimport { AgentSDKProvider } from \"./agent-sdk.js\";\nimport { AnthropicProvider } from \"./anthropic.js\";\nimport { MinimaxProvider } from \"./minimax.js\";\nimport { NoopProvider } from \"./noop.js\";\nimport { OpenAIProvider } from \"./openai.js\";\nimport { OpenRouterProvider } from \"./openrouter.js\";\nimport { ResilientProvider } from \"./resilient.js\";\nimport { FallbackChainProvider } from \"./fallback-chain.js\";\nimport { getEnvVar } from \"../config.js\";\n\nexport { createEmbeddingProvider, createImageEmbeddingProvider } from \"./embedding/index.js\";\n\nfunction requireEnvVar(key: string): string {\n  const value = getEnvVar(key);\n  if (!value) {\n    throw new Error(\n      `Missing required environment variable: ${key}. Set it in ~/.agentmemory/.env or as an environment variable.`,\n    );\n  }\n  return value;\n}\n\n// #778: fallback providers used to inherit the primary provider's\n// model name (e.g. fallback Gemini was called with `gpt-4o-mini`),\n// 404'd every call, and tripped the circuit breaker — making\n// FALLBACK_PROVIDERS actively worse than no fallback. Each provider\n// must resolve its OWN env-driven default model. Mirrors the resolution\n// in detectProvider() so primary + fallback agree on what each\n// provider's default model is.\nfunction defaultModelFor(providerType: ProviderConfig[\"provider\"]): string {\n  switch (providerType) {\n    case \"openai\":\n      return getEnvVar(\"OPENAI_MODEL\") || \"gpt-5.6-luna\";\n    case \"anthropic\":","sourceCodeStart":3,"sourceCodeEnd":39,"githubUrl":"https://github.com/rohitg00/agentmemory/blob/e04ba88819c365c9acf9d6661ea802143e728bd6/src/providers/index.ts#L3-L39","documentation":"The provider factory's requireEnvVar helper enforces that mandatory provider configuration variables exist, reading via getEnvVar (environment plus ~/.agentmemory/.env). When the named variable is absent or empty it throws with explicit instructions on where to set it, failing fast at provider creation instead of mid-request.","triggerScenarios":"Calling createProvider/createBaseProvider (or createFallbackProvider) for a provider type whose required env var (e.g. a model or key variable read through requireEnvVar) is unset — e.g. factory branch does requireEnvVar(\"X_API_KEY\") and X_API_KEY is missing.","commonSituations":"Docker/K8s deployments without the secret mounted; ~/.agentmemory/.env never created so env-file defaults are absent; variable renamed across versions (docs vs code mismatch); empty-string value which getEnvVar treats as missing; running via systemd/cron with a stripped environment.","solutions":["Set the exact variable named in the message in ~/.agentmemory/.env or export it in the environment","Ensure non-empty value (empty string still throws)","Create ~/.agentmemory/.env with the right contents if relying on the env-file, and confirm the daemon loads that path","In containers, pass the env explicitly (-e KEY=... / secret mounts) rather than relying on your interactive shell"],"exampleFix":"// before\n// $ export WRONG_KEY=sk-...\nconst provider = await createProvider({ type: 'openai' }); // Missing required environment variable: OPENAI_API_KEY\n// after\n// $ export OPENAI_API_KEY=sk-...   (or add to ~/.agentmemory/.env)\nconst provider = await createProvider({ type: 'openai' });","handlingStrategy":"validation","validationCode":"const REQUIRED = ['OPENAI_API_KEY' /* or whichever provider type you use */];\nfunction assertEnv(keys: string[]) {\n  const missing = keys.filter(k => !process.env[k] || process.env[k]!.trim() === '');\n  if (missing.length) throw new Error(`Missing required environment variables: ${missing.join(', ')} — set them in ~/.agentmemory/.env or the environment`);\n}\nassertEnv(REQUIRED); // before createProvider(...)","typeGuard":"const envVarIsSet = (k: string): k is string => {\n  const v = process.env[k];\n  return typeof v === 'string' && v.trim().length > 0;\n};","tryCatchPattern":"try {\n  provider = await createProvider(config);\n} catch (err) {\n  const m = String((err as Error).message).match(/Missing required environment variable: (\\w+)/);\n  if (m) {\n    console.error(`Set ${m[1]} in ~/.agentmemory/.env or export it, then restart`);\n    process.exit(1);\n  }\n  throw err;\n}","preventionTips":["Fail fast at boot: assert every env var your provider config needs before starting the daemon","In containers, inject secrets explicitly; don't rely on interactive-shell exports surviving into services","Keep ~/.agentmemory/.env present and readable in all environments","After upgrading, diff new required env vars against your current .env","Treat empty strings as unset — always assign real values"],"tags":["missing-env-var","configuration","provider-factory"],"backgroundTag":"missing-env-var","analyzedSha":"e04ba88819c365c9acf9d6661ea802143e728bd6","analyzedAt":"2026-08-30T01:07:40.754Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}