crewAIInc/crewAI · error · ValueError
OPENAI_API_KEY environment variable is required for MongoDBV
Error message
OPENAI_API_KEY environment variable is required for MongoDBVectorSearchTool and it is mandatory to use the tool.
What it means
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.
Source
Thrown at lib/crewai-tools/src/crewai_tools/tools/mongodb_vector_search_tool/vector_search.py:129
import click
if click.confirm(
"You are missing the 'mongodb' crewai tool. Would you like to install it?"
):
import subprocess
subprocess.run(["uv", "add", "pymongo"], check=True) # noqa: S607
else:
raise ImportError("You are missing the 'mongodb' crewai tool.")
self._openai_client: AzureOpenAI | Client
if "AZURE_OPENAI_ENDPOINT" in os.environ:
self._openai_client = AzureOpenAI()
elif "OPENAI_API_KEY" in os.environ:
self._openai_client = Client()
else:
raise ValueError(
"OPENAI_API_KEY environment variable is required for MongoDBVectorSearchTool and it is mandatory to use the tool."
)
from pymongo import MongoClient
from pymongo.driver_info import DriverInfo
self._client: MongoClient[dict[str, Any]] = MongoClient(
self.connection_string,
driver=DriverInfo(name="CrewAI", version=version("crewai-tools")),
)
self._coll = self._client[self.database_name][self.collection_name]
def create_vector_search_index(
self,
*,
dimensions: int,
relevance_score_fn: str = "cosine",
auto_index_timeout: int = 15,View on GitHub (pinned to 754d7323be)
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
Example fix
# before
# no env vars set
tool = MongoDBVectorSearchTool(...) # ValueError
# after
import os
from dotenv import load_dotenv
load_dotenv()
assert os.getenv("OPENAI_API_KEY"), "OPENAI_API_KEY required"
tool = MongoDBVectorSearchTool(collection_name="docs", index_name="vector_index") Defensive patterns
Strategy: validation
Validate before calling
import os
def embeddings_config_ok() -> bool:
return "OPENAI_API_KEY" in os.environ or "AZURE_OPENAI_ENDPOINT" in os.environ
assert embeddings_config_ok(), "Set OPENAI_API_KEY (or AZURE_OPENAI_ENDPOINT + key)" Try / catch
try:
tool = MongoDBVectorSearchTool(collection_name="docs", index_name="idx")
except ValueError as e:
if "OPENAI_API_KEY" in str(e):
raise SystemExit("Set OPENAI_API_KEY or AZURE_OPENAI_ENDPOINT") from e
raise Prevention
- 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
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- OPENAI_API_KEY environment variable is missing. Required for
- Failed to initialize {self.config.provider} embedding servic
- `api_key` is required, please set the `HYPERBROWSER_API_KEY`
- AGENT_HANDLER_API_KEY environment variable is required. Set
- Invalid configuration for embedding provider '{provider}':\n
AI-assisted analysis of crewAIInc/crewAI@754d7323be (2026-08-15).
Data as JSON: /api/errors/bb49cdf2826472b0.
Report an issue: GitHub.