microsoft/semantic-kernel · error · ServiceInvalidRequestError

An unexpected error occurred while getting search results.

Error message

An unexpected error occurred while getting search results.

What it means

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.

Source

Thrown at python/semantic_kernel/connectors/google_search.py:279

                params:\nnum_results: {options.top}\noffset: {options.skip}"
        )

        full_url = f"{CUSTOM_SEARCH_URL}{self._build_query(query, options)}"
        headers = {"user_agent": SEMANTIC_KERNEL_USER_AGENT}
        try:
            async with AsyncClient(timeout=5) as client:
                response = await client.get(full_url, headers=headers)
                response.raise_for_status()
                return GoogleSearchResponse.model_validate_json(response.text)
        except HTTPStatusError as ex:
            logger.error(f"Failed to get search results: {ex}")
            raise ServiceInvalidRequestError("Failed to get search results.") from ex
        except RequestError as ex:
            logger.error(f"Client error occurred: {ex}")
            raise ServiceInvalidRequestError("A client error occurred while getting search results.") from ex
        except Exception as ex:
            logger.error(f"An unexpected error occurred: {ex}")
            raise ServiceInvalidRequestError("An unexpected error occurred while getting search results.") from ex

    def _validate_options(self, options: SearchOptions) -> None:
        if options.top > 10:
            raise ServiceInvalidRequestError("count value must be less than or equal to 10.")

    def _parse_filter_lambda(self, filter_lambda: Callable | str) -> list[dict[str, str]]:
        """Parse a string lambda or string expression into a list of {field: value} dicts using AST."""
        expr = filter_lambda if isinstance(filter_lambda, str) else getsource(filter_lambda).strip()
        tree = ast.parse(expr, mode="eval")
        node = tree.body
        visitor = SearchLambdaVisitor(valid_parameters=QUERY_PARAMETERS)
        visitor.visit(node)
        return visitor.filters

    def _build_query(self, query: str, options: SearchOptions) -> str:
        params = {
            "key": self.settings.api_key.get_secret_value(),
            "cx": self.settings.engine_id,

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Read the logged 'An unexpected error occurred: <ex>' line to see the root exception.
  2. Inspect ex.__cause__ for the precise failure (often a pydantic ValidationError or JSONDecodeError).
  3. If the response schema changed, pin or upgrade semantic_kernel and report the schema drift.
  4. Reproduce the raw request with httpx/curl to see the actual body Google returned.

Example fix

# before
results = await google.search('skates')  # non-JSON body -> [1305]

# after
import logging
logging.getLogger('semantic_kernel.connectors.google_search').setLevel(logging.DEBUG)
try:
    results = await google.search('skates')
except ServiceInvalidRequestError as ex:
    root = ex.__cause__
    logging.error('google search root cause: %r', root)
    raise
Defensive patterns

Strategy: try-catch

Try / catch

import logging
from semantic_kernel.exceptions import ServiceInvalidRequestError

try:
    results = await google.search(query, top=top)
except ServiceInvalidRequestError as ex:
    root = ex.__cause__
    logging.exception('Google search failed unexpectedly; root cause: %r', root)
    raise

Prevention

When it happens

Trigger: 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.

Common situations: Captive portals returning HTML; Google API deprecating/adding fields; transient CDN weirdness; upstream library version drift.

Related errors


AI-assisted analysis of microsoft/semantic-kernel@c028a0c7dc (2026-08-13). Data as JSON: /api/errors/e822d5490ddb7e81. Report an issue: GitHub.