assafelovic/gpt-researcher · error · Exception

Serper API key not found. Please set the SERPER_API_KEY envi

Error message

Serper API key not found. Please set the SERPER_API_KEY environment variable. You can get a key at https://serper.dev/

What it means

The Serper retriever needs an API key to call serper.dev's search API. In __init__, get_api_key() looks up os.environ['SERPER_API_KEY'] and raises a generic Exception if the lookup fails. The error is purely environmental — no request is attempted without the key.

Source

Thrown at gpt_researcher/retrievers/serper/serper.py:53

        Returns:
            list: List of sites to exclude
        """
        exclude_sites_env = os.getenv("SERPER_EXCLUDE_SITES", "")
        if exclude_sites_env:
            # Split by comma and strip whitespace
            return [site.strip() for site in exclude_sites_env.split(",") if site.strip()]
        return []

    def get_api_key(self):
        """
        Gets the Serper API key
        Returns:

        """
        try:
            api_key = os.environ["SERPER_API_KEY"]
        except Exception:
            raise Exception("Serper API key not found. Please set the SERPER_API_KEY environment variable. "
                            "You can get a key at https://serper.dev/")
        return api_key

    def search(self, max_results=7):
        """
        Searches the query with optional country, language, and time filtering
        Returns:
            list: List of search results with title, href, and body
        """
        print("Searching with query {0}...".format(self.query))
        """Useful for general internet search queries using the Serper API."""

        # Search the query (see https://serper.dev/playground for the format)
        url = "https://google.serper.dev/search"

        headers = {
            'X-API-KEY': self.api_key,
            'Content-Type': 'application/json'

View on GitHub (pinned to 6f998577d5)

Solutions

  1. Export the variable: export SERPER_API_KEY='your-key' or add SERPER_API_KEY=... to your .env and load it before startup.
  2. In Docker/CI, inject it as a secret/environment (-e SERPER_API_KEY=...).
  3. Create a key at https://serper.dev if none exists.
  4. Sanity-check with python -c "import os; print(bool(os.environ.get('SERPER_API_KEY')))".

Example fix

# before
from gpt_researcher.retrievers.serper.serper import SerperSearch
s = SerperSearch(query='news')  # raises: Serper API key not found

# after
import os
os.environ['SERPER_API_KEY'] = 'your-key'
s = SerperSearch(query='news')
Defensive patterns

Strategy: validation

Validate before calling

import os

if not os.environ.get('SERPER_API_KEY'):
    raise SystemExit('SERPER_API_KEY is not set — get a key at https://serper.dev')

Try / catch

try:
    searcher = SerperSearch(query='...')
except Exception as e:
    if 'API key not found' in str(e):
        raise SystemExit(f'Fix configuration: {e}')
    raise

Prevention

When it happens

Trigger: Constructing the Serper retriever (e.g., selecting 'serper' as the retriever/search provider in GPT Researcher config) when SERPER_API_KEY is not present in the process environment; the bare except also swallows and converts any exception raised during the os.environ lookup.

Common situations: Key stored in .env but dotenv not loaded; CI/CD pipeline secrets not injected; shell session started before the variable was exported; confusing SERPER_API_KEY with SERPAPI_API_KEY when switching search providers.

Understand the failure class

Background: "environment variable is not set" and "Missing keys in environment" errors: what missing required env var messages mean and how to fix them — this error's family across 28 libraries.

Related errors


AI-assisted analysis of assafelovic/gpt-researcher@6f998577d5 (2026-08-28). Data as JSON: /api/errors/4d7b3a5ba177747c. Report an issue: GitHub.