mem0ai/mem0 · error · ValueError

Unsupported metric_type: {distance}

Error message

Unsupported metric_type: {distance}

What it means

BaiduDB.create_col raises ValueError when the distance string does not exactly match any pymochow MetricType enum member NAME. The loop compares the raw string against MetricType.__members__ keys (e.g. 'COSINE', 'L2', 'IP'), so it is case-sensitive: 'cosine' fails while 'COSINE' passes, and unsupported metrics like 'euclidean' fail outright.

Source

Thrown at mem0/vector_stores/baidu.py:133

            vector_size (int): Dimension of the vector.
            distance (str): Metric type for similarity search.
        """
        # Check if table already exists
        try:
            tables = self._database.list_table()
            table_exists = any(table.table_name == name for table in tables)
            if table_exists:
                logger.info(f"Table {name} already exists. Skipping creation.")
                self._table = self._database.describe_table(name)
                return

            # Convert distance string to MetricType enum
            metric_type = None
            for k, v in MetricType.__members__.items():
                if k == distance:
                    metric_type = v
            if metric_type is None:
                raise ValueError(f"Unsupported metric_type: {distance}")

            # Define table schema
            fields = [
                Field(
                    "id", FieldType.STRING, primary_key=True, partition_key=True, auto_increment=False, not_null=True
                ),
                Field("vector", FieldType.FLOAT_VECTOR, dimension=vector_size),
                Field("metadata", FieldType.JSON),
            ]

            # Create vector index
            indexes = [
                VectorIndex(
                    index_name="vector_idx",
                    index_type=IndexType.HNSW,
                    field="vector",
                    metric_type=metric_type,
                    params=HNSWParams(m=16, efconstruction=200),

View on GitHub (pinned to 001c235229)

Solutions

  1. Pass the exact enum member name in uppercase, e.g. distance='COSINE' (check pymochow's MetricType for the accepted names such as COSINE/L2/IP).
  2. If the string comes from shared config, uppercase/normalize it before it reaches BaiduDB: distance.strip().upper().
  3. Verify available names at runtime: python -c "from pymochow.model.table import MetricType; print(list(MetricType.__members__))".

Example fix

# before
BaiduDB(..., distance_metric or config with distance="cosine")  # ValueError

# after
config = {"distance": "COSINE", ...}  # exact MetricType member name
Defensive patterns

Strategy: validation

Validate before calling

from pymochow.model.table import MetricType

VALID_METRICS = set(MetricType.__members__)

def normalize_distance(distance: str) -> str:
    d = distance.strip().upper()
    if d not in VALID_METRICS:
        raise ValueError(f"distance must be one of {sorted(VALID_METRICS)}, got {distance!r}")
    return d

distance = normalize_distance(cfg["distance"])  # before creating BaiduDB

Type guard

def is_valid_baidu_metric(distance: str) -> bool:
    return isinstance(distance, str) and distance.strip().upper() in MetricType.__members__

Prevention

When it happens

Trigger: Calling create_col (or constructing BaiduDB with a new collection name) with distance='cosine' (lowercase), 'euclidean', or any string that is not an exact MetricType member name. Note many other mem0 vector stores accept lowercase distance strings, so config copied between providers often trips this.

Common situations: Reusing a distance='cosine' config written for Qdrant/Chroma against the Baidu backend; upgrading pymochow where MetricType member names changed; passing a distance value sourced from user input or a shared config file.

Related errors


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