{"record":{"id":"e822d5490ddb7e81","repo":"microsoft/semantic-kernel","slug":"an-unexpected-error-occurred-while-getting-search-e822d5","errorCode":null,"errorMessage":"An unexpected error occurred while getting search results.","messagePattern":"An unexpected error occurred while getting search results\\.","errorType":"exception","errorClass":"ServiceInvalidRequestError","httpStatus":null,"severity":"error","filePath":"python/semantic_kernel/connectors/google_search.py","lineNumber":279,"sourceCode":"                params:\\nnum_results: {options.top}\\noffset: {options.skip}\"\n        )\n\n        full_url = f\"{CUSTOM_SEARCH_URL}{self._build_query(query, options)}\"\n        headers = {\"user_agent\": SEMANTIC_KERNEL_USER_AGENT}\n        try:\n            async with AsyncClient(timeout=5) as client:\n                response = await client.get(full_url, headers=headers)\n                response.raise_for_status()\n                return GoogleSearchResponse.model_validate_json(response.text)\n        except HTTPStatusError as ex:\n            logger.error(f\"Failed to get search results: {ex}\")\n            raise ServiceInvalidRequestError(\"Failed to get search results.\") from ex\n        except RequestError as ex:\n            logger.error(f\"Client error occurred: {ex}\")\n            raise ServiceInvalidRequestError(\"A client error occurred while getting search results.\") from ex\n        except Exception as ex:\n            logger.error(f\"An unexpected error occurred: {ex}\")\n            raise ServiceInvalidRequestError(\"An unexpected error occurred while getting search results.\") from ex\n\n    def _validate_options(self, options: SearchOptions) -> None:\n        if options.top > 10:\n            raise ServiceInvalidRequestError(\"count value must be less than or equal to 10.\")\n\n    def _parse_filter_lambda(self, filter_lambda: Callable | str) -> list[dict[str, str]]:\n        \"\"\"Parse a string lambda or string expression into a list of {field: value} dicts using AST.\"\"\"\n        expr = filter_lambda if isinstance(filter_lambda, str) else getsource(filter_lambda).strip()\n        tree = ast.parse(expr, mode=\"eval\")\n        node = tree.body\n        visitor = SearchLambdaVisitor(valid_parameters=QUERY_PARAMETERS)\n        visitor.visit(node)\n        return visitor.filters\n\n    def _build_query(self, query: str, options: SearchOptions) -> str:\n        params = {\n            \"key\": self.settings.api_key.get_secret_value(),\n            \"cx\": self.settings.engine_id,","sourceCodeStart":261,"sourceCodeEnd":297,"githubUrl":"https://github.com/microsoft/semantic-kernel/blob/c028a0c7dc4f0814cdcbaba9d998f187a41197bf/python/semantic_kernel/connectors/google_search.py#L261-L297","documentation":"The final except Exception branch in _inner_search catches anything that is neither HTTPStatusError nor RequestError and re-raises it as ServiceInvalidRequestError('An unexpected error occurred while getting search results.'). Typical causes are failures after the HTTP call completed, such as JSON validation or pydantic parsing of the response body. The original exception is in __cause__ and is also written to the log.","triggerScenarios":"Google returns a non-JSON body (e.g. an HTML error/interstitial page); GoogleSearchResponse.model_validate_json fails because the response schema changed; an unexpected httpx internal error; pydantic version mismatch on response parsing.","commonSituations":"Captive portals returning HTML; Google API deprecating/adding fields; transient CDN weirdness; upstream library version drift.","solutions":["Read the logged 'An unexpected error occurred: <ex>' line to see the root exception.","Inspect ex.__cause__ for the precise failure (often a pydantic ValidationError or JSONDecodeError).","If the response schema changed, pin or upgrade semantic_kernel and report the schema drift.","Reproduce the raw request with httpx/curl to see the actual body Google returned."],"exampleFix":"# before\nresults = await google.search('skates')  # non-JSON body -> [1305]\n\n# after\nimport logging\nlogging.getLogger('semantic_kernel.connectors.google_search').setLevel(logging.DEBUG)\ntry:\n    results = await google.search('skates')\nexcept ServiceInvalidRequestError as ex:\n    root = ex.__cause__\n    logging.error('google search root cause: %r', root)\n    raise","handlingStrategy":"try-catch","validationCode":null,"typeGuard":null,"tryCatchPattern":"import logging\nfrom semantic_kernel.exceptions import ServiceInvalidRequestError\n\ntry:\n    results = await google.search(query, top=top)\nexcept ServiceInvalidRequestError as ex:\n    root = ex.__cause__\n    logging.exception('Google search failed unexpectedly; root cause: %r', root)\n    raise","preventionTips":["Enable DEBUG logging on the google_search logger to capture the root exception.","Reproduce the raw request with httpx/curl to inspect the actual response body.","Keep semantic_kernel up to date so GoogleSearchResponse matches Google's schema."],"tags":["google-search","network","unexpected","parsing"],"backgroundTag":null,"analyzedSha":"c028a0c7dc4f0814cdcbaba9d998f187a41197bf","analyzedAt":"2026-08-13T13:48:05.040Z","schemaVersion":2},"datasetVersion":"2026-08-14T10:17:34.591Z"}