deepset-ai/haystack · error · ValueError
n_expansions must be positive
Error message
n_expansions must be positive
What it means
QueryExpander.__init__ requires n_expansions (number of alternative queries the LLM should generate) to be a positive integer. Zero or negative values would ask the model to produce no/non-sensical expansions, so construction fails fast.
Source
Thrown at haystack/components/query/query_expander.py:110
chat_generator: ChatGenerator | None = None,
prompt_template: str | None = None,
n_expansions: int = 4,
include_original_query: bool = True,
) -> None:
"""
Initialize the QueryExpander component.
:param chat_generator: The chat generator component to use for query expansion.
If None, a default OpenAIChatGenerator with gpt-4.1-mini model is used.
:param prompt_template: Custom [PromptBuilder](https://docs.haystack.deepset.ai/docs/promptbuilder)
template for query expansion. The template should instruct the LLM to return a JSON response with the
structure: `{"queries": ["query1", "query2", "query3"]}`. The template should include 'query' and
'n_expansions' variables.
:param n_expansions: Number of alternative queries to generate (default: 4).
:param include_original_query: Whether to include the original query in the output.
"""
if n_expansions <= 0:
raise ValueError("n_expansions must be positive")
self.n_expansions = n_expansions
self.include_original_query = include_original_query
if chat_generator is None:
self.chat_generator: ChatGenerator = OpenAIChatGenerator(
model="gpt-4.1-mini",
generation_kwargs={
"temperature": 0.7,
"response_format": {
"type": "json_schema",
"json_schema": {
"name": "query_expansion",
"schema": {
"type": "object",
"properties": {"queries": {"type": "array", "items": {"type": "string"}}},
"required": ["queries"],
"additionalProperties": False,View on GitHub (pinned to e318778c9b)
Solutions
- Pass a positive integer, e.g. QueryExpander(n_expansions=4) (default).
- Validate/clamp user input: max(1, requested).
- Omit the parameter to keep the default of 4.
Example fix
// before expander = QueryExpander(n_expansions=0) // after expander = QueryExpander(n_expansions=4)
Defensive patterns
Strategy: validation
Validate before calling
if n_expansions <= 0:
raise ValueError(f'n_expansions must be positive, got {n_expansions}') Type guard
def is_positive_int(v) -> bool:
return isinstance(v, int) and v > 0 Try / catch
try:
expander = QueryExpander(n_expansions=n)
except ValueError as e:
logger.error('Invalid n_expansions: %s', e)
expander = QueryExpander() # default 4 Prevention
- Clamp user-facing inputs: max(1, requested).
- Don't use 0 as 'unset'; use None/omit the parameter.
- Validate app settings at startup, not at first query.
When it happens
Trigger: QueryExpander(n_expansions=0), negative values, or a variable computed from user/config input that resolved to <= 0.
Common situations: App settings exposing 'number of query variations' to end users who enter 0; config defaults of 0 meaning 'unset' elsewhere but invalid here.
Understand the failure class
Background: "must be positive", "Invalid value": how libraries reject invalid parameter values (ValueError, ArgumentError, INVALID_PARAMETER_VALUE) — this error's family across 28 libraries.
Related errors
- header_split_levels must be a non-empty list.
- min_effective_lines must be at least 1.
- max_effective_lines must be at least 1.
- expected_chars_per_line must be at least 1.
- oversized_factor must be at least 1.
AI-assisted analysis of deepset-ai/haystack@e318778c9b (2026-08-30).
Data as JSON: /api/errors/5f8673fbd580bb10.
Report an issue: GitHub.