{"record":{"id":"30cc5e58890de089","repo":"crewAIInc/crewAI","slug":"openai-api-key-environment-variable-is-missing-re","errorCode":null,"errorMessage":"OPENAI_API_KEY environment variable is missing. Required for default embeddings.","messagePattern":"OPENAI_API_KEY environment variable is missing\\. Required for default embeddings\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"lib/crewai-tools/src/crewai_tools/tools/db2_search_tool/db2_search_tool.py","lineNumber":215,"sourceCode":"        or underscores. Schema-qualified names (allow_period=True) allow exactly one\n        period separating two valid simple identifiers (e.g. myschema.mytable).\n        \"\"\"\n        pattern = (\n            r\"^[A-Za-z][A-Za-z0-9_]*(\\.[A-Za-z][A-Za-z0-9_]*)?$\"\n            if allow_period\n            else r\"^[A-Za-z][A-Za-z0-9_]*$\"\n        )\n        if not re.match(pattern, name):\n            raise ValueError(\n                f\"Security Alert: Invalid database identifier detected: {name}\"\n            )\n        return name\n\n    def _get_openai_client(self) -> Any:\n        if self._openai_client is None:\n            api_key = os.getenv(\"OPENAI_API_KEY\")\n            if not api_key:\n                raise ValueError(\n                    \"OPENAI_API_KEY environment variable is missing. Required for default embeddings.\"\n                )\n            openai = importlib.import_module(\"openai\")\n            self._openai_client = openai.OpenAI(api_key=api_key)\n        return self._openai_client\n\n    def _generate_embedding(self, text: str) -> list[float]:\n        if self.custom_embedding_fn:\n            return self.custom_embedding_fn(text)\n\n        result = (\n            self._get_openai_client()\n            .embeddings.create(\n                input=[text],\n                model=self.embedding_model,\n            )\n            .data[0]\n            .embedding","sourceCodeStart":197,"sourceCodeEnd":233,"githubUrl":"https://github.com/crewAIInc/crewAI/blob/754d7323beb2fd042e33444a115ea2d5a47193f0/lib/crewai-tools/src/crewai_tools/tools/db2_search_tool/db2_search_tool.py#L197-L233","documentation":"DB2VectorSearchTool._get_openai_client lazily creates an OpenAI client for default embeddings and reads OPENAI_API_KEY from the environment; if the variable is unset (or empty), it raises ValueError before importing openai. This fires on the first _run that needs an embedding and no custom_embedding_fn was provided. It is an environment/configuration error, not an OpenAI API failure.","triggerScenarios":"Calling tool._run(query='...') without OPENAI_API_KEY exported (shell, container, cron, CI); the variable set in a .env file that was never loaded into the process; a service unit or Docker image missing the env var.","commonSituations":"Local works but deployed container/cron lacks the variable; .env exists but python-dotenv load_dotenv() is not called before tool use; key stored under a different name (OPEN_AI_KEY, OPENAI_KEY).","solutions":["Export the variable in the running process: export OPENAI_API_KEY=sk-... (or add it to the container/service environment).","Or avoid OpenAI entirely by passing custom_embedding_fn (an ImportString like 'mypkg.embeddings:embed') so no key is needed.","If using a .env file, call load_dotenv() before the first tool call.","Verify in-process with os.environ.get('OPENAI_API_KEY') before running the search."],"exampleFix":"# before: subprocess without the variable\nsubprocess.run(['python', 'search.py'])\n\n# after\nimport os\nos.environ['OPENAI_API_KEY'] = key  # or export in shell/container\ntool._run(query='quarterly summary')","handlingStrategy":"validation","validationCode":"import os\n\ndef ensure_openai_key() -> None:\n    if not os.getenv('OPENAI_API_KEY'):\n        raise RuntimeError('OPENAI_API_KEY is not set — export it or pass custom_embedding_fn')\n\nensure_openai_key()\ntool._run(query='...')","typeGuard":null,"tryCatchPattern":"try:\n    tool._run(query=q)\nexcept ValueError as e:\n    if 'OPENAI_API_KEY' in str(e):\n        load_dotenv(); tool._run(query=q)  # load .env and retry once\n    else:\n        raise","preventionTips":["Set required env vars in the service/container definition, not the interactive shell only.","Call load_dotenv() at process start if keys live in .env.","Pass custom_embedding_fn when you use your own embedding service to remove the OpenAI dependency."],"tags":["db2","openai","environment-variable","embeddings","configuration"],"backgroundTag":null,"analyzedSha":"754d7323beb2fd042e33444a115ea2d5a47193f0","analyzedAt":"2026-08-15T04:06:56.746Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}