mem0ai/mem0 · error · ValueError
Invalid filter key: {key!r}
Error message
Invalid filter key: {key!r} What it means
BaiduDB._create_filter raises ValueError when a metadata filter key fails the _SAFE_FILTER_KEY regex ^[a-zA-Z_][a-zA-Z0-9_]*$. Because keys are interpolated directly into a SQL-like expression metadata["key"] = value, non-identifier keys (spaces, dots, hyphens, leading digits, empty strings) are rejected to prevent injection into the Baidu query language.
Source
Thrown at mem0/vector_stores/baidu.py:418
)
except Exception as e:
logger.warning(f"Error resetting table: {e}")
raise
def _create_filter(self, filters: dict) -> str:
"""
Create filter expression for queries.
Args:
filters (dict): Filter conditions.
Returns:
str: Filter expression.
"""
conditions = []
for key, value in filters.items():
if not self._SAFE_FILTER_KEY.match(key):
raise ValueError(f"Invalid filter key: {key!r}")
if isinstance(value, str):
escaped = value.replace("\\", "\\\\").replace('"', '\\"')
conditions.append(f'metadata["{key}"] = "{escaped}"')
elif isinstance(value, (int, float, bool)):
conditions.append(f'metadata["{key}"] = {value}')
else:
raise ValueError(
f"Filter value for {key!r} must be str, int, float, or bool, "
f"got {type(value).__name__}"
)
return " AND ".join(conditions)
View on GitHub (pinned to 001c235229)
Solutions
- Rename the metadata key to a plain identifier (letters, digits, underscore, not starting with a digit) both in stored payloads and in filters.
- Sanitize keys before calling search: re.sub(r'[^A-Za-z0-9_]', '_', key).
- Drop or reject non-conforming keys early at the API boundary instead of letting the vector store throw.
Example fix
# before
results = db.search(query="...", vectors=[...], filters={"user-id": "alice"}) # ValueError
# after
results = db.search(query="...", vectors=[...], filters={"user_id": "alice"}) Defensive patterns
Strategy: validation
Validate before calling
import re
_SAFE_KEY = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*$")
def sanitize_filters(filters: dict) -> dict:
out = {}
for k, v in (filters or {}).items():
if not _SAFE_KEY.match(k or ""):
k2 = re.sub(r"[^A-Za-z0-9_]", "_", str(k))
if not re.match(r"^[A-Za-z_]", k2):
k2 = "f_" + k2
k = k2
out[k] = v
return out
db.search(query, vectors, filters=sanitize_filters(filters)) Type guard
def has_safe_filter_keys(filters: dict) -> bool:
import re
return all(isinstance(k, str) and re.match(r"^[a-zA-Z_][a-zA-Z0-9_]*$", k) for k in (filters or {})) Prevention
- Restrict stored metadata keys to identifier-safe names at write time.
- Never build filter keys from raw user input.
- Centralize filter normalization in one helper reused by every provider call.
When it happens
Trigger: Calling search/get on BaiduDB with filters={'user-id': 'x'}, {'meta.key': 'v'}, {'2key': 1}, or any key containing characters outside [A-Za-z0-9_] or starting with a digit. Only runs when filters is a non-empty dict.
Common situations: Passing structured metadata keys that came from JSON payloads with dots/hyphens; copying filter syntax from another provider (e.g. Qdrant nested 'metadata.field' paths); machine-generated keys from user data.
Related errors
- Invalid filter key: ${key}
- Filter value for ${key} must be str, int, float, or bool, go
- Invalid filter key: ${JSON.stringify(key)}
- Invalid filter key: ${JSON.stringify(key)}
- Filter list for '${key}' contains an object, which may conta
AI-assisted analysis of mem0ai/mem0@001c235229 (2026-08-15).
Data as JSON: /api/errors/8596f53551843744.
Report an issue: GitHub.