{"record":{"id":"c81892b712e73597","repo":"FoundationAgents/MetaGPT","slug":"to-use-serpapi-search-engine-make-sure-you-provid","errorCode":null,"errorMessage":"To use serpapi search engine, make sure you provide the `api_key` when constructing an object. You can obtain an API key from https://serpapi.com/.","messagePattern":"To use serpapi search engine, make sure you provide the `api_key` when constructing an object\\. You can obtain an API key from https://serpapi\\.com/\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"metagpt/tools/search_engine_serpapi.py","lineNumber":39,"sourceCode":"            \"engine\": \"google\",\n            \"google_domain\": \"google.com\",\n            \"gl\": \"us\",\n            \"hl\": \"en\",\n        }\n    )\n    url: str = \"https://serpapi.com/search\"\n    aiosession: Optional[aiohttp.ClientSession] = None\n    proxy: Optional[str] = None\n\n    @model_validator(mode=\"before\")\n    @classmethod\n    def validate_serpapi(cls, values: dict) -> dict:\n        if \"serpapi_api_key\" in values:\n            values.setdefault(\"api_key\", values[\"serpapi_api_key\"])\n            warnings.warn(\"`serpapi_api_key` is deprecated, use `api_key` instead\", DeprecationWarning, stacklevel=2)\n\n        if \"api_key\" not in values:\n            raise ValueError(\n                \"To use serpapi search engine, make sure you provide the `api_key` when constructing an object. You can obtain\"\n                \" an API key from https://serpapi.com/.\"\n            )\n        return values\n\n    async def run(self, query, max_results: int = 8, as_string: bool = True, **kwargs: Any) -> str:\n        \"\"\"Run query through SerpAPI and parse result async.\"\"\"\n        result = await self.results(query, max_results)\n        return self._process_response(result, as_string=as_string)\n\n    async def results(self, query: str, max_results: int) -> dict:\n        \"\"\"Use aiohttp to run query through SerpAPI and return the results async.\"\"\"\n\n        params = self.get_params(query)\n        params[\"source\"] = \"python\"\n        params[\"num\"] = max_results\n        params[\"output\"] = \"json\"\n","sourceCodeStart":21,"sourceCodeEnd":57,"githubUrl":"https://github.com/FoundationAgents/MetaGPT/blob/11cdf466d042aece04fc6cfd13b28e1a70341b1f/metagpt/tools/search_engine_serpapi.py#L21-L57","documentation":"ValueError from SerperAPIWrapper's model_validator (mode='before'): the constructor values contain neither api_key nor the deprecated serpapi_api_key alias. SerpAPI is a paid/keyed service, so the wrapper refuses to build without credentials. The legacy alias is honored with a DeprecationWarning.","triggerScenarios":"SerpAPIWrapper() with no arguments; config selects serpapi as the search engine but the api key is absent from config and env; key intended to come from env but the variable was never loaded.","commonSituations":"Switching MetaGPT's SearchEngine to SerpAPI without setting SERPAPI_API_KEY; .env file not loaded in deployment; legacy config using serpapi_api_key removed during refactor.","solutions":["Pass the key: SerpAPIWrapper(api_key=os.environ['SERPAPI_API_KEY'])","Or set api_key in your MetaGPT config for the serpapi engine","Legacy field serpapi_api_key still works (deprecation warning) if your config uses it"],"exampleFix":"# before\nengine = SerperAPIWrapper()  # ValueError\n# after\nengine = SerperAPIWrapper(api_key=os.environ[\"SERPAPI_API_KEY\"])","handlingStrategy":"validation","validationCode":"import os\napi_key = os.environ.get(\"SERPAPI_API_KEY\")\nif not api_key:\n    raise SystemExit(\"set SERPAPI_API_KEY before constructing SerperAPIWrapper\")","typeGuard":null,"tryCatchPattern":"try:\n    engine = SerperAPIWrapper(api_key=k)\nexcept ValueError as e:\n    raise ConfigError(str(e))","preventionTips":["Check required credential env vars in a startup preflight","Keep deprecated serpapi_api_key configs working but migrate them to api_key","Never rely on defaults for keyed third-party services"],"tags":["search","serpapi","credentials","config","pydantic"],"backgroundTag":null,"analyzedSha":"11cdf466d042aece04fc6cfd13b28e1a70341b1f","analyzedAt":"2026-08-14T23:20:02.994Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}