microsoft/semantic-kernel · error · ServiceInvalidRequestError

count value must be less than 21.

Error message

count value must be less than 21.

What it means

Brave's web search API caps results at 20 per request; the connector enforces this client-side by rejecting top >= 21 with ServiceInvalidRequestError before the call. This prevents an guaranteed API-side rejection.

Source

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

            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()
        tree = ast.parse(expr, mode="eval")
        node = tree.body
        visitor = SearchLambdaVisitor(valid_parameters=QUERY_PARAMETERS)
        visitor.visit(node)
        return visitor.filters

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Lower top to <= 20 per request.
  2. For more than 20 results, paginate with skip/top across multiple requests (respecting the skip <= 9 cap).
  3. Clamp user-supplied count to 20 before calling search.

Example fix

// before
results = await connector.search(query, top=50)
// after
results = await connector.search(query, top=min(20, user_count))
Defensive patterns

Strategy: validation

Validate before calling

if top > 20:
    raise ValueError("Brave caps results at 20 per request")
results = await connector.search(query, top=min(20, top))

Type guard

def is_valid_top(top: int) -> bool:
    return isinstance(top, int) and 1 <= top <= 20

Prevention

When it happens

Trigger: Calling search() with top >= 21 (e.g. top=50 to fetch a page). The check at brave.py:247-248 fires in _validate_options.

Common situations: Pagination logic requesting large pages, or confusing Brave's per-request cap with the total available results.

Related errors


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