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

A catch-all ServiceInvalidRequestError for any exception during the Brave request that is neither an HTTPStatusError nor a RequestError. This guards against unexpected failures (e.g. JSON validation errors from model_validate_json, unexpected SDK exceptions) so the connector never leaks an unhandled exception to the caller.

Source

Thrown at python/semantic_kernel/connectors/brave.py:241

        headers = {
            "X-Subscription-Token": self.settings.api_key.get_secret_value(),
            "user_agent": SEMANTIC_KERNEL_USER_AGENT,
        }
        try:
            async with AsyncClient(timeout=5) as client:
                response = await client.get(url, headers=headers, params=params)
                response.raise_for_status()
                return BraveSearchResponse.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 <= 0:
            raise ServiceInvalidRequestError("count value must be greater than 0.")
        if options.top >= 21:
            raise ServiceInvalidRequestError("count value must be less than 21.")

        if options.skip < 0:
            raise ServiceInvalidRequestError("offset must be greater than or equal to 0.")
        if options.skip > 9:
            raise ServiceInvalidRequestError("offset must be less than 10.")

    def _get_url(self) -> str:
        return DEFAULT_URL

    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()

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Inspect exc.__cause__ to identify the unexpected exception type and message.
  2. If the cause is a pydantic ValidationError, the Brave API response schema may have changed — check for a connector version update.
  3. For unknown transient causes, add a retry with limited attempts and log the underlying exception for diagnosis.

Example fix

// before
results = await connector.search(query)
// after
try:
    results = await connector.search(query)
except ServiceInvalidRequestError as e:
    logger.exception("Brave unexpected error: %s", e.__cause__)
    raise
Defensive patterns

Strategy: try-catch

Try / catch

from semantic_kernel.exceptions import ServiceInvalidRequestError

try:
    results = await connector.search(query)
except ServiceInvalidRequestError as e:
    logger.exception("Unexpected Brave search error: %s", e.__cause__)
    raise

Prevention

When it happens

Trigger: Calling search() and an exception other than HTTPStatusError or RequestError is raised inside the try block at brave.py:228-232 — most commonly a pydantic ValidationError thrown by BraveSearchResponse.model_validate_json when the response body does not match the expected schema, or an unexpected httpx/transport error type.

Common situations: The Brave API returns a malformed/unexpected JSON shape that fails pydantic validation, an unhandled httpx exception type, or a bug in response parsing.

Related errors


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