mem0ai/mem0 · error · ValueError
top_k must be a valid integer
Error message
top_k must be a valid integer
What it means
Raised by _validate_search_params when the 'top_k' argument is not a Python int. Because booleans are explicitly excluded (isinstance(top_k, bool) is rejected even though bool subclasses int), passing True/False, a float like 5.0, a numeric string like '5', or None-like sentinels raises this ValueError. top_k determines how many memories search()/get_all() return, and the SDK requires an exact integer count.
Source
Thrown at mem0/memory/main.py:232
Validates search parameters.
Args:
threshold: Similarity threshold (must be between 0 and 1)
top_k: Number of results to return (must be non-negative integer)
Raises:
ValueError: If threshold or top_k are invalid
"""
if threshold is not None:
if not isinstance(threshold, (int, float)):
raise ValueError("threshold must be a valid number")
if threshold < 0 or threshold > 1:
raise ValueError(
f"Invalid threshold: {threshold}. Must be between 0 and 1 (inclusive)."
)
if top_k is not None:
if not isinstance(top_k, int) or isinstance(top_k, bool):
raise ValueError("top_k must be a valid integer")
if top_k < 0:
raise ValueError(
f"Invalid top_k: {top_k}. Must be a non-negative integer."
)
def _validate_and_trim_search_query(query: str) -> str:
"""
Validates and normalizes a search query before embedding/vector search.
Raises:
ValueError: If query is not a string or is empty/whitespace-only.
"""
if not isinstance(query, str):
raise ValueError("Invalid query: must be a non-empty string.")
trimmed = query.strip()
if not trimmed:
raise ValueError("Invalid query: cannot be empty or whitespace-only.")View on GitHub (pinned to 001c235229)
Solutions
- Convert to int before the call: top_k=int(value).
- Fix config loading so numeric settings are cast to int, not left as strings or floats.
- If the value may legitimately be absent, pass None instead of 0.0 or an empty string.
- Ensure you are not passing a boolean feature flag into top_k.
Example fix
# before
top_k = os.environ.get("MEM0_TOP_K", 5) # str at runtime
m.search(q, filters=f, top_k=top_k)
# after
top_k = int(os.environ.get("MEM0_TOP_K", 5))
m.search(q, filters=f, top_k=top_k) Defensive patterns
Strategy: type-guard
Validate before calling
top_k = int(top_k) # after confirming it is numeric
if not isinstance(top_k, int) or isinstance(top_k, bool):
raise ValueError(f"top_k must be int, got {type(top_k).__name__}") Type guard
def is_valid_top_k(k) -> bool:
return k is None or (isinstance(k, int) and not isinstance(k, bool) and k >= 0) Prevention
- Cast config/env values with int() at load time, not at call time.
- Booleans are rejected explicitly — never route feature flags into top_k.
- Annotate your wrapper signature as Optional[int] and run mypy to catch float/str leaks.
When it happens
Trigger: Calling m.search(query, filters={...}, top_k=5.0); top_k="10" read from an env var or CLI arg without int() conversion; top_k=True passed by a feature-flag miswiring; top_k=numpy.int64(5) is fine (it is an int subclass) but top_k=decimal.Decimal('5') is not.
Common situations: Reading top_k from environment variables or JSON/YAML config (config parsers yield strings or floats); function signatures annotated loosely so a float slips through; pandas/numpy pipelines producing float columns.
Related errors
- Invalid top_k: {top_k}. Must be a non-negative integer.
- Invalid query: must be a non-empty string.
- threshold must be a valid number
- Invalid threshold: ${threshold}. Must be between 0 and 1 (in
- topK must be a valid integer
AI-assisted analysis of mem0ai/mem0@001c235229 (2026-08-15).
Data as JSON: /api/errors/fb7a90a80430bcb3.
Report an issue: GitHub.