mem0ai/mem0 · error · ValueError

Invalid query: cannot be empty or whitespace-only.

Error message

Invalid query: cannot be empty or whitespace-only.

What it means

Raised by _validate_and_trim_search_query when the query is a string but contains only whitespace after .strip() (e.g. '', ' ', '\n\t'). An empty query would produce a meaningless embedding, so the SDK rejects it up front. Note the helper also trims the query, so valid queries are normalized to stripped text before embedding.

Solutions

  1. Check query.strip() in your UI/wrapper before calling search and treat it as a no-op.
  2. Fall back to a default retrieval query (e.g. last user message) when the computed query is blank.
  3. Trim inputs at ingest time so stored/derived text is never whitespace-only.
  4. Return an empty result list yourself instead of relying on the exception.

Example fix

# before
results = m.search(raw_input, filters=f)  # raw_input = "   "

# after
q = (raw_input or "").strip()
results = m.search(q, filters=f) if q else []
Defensive patterns

Strategy: validation

Validate before calling

q = (query or "").strip()
if not q:
    return []  # or raise your own domain error
results = m.search(q, filters=f)

Type guard

def is_searchable_query(q) -> bool:
    return isinstance(q, str) and len(q.strip()) > 0

Prevention

When it happens

Trigger: m.search('', filters=...); m.search(' ', ...); a query built by string formatting where a variable was empty: f"{prefix} {suffix}" with both empty; user pressing Enter on an empty chat input that is forwarded directly; whitespace-only text extracted from a document chunk.

Common situations: Chat/RAG frontends forwarding empty user input; PDF/web scrapers yielding whitespace-only chunks that get searched; f-string templates with optional parts all empty.

Related errors


AI-assisted analysis of mem0ai/mem0@001c235229 (2026-08-15). Data as JSON: /api/errors/7c3b4a8cd63c8069. Report an issue: GitHub.

Appendix: source

Thrown at mem0/memory/main.py:250

            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.")
    return trimmed


def _is_sensitive_field(field_name: str) -> bool:
    """Check if a field should be redacted for telemetry safety.

    Uses a layered approach:
    1. Runtime fields (allowlist) — always preserved, highest priority.
    2. Exact deny list — known secret field names.
    3. Suffix deny list — catches patterns like db_password, auth_secret, etc.
    """
    name = field_name.lower().strip()
    if name in _RUNTIME_FIELDS:
        return False
    if name in _SENSITIVE_FIELDS_EXACT:
        return True
    return any(name.endswith(suffix) for suffix in _SENSITIVE_SUFFIXES)

View on GitHub (pinned to 001c235229)