crewAIInc/crewAI · critical · ValueError

BRAVE_API_KEY environment variable is required for BraveSear

Error message

BRAVE_API_KEY environment variable is required for BraveSearchTool

What it means

BraveSearchTool.__init__ raises ValueError immediately at construction time if the BRAVE_API_KEY environment variable is not set. The key cannot be passed as a constructor argument (it is only read from the environment), so instantiation without prior env setup always fails.

Source

Thrown at lib/crewai-tools/src/crewai_tools/tools/brave_search_tool/brave_search_tool.py:56

    n_results: int = 10
    save_file: bool = False
    env_vars: list[EnvVar] = Field(
        default_factory=lambda: [
            EnvVar(
                name="BRAVE_API_KEY",
                description="API key for Brave Search",
                required=True,
            ),
        ]
    )
    # Rate limiting parameters
    _last_request_time: ClassVar[float] = 0
    _min_request_interval: ClassVar[float] = 1.0  # seconds

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        super().__init__(*args, **kwargs)
        if "BRAVE_API_KEY" not in os.environ:
            raise ValueError(
                "BRAVE_API_KEY environment variable is required for BraveSearchTool"
            )

    def _run(
        self,
        **kwargs: Any,
    ) -> Any:
        current_time = time.time()
        if (current_time - self._last_request_time) < self._min_request_interval:
            time.sleep(
                self._min_request_interval - (current_time - self._last_request_time)
            )
        BraveSearchTool._last_request_time = time.time()

        try:
            # Fallback to "query" or "search_query" for backwards compatibility
            query = kwargs.get("q") or kwargs.get("query") or kwargs.get("search_query")
            if not query:

View on GitHub (pinned to 754d7323be)

Solutions

  1. export BRAVE_API_KEY=<your key> before starting the process (get one at bravesearch api portal).
  2. In Python, call load_dotenv() before constructing the tool: from dotenv import load_dotenv; load_dotenv().
  3. For Docker/CI, inject the variable via -e BRAVE_API_KEY=... or the platform's secret manager.
  4. Verify with 'echo $BRAVE_API_KEY' (or os.environ check) in the same process that builds the tool.

Example fix

# before
tool = BraveSearchTool()  # ValueError: BRAVE_API_KEY environment variable is required

# after
import os
from dotenv import load_dotenv
from crewai_tools.tools.brave_search_tool import BraveSearchTool

load_dotenv()
assert os.getenv('BRAVE_API_KEY'), 'set BRAVE_API_KEY first'
tool = BraveSearchTool()
Defensive patterns

Strategy: validation

Validate before calling

import os

if not os.getenv("BRAVE_API_KEY"):
    raise SystemExit("Set BRAVE_API_KEY before creating BraveSearchTool")

Try / catch

try:
    tool = BraveSearchTool()
except ValueError as e:
    if "BRAVE_API_KEY" in str(e):
        load_dotenv()
        tool = BraveSearchTool()  # retry once after loading .env
    else:
        raise

Prevention

When it happens

Trigger: Instantiating BraveSearchTool() in a shell/process where BRAVE_API_KEY was never exported; setting the variable after the tool was constructed; running in CI, Docker, or a notebook where the .env file was not loaded before import/instantiation.

Common situations: Missing export in shell profile, .env not loaded (python-dotenv load_dotenv() called too late or not at all), secret configured only in a different environment (local vs deploy), case-sensitivity mistakes like BRAVE_APIKEY.

Related errors


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