{"record":{"id":"68dacb45f1fe977b","repo":"chroma-core/chroma","slug":"the-self-api-key-env-var-environment-variable-is-68dacb","errorCode":null,"errorMessage":"The {self.api_key_env_var} environment variable is not set.","messagePattern":"The (.+?) environment variable is not set\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"chromadb/utils/embedding_functions/openai_embedding_function.py","lineNumber":67,"sourceCode":"            raise ValueError(\n                \"The openai python package is not installed. Please install it with `pip install openai`\"\n            )\n\n        if api_key is not None:\n            warnings.warn(\n                \"Direct api_key configuration will not be persisted. \"\n                \"Please use environment variables via api_key_env_var for persistent storage.\",\n                DeprecationWarning,\n            )\n\n        if os.getenv(\"OPENAI_API_KEY\") is not None:\n            self.api_key_env_var = \"OPENAI_API_KEY\"\n        else:\n            self.api_key_env_var = api_key_env_var\n\n        self.api_key = api_key or os.getenv(self.api_key_env_var)\n        if not self.api_key:\n            raise ValueError(\n                f\"The {self.api_key_env_var} environment variable is not set.\"\n            )\n\n        self.model_name = model_name\n        self.organization_id = organization_id\n        self.api_base = api_base\n        self.api_type = api_type\n        self.api_version = api_version\n        self.deployment_id = deployment_id\n        self.default_headers = default_headers\n        self.dimensions = dimensions\n\n        # Initialize the OpenAI client\n        client_params: Dict[str, Any] = {\"api_key\": self.api_key}\n\n        if self.organization_id is not None:\n            client_params[\"organization\"] = self.organization_id\n        if self.api_base is not None:","sourceCodeStart":49,"sourceCodeEnd":85,"githubUrl":"https://github.com/chroma-core/chroma/blob/aecdd12c8a891610db8653630b066b32ceb678b5/chromadb/utils/embedding_functions/openai_embedding_function.py#L49-L85","documentation":"OpenAIEmbeddingFunction.__init__ raises this ValueError when no API key can be resolved: the api_key argument was not passed and os.getenv(api_key_env_var) is empty/unset. The env var name defaults to OPENAI_API_KEY, but note the constructor forces self.api_key_env_var to \"OPENAI_API_KEY\" whenever that variable is set, otherwise it uses the api_key_env_var parameter. Construction fails immediately, before any embeddings are requested.","triggerScenarios":"Calling OpenAIEmbeddingFunction() (or passing it as embedding_function= to Client/CreateCollection) in a process where OPENAI_API_KEY is unset and no api_key or custom api_key_env_var with a set variable is provided. Also happens when a custom api_key_env_var is passed but that variable is empty, and when code that worked locally (env var in shell) runs under cron/CI/docker where the variable was never exported.","commonSituations":"Forgetting to export OPENAI_API_KEY in the shell or Docker image; using a secrets manager (dotenv, Vault, pydantic-settings) but loading it after constructing the embedding function; passing api_key_env_var=\"MY_KEY\" while only OPENAI_API_KEY is set is fine, but the reverse (custom name, unset value) fails; .env file present but python-dotenv load_dotenv() never called.","solutions":["Set the environment variable before constructing: export OPENAI_API_KEY=sk-... (or the custom name you passed to api_key_env_var), and verify with echo $OPENAI_API_KEY in the same environment that runs the app.","If the key is empty in env, pass it explicitly: OpenAIEmbeddingFunction(api_key=\"sk-...\") — note this now emits a DeprecationWarning because direct api_key is not persisted in collection metadata.","If you use a custom variable name, make sure it matches what is actually exported: OpenAIEmbeddingFunction(api_key_env_var=\"MY_OPENAI_KEY\") requires export MY_OPENAI_KEY=...","In docker-compose/Kubernetes, add the variable to environment: or envFrom: and restart the pod/container; in CI, add it to the pipeline's secret variables.","If loading from .env, call load_dotenv() before creating the embedding function, not after."],"exampleFix":"// before\nimport chromadb.utils.embedding_functions as ef\nopenai_ef = ef.OpenAIEmbeddingFunction()  # ValueError: The OPENAI_API_KEY environment variable is not set.\n\n# after\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()  # ensure .env is loaded first\nif not os.getenv(\"OPENAI_API_KEY\"):\n    raise RuntimeError(\"OPENAI_API_KEY missing — check your secrets setup\")\nopenai_ef = ef.OpenAIEmbeddingFunction(model_name=\"text-embedding-3-small\")","handlingStrategy":"validation","validationCode":"import os\n\nOPENAI_EF_ENV = os.getenv(\"OPENAI_API_KEY_ENV_VAR\", \"OPENAI_API_KEY\")\nif not os.getenv(OPENAI_EF_ENV):\n    raise RuntimeError(\n        f\"{OPENAI_EF_ENV} is not set — export it before creating OpenAIEmbeddingFunction\"\n    )\n# safe to construct now\nopenai_ef = OpenAIEmbeddingFunction()","typeGuard":"def has_openai_api_key(env_var: str = \"OPENAI_API_KEY\") -> bool:\n    return bool(os.getenv(env_var))","tryCatchPattern":"try:\n    openai_ef = OpenAIEmbeddingFunction()\nexcept ValueError as e:\n    if \"environment variable is not set\" in str(e):\n        raise RuntimeError(f\"Missing OpenAI credentials: {e}\") from e\n    raise","preventionTips":["Load secrets (load_dotenv / secrets manager) at process start, before any embedding function is constructed.","Wrap EF construction in a small factory function that validates required env vars and fails with an actionable message.","In Docker/CI, assert required env vars in an entrypoint check before the app boots.","Prefer api_key_env_var over raw api_key so keys never land in code or persisted collection config."],"tags":["openai","embedding","api-key","environment-variable","chroma","constructor"],"backgroundTag":"missing-api-key-env-var","analyzedSha":"aecdd12c8a891610db8653630b066b32ceb678b5","analyzedAt":"2026-08-16T21:53:27.228Z","schemaVersion":2},"datasetVersion":"2026-08-16T23:17:17.608Z"}