{"record":{"id":"fb7a90a80430bcb3","repo":"mem0ai/mem0","slug":"top-k-must-be-a-valid-integer","errorCode":null,"errorMessage":"top_k must be a valid integer","messagePattern":"top_k must be a valid integer","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"mem0/memory/main.py","lineNumber":232,"sourceCode":"    Validates search parameters.\n\n    Args:\n        threshold: Similarity threshold (must be between 0 and 1)\n        top_k: Number of results to return (must be non-negative integer)\n\n    Raises:\n        ValueError: If threshold or top_k are invalid\n    \"\"\"\n    if threshold is not None:\n        if not isinstance(threshold, (int, float)):\n            raise ValueError(\"threshold must be a valid number\")\n        if threshold < 0 or threshold > 1:\n            raise ValueError(\n                f\"Invalid threshold: {threshold}. Must be between 0 and 1 (inclusive).\"\n            )\n    if top_k is not None:\n        if not isinstance(top_k, int) or isinstance(top_k, bool):\n            raise ValueError(\"top_k must be a valid integer\")\n        if top_k < 0:\n            raise ValueError(\n                f\"Invalid top_k: {top_k}. Must be a non-negative integer.\"\n            )\n\n\ndef _validate_and_trim_search_query(query: str) -> str:\n    \"\"\"\n    Validates and normalizes a search query before embedding/vector search.\n\n    Raises:\n        ValueError: If query is not a string or is empty/whitespace-only.\n    \"\"\"\n    if not isinstance(query, str):\n        raise ValueError(\"Invalid query: must be a non-empty string.\")\n    trimmed = query.strip()\n    if not trimmed:\n        raise ValueError(\"Invalid query: cannot be empty or whitespace-only.\")","sourceCodeStart":214,"sourceCodeEnd":250,"githubUrl":"https://github.com/mem0ai/mem0/blob/001c235229be8795e3834520467bd0d661ed8f34/mem0/memory/main.py#L214-L250","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","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."],"exampleFix":"# before\ntop_k = os.environ.get(\"MEM0_TOP_K\", 5)  # str at runtime\nm.search(q, filters=f, top_k=top_k)\n\n# after\ntop_k = int(os.environ.get(\"MEM0_TOP_K\", 5))\nm.search(q, filters=f, top_k=top_k)","handlingStrategy":"type-guard","validationCode":"top_k = int(top_k)  # after confirming it is numeric\nif not isinstance(top_k, int) or isinstance(top_k, bool):\n    raise ValueError(f\"top_k must be int, got {type(top_k).__name__}\")","typeGuard":"def is_valid_top_k(k) -> bool:\n    return k is None or (isinstance(k, int) and not isinstance(k, bool) and k >= 0)","tryCatchPattern":null,"preventionTips":["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."],"tags":["validation","search","top-k","typeerror"],"backgroundTag":null,"analyzedSha":"001c235229be8795e3834520467bd0d661ed8f34","analyzedAt":"2026-08-15T01:55:42.685Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}