crewAIInc/crewAI · error · ValueError

api_key is required (or set BROWSERBASE_API_KEY in env).

Error message

api_key is required (or set BROWSERBASE_API_KEY in env).

What it means

StagehandTool requires a Browserbase API key. During construction it resolves api_key from the constructor argument or the BROWSERBASE_API_KEY environment variable; if neither yields a value it raises ValueError at init (fail-fast), before any browser session is created. Stagehand runs on Browserbase cloud browsers, so the key is mandatory.

Source

Thrown at lib/crewai-tools/src/crewai_tools/tools/stagehand_tool/stagehand_tool.py:246

        self._session_id = session_id

        if not self._testing:
            log_level = {1: "INFO", 2: "WARNING", 3: "DEBUG"}.get(self.verbose, "ERROR")
            configure_logging(
                level=log_level, remove_logger_name=True, quiet_dependencies=True
            )

        self._check_required_credentials()

    def _check_required_credentials(self) -> None:
        """Validate that required credentials are present."""
        if not self._testing and not _HAS_STAGEHAND:
            raise ImportError(
                "`stagehand` package not found, please run `uv add stagehand`"
            )

        if not self.api_key:
            raise ValueError("api_key is required (or set BROWSERBASE_API_KEY in env).")
        if not self.project_id:
            raise ValueError(
                "project_id is required (or set BROWSERBASE_PROJECT_ID in env)."
            )

    def __del__(self) -> None:
        """Ensure cleanup on deletion."""
        try:
            self.close()
        except Exception:  # noqa: S110
            pass

    def _get_model_api_key(self) -> str | None:
        """Get the appropriate API key based on the model being used."""
        model_str = str(self.model_name)
        if "gpt" in model_str.lower():
            return self.model_api_key or os.getenv("OPENAI_API_KEY")
        if "claude" in model_str.lower() or "anthropic" in model_str.lower():

View on GitHub (pinned to 754d7323be)

Solutions

  1. Set the env var: export BROWSERBASE_API_KEY=your_key (add it to .env and load it before constructing the tool).
  2. Or pass it explicitly: StagehandTool(api_key="...", project_id="...").
  3. Verify the variable is actually visible in the process (print(os.environ.get('BROWSERBASE_API_KEY')) is None-check) in CI.

Example fix

# before
tool = StagehandTool()  # ValueError: api_key is required

# after
import os
tool = StagehandTool(
    api_key=os.environ["BROWSERBASE_API_KEY"],
    project_id=os.environ["BROWSERBASE_PROJECT_ID"],
)
Defensive patterns

Strategy: validation

Validate before calling

import os
api_key = os.environ.get("BROWSERBASE_API_KEY") or provided_api_key
if not api_key:
    raise ValueError("Set BROWSERBASE_API_KEY or pass api_key= to StagehandTool")

Type guard

def has_browserbase_api_key(api_key: str | None) -> bool:
    return bool(api_key or os.environ.get("BROWSERBASE_API_KEY"))

Try / catch

try:
    tool = StagehandTool()
except ValueError as e:
    if "api_key is required" in str(e):
        raise RuntimeError("Missing BROWSERBASE_API_KEY; add it to .env / CI secrets") from e
    raise

Prevention

When it happens

Trigger: StagehandTool() with no api_key while BROWSERBASE_API_KEY is unset/empty; env var name typos (e.g. BROWSERBASE_APIKEY); .env file not loaded before construction; CI secrets not injected.

Common situations: Missing or misspelled environment variable; secrets configured in the CI UI but not exported to the job; local .env files not loaded with python-dotenv before the tool is constructed.

Related errors


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