crewAIInc/crewAI · error · ValueError

OPENAI_API_KEY environment variable is missing. Required for

Error message

OPENAI_API_KEY environment variable is missing. Required for default embeddings.

What it means

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.

Source

Thrown at lib/crewai-tools/src/crewai_tools/tools/db2_search_tool/db2_search_tool.py:215

        or underscores. Schema-qualified names (allow_period=True) allow exactly one
        period separating two valid simple identifiers (e.g. myschema.mytable).
        """
        pattern = (
            r"^[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)?$"
            if allow_period
            else r"^[A-Za-z][A-Za-z0-9_]*$"
        )
        if not re.match(pattern, name):
            raise ValueError(
                f"Security Alert: Invalid database identifier detected: {name}"
            )
        return name

    def _get_openai_client(self) -> Any:
        if self._openai_client is None:
            api_key = os.getenv("OPENAI_API_KEY")
            if not api_key:
                raise ValueError(
                    "OPENAI_API_KEY environment variable is missing. Required for default embeddings."
                )
            openai = importlib.import_module("openai")
            self._openai_client = openai.OpenAI(api_key=api_key)
        return self._openai_client

    def _generate_embedding(self, text: str) -> list[float]:
        if self.custom_embedding_fn:
            return self.custom_embedding_fn(text)

        result = (
            self._get_openai_client()
            .embeddings.create(
                input=[text],
                model=self.embedding_model,
            )
            .data[0]
            .embedding

View on GitHub (pinned to 754d7323be)

Solutions

  1. Export the variable in the running process: export OPENAI_API_KEY=sk-... (or add it to the container/service environment).
  2. Or avoid OpenAI entirely by passing custom_embedding_fn (an ImportString like 'mypkg.embeddings:embed') so no key is needed.
  3. If using a .env file, call load_dotenv() before the first tool call.
  4. Verify in-process with os.environ.get('OPENAI_API_KEY') before running the search.

Example fix

# before: subprocess without the variable
subprocess.run(['python', 'search.py'])

# after
import os
os.environ['OPENAI_API_KEY'] = key  # or export in shell/container
tool._run(query='quarterly summary')
Defensive patterns

Strategy: validation

Validate before calling

import os

def ensure_openai_key() -> None:
    if not os.getenv('OPENAI_API_KEY'):
        raise RuntimeError('OPENAI_API_KEY is not set — export it or pass custom_embedding_fn')

ensure_openai_key()
tool._run(query='...')

Try / catch

try:
    tool._run(query=q)
except ValueError as e:
    if 'OPENAI_API_KEY' in str(e):
        load_dotenv(); tool._run(query=q)  # load .env and retry once
    else:
        raise

Prevention

When it happens

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

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

Related errors


AI-assisted analysis of crewAIInc/crewAI@754d7323be (2026-08-15). Data as JSON: /api/errors/30cc5e58890de089. Report an issue: GitHub.