microsoft/semantic-kernel · error · ServiceInvalidRequestError

count value must be greater than 0.

Error message

count value must be greater than 0.

What it means

A validation guard in _validate_options: Brave's web search count parameter must be at least 1. Passing top <= 0 raises ServiceInvalidRequestError before any network call is made. This is caller-side input validation, not a Brave API response.

Source

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

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

View on GitHub (pinned to c028a0c7dc)

Solutions

  1. Pass top >= 1 (e.g. top=5 default) when calling search.
  2. Clamp user-supplied count to a minimum of 1 before calling search.
  3. Validate pagination inputs upstream so top is never zero or negative.

Example fix

// before
results = await connector.search(query, top=0)
// after
results = await connector.search(query, top=max(1, user_count))
Defensive patterns

Strategy: validation

Validate before calling

if top <= 0:
    raise ValueError("top must be >= 1 for Brave search")
results = await connector.search(query, top=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=0 or a negative number, either directly or via SearchOptions(top=...). The check at brave.py:245-246 fires immediately inside _inner_search.

Common situations: A default of 0 passed from upstream pagination logic, a computed top that underflows to 0, or reusing an options object whose top was zeroed out.

Related errors


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