rohitg00/agentmemory · error · Error

Missing required environment variable: ${key}. Set it in ~/.

Error message

Missing required environment variable: ${key}. Set it in ~/.agentmemory/.env or as an environment variable.

What it means

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.

Source

Thrown at src/providers/index.ts:21

  ProviderConfig,
  FallbackConfig,
} from "../types.js";
import { AgentSDKProvider } from "./agent-sdk.js";
import { AnthropicProvider } from "./anthropic.js";
import { MinimaxProvider } from "./minimax.js";
import { NoopProvider } from "./noop.js";
import { OpenAIProvider } from "./openai.js";
import { OpenRouterProvider } from "./openrouter.js";
import { ResilientProvider } from "./resilient.js";
import { FallbackChainProvider } from "./fallback-chain.js";
import { getEnvVar } from "../config.js";

export { createEmbeddingProvider, createImageEmbeddingProvider } from "./embedding/index.js";

function requireEnvVar(key: string): string {
  const value = getEnvVar(key);
  if (!value) {
    throw new Error(
      `Missing required environment variable: ${key}. Set it in ~/.agentmemory/.env or as an environment variable.`,
    );
  }
  return value;
}

// #778: fallback providers used to inherit the primary provider's
// model name (e.g. fallback Gemini was called with `gpt-4o-mini`),
// 404'd every call, and tripped the circuit breaker — making
// FALLBACK_PROVIDERS actively worse than no fallback. Each provider
// must resolve its OWN env-driven default model. Mirrors the resolution
// in detectProvider() so primary + fallback agree on what each
// provider's default model is.
function defaultModelFor(providerType: ProviderConfig["provider"]): string {
  switch (providerType) {
    case "openai":
      return getEnvVar("OPENAI_MODEL") || "gpt-5.6-luna";
    case "anthropic":

View on GitHub (pinned to e04ba88819)

Solutions

  1. Set the exact variable named in the message in ~/.agentmemory/.env or export it in the environment
  2. Ensure non-empty value (empty string still throws)
  3. Create ~/.agentmemory/.env with the right contents if relying on the env-file, and confirm the daemon loads that path
  4. In containers, pass the env explicitly (-e KEY=... / secret mounts) rather than relying on your interactive shell

Example fix

// before
// $ export WRONG_KEY=sk-...
const provider = await createProvider({ type: 'openai' }); // Missing required environment variable: OPENAI_API_KEY
// after
// $ export OPENAI_API_KEY=sk-...   (or add to ~/.agentmemory/.env)
const provider = await createProvider({ type: 'openai' });
Defensive patterns

Strategy: validation

Validate before calling

const REQUIRED = ['OPENAI_API_KEY' /* or whichever provider type you use */];
function assertEnv(keys: string[]) {
  const missing = keys.filter(k => !process.env[k] || process.env[k]!.trim() === '');
  if (missing.length) throw new Error(`Missing required environment variables: ${missing.join(', ')} — set them in ~/.agentmemory/.env or the environment`);
}
assertEnv(REQUIRED); // before createProvider(...)

Type guard

const envVarIsSet = (k: string): k is string => {
  const v = process.env[k];
  return typeof v === 'string' && v.trim().length > 0;
};

Try / catch

try {
  provider = await createProvider(config);
} catch (err) {
  const m = String((err as Error).message).match(/Missing required environment variable: (\w+)/);
  if (m) {
    console.error(`Set ${m[1]} in ~/.agentmemory/.env or export it, then restart`);
    process.exit(1);
  }
  throw err;
}

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Understand the failure class

Background: "environment variable is not set" and "Missing keys in environment" errors: what missing required env var messages mean and how to fix them — this error's family across 28 libraries.

Related errors


AI-assisted analysis of rohitg00/agentmemory@e04ba88819 (2026-08-30). Data as JSON: /api/errors/e528a4760150980e. Report an issue: GitHub.