{"record":{"id":"bb49cdf2826472b0","repo":"crewAIInc/crewAI","slug":"openai-api-key-environment-variable-is-required-fo","errorCode":null,"errorMessage":"OPENAI_API_KEY environment variable is required for MongoDBVectorSearchTool and it is mandatory to use the tool.","messagePattern":"OPENAI_API_KEY environment variable is required for MongoDBVectorSearchTool and it is mandatory to use the tool\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"lib/crewai-tools/src/crewai_tools/tools/mongodb_vector_search_tool/vector_search.py","lineNumber":129,"sourceCode":"            import click\n\n            if click.confirm(\n                \"You are missing the 'mongodb' crewai tool. Would you like to install it?\"\n            ):\n                import subprocess\n\n                subprocess.run([\"uv\", \"add\", \"pymongo\"], check=True)  # noqa: S607\n\n            else:\n                raise ImportError(\"You are missing the 'mongodb' crewai tool.\")\n\n        self._openai_client: AzureOpenAI | Client\n        if \"AZURE_OPENAI_ENDPOINT\" in os.environ:\n            self._openai_client = AzureOpenAI()\n        elif \"OPENAI_API_KEY\" in os.environ:\n            self._openai_client = Client()\n        else:\n            raise ValueError(\n                \"OPENAI_API_KEY environment variable is required for MongoDBVectorSearchTool and it is mandatory to use the tool.\"\n            )\n\n        from pymongo import MongoClient\n        from pymongo.driver_info import DriverInfo\n\n        self._client: MongoClient[dict[str, Any]] = MongoClient(\n            self.connection_string,\n            driver=DriverInfo(name=\"CrewAI\", version=version(\"crewai-tools\")),\n        )\n        self._coll = self._client[self.database_name][self.collection_name]\n\n    def create_vector_search_index(\n        self,\n        *,\n        dimensions: int,\n        relevance_score_fn: str = \"cosine\",\n        auto_index_timeout: int = 15,","sourceCodeStart":111,"sourceCodeEnd":147,"githubUrl":"https://github.com/crewAIInc/crewAI/blob/754d7323beb2fd042e33444a115ea2d5a47193f0/lib/crewai-tools/src/crewai_tools/tools/mongodb_vector_search_tool/vector_search.py#L111-L147","documentation":"The tool needs an OpenAI (or Azure OpenAI) client to embed documents/queries before vector search. At construction it picks AzureOpenAI when AZURE_OPENAI_ENDPOINT is set, Client (OpenAI) when OPENAI_API_KEY is set, and raises this ValueError when neither env var is present — embeddings are mandatory, so there is no keyless path.","triggerScenarios":"Constructing MongoDBVectorSearchTool with neither OPENAI_API_KEY nor AZURE_OPENAI_ENDPOINT in the environment; setting the key after process start without restart; .env file present but load_dotenv() not called before construction.","commonSituations":"Forgetting to export the key in a new shell; docker env not passed (--env-file omitted); CI secrets not injected; intending Azure but missing the endpoint variable so it falls through to the check.","solutions":["export OPENAI_API_KEY='sk-...' before constructing the tool (or set it in .env + load_dotenv())","For Azure, set AZURE_OPENAI_ENDPOINT (plus AZURE_OPENAI_API_KEY) so the AzureOpenAI branch is taken","Pass env vars into containers: docker run --env-file .env ...","Assert the variable in a startup check so failures happen loudly and early"],"exampleFix":"# before\n# no env vars set\ntool = MongoDBVectorSearchTool(...)  # ValueError\n\n# after\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\nassert os.getenv(\"OPENAI_API_KEY\"), \"OPENAI_API_KEY required\"\ntool = MongoDBVectorSearchTool(collection_name=\"docs\", index_name=\"vector_index\")","handlingStrategy":"validation","validationCode":"import os\n\ndef embeddings_config_ok() -> bool:\n    return \"OPENAI_API_KEY\" in os.environ or \"AZURE_OPENAI_ENDPOINT\" in os.environ\n\nassert embeddings_config_ok(), \"Set OPENAI_API_KEY (or AZURE_OPENAI_ENDPOINT + key)\"","typeGuard":null,"tryCatchPattern":"try:\n    tool = MongoDBVectorSearchTool(collection_name=\"docs\", index_name=\"idx\")\nexcept ValueError as e:\n    if \"OPENAI_API_KEY\" in str(e):\n        raise SystemExit(\"Set OPENAI_API_KEY or AZURE_OPENAI_ENDPOINT\") from e\n    raise","preventionTips":["load_dotenv() before constructing embedding-backed tools","Add an env-var checklist to your app's startup","For Azure, set both AZURE_OPENAI_ENDPOINT and AZURE_OPENAI_API_KEY"],"tags":["env-var","openai","azure","embeddings","configuration"],"backgroundTag":null,"analyzedSha":"754d7323beb2fd042e33444a115ea2d5a47193f0","analyzedAt":"2026-08-15T04:06:56.746Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}