chroma-core/chroma · error · ValueError

SparseVector indices must be integers, got {type(idx).__name

Error message

SparseVector indices must be integers, got {type(idx).__name__} at position {i}

What it means

Chroma's SparseVector dataclass (chromadb/base_types.py) fully validates itself in __post_init__ at construction time. This ValueError means at least one element of `indices` is not a true Python `int` as checked by `isinstance(idx, int)`. NumPy scalars (np.int64, np.int32), floats like 3.0, and numeric strings all fail this check even though they look like valid indices; the message names the offending type and its list position.

Source

Thrown at chromadb/base_types.py:63

            raise ValueError(
                f"SparseVector indices and values must have the same length, "
                f"got {len(self.indices)} indices and {len(self.values)} values"
            )

        if self.labels is not None:
            if not isinstance(self.labels, list):
                raise ValueError(
                    f"Expected SparseVector labels to be a list, got {type(self.labels).__name__}"
                )
            if len(self.labels) != len(self.indices):
                raise ValueError(
                    f"SparseVector labels must have the same length as indices and values, "
                    f"got {len(self.labels)} labels, {len(self.indices)} indices"
                )

        for i, idx in enumerate(self.indices):
            if not isinstance(idx, int):
                raise ValueError(
                    f"SparseVector indices must be integers, got {type(idx).__name__} at position {i}"
                )
            if idx < 0:
                raise ValueError(
                    f"SparseVector indices must be non-negative, got {idx} at position {i}"
                )

        for i, val in enumerate(self.values):
            if not isinstance(val, (int, float)):
                raise ValueError(
                    f"SparseVector values must be numbers, got {type(val).__name__} at position {i}"
                )

        # Validate indices are sorted in strictly ascending order
        if len(self.indices) > 1:
            for i in range(1, len(self.indices)):
                if self.indices[i] <= self.indices[i - 1]:
                    raise ValueError(

View on GitHub (pinned to aecdd12c8a)

Solutions

  1. Convert before constructing: indices = [int(i) for i in indices] (and values = [float(v) for v in values]).
  2. If the data comes from a NumPy array, call .tolist() on it - it produces native Python ints/floats.
  3. Use the type name and position in the error message to find the offending element and fix the producer that emits it.

Example fix

// before
import numpy as np
idx = np.argwhere(mask).flatten()  # dtype int64 -> np.int64 elements
sv = SparseVector(indices=list(idx), values=vals)  # ValueError: got int64

// after
idx = np.argwhere(mask).flatten().tolist()  # native Python ints
sv = SparseVector(indices=idx, values=vals)
Defensive patterns

Strategy: validation

Validate before calling

# Normalize before constructing SparseVector
def to_int_indices(indices):
    return [int(i) for i in indices]  # rejects non-numeric garbage loudly

raw = np.argwhere(mask).flatten()
indices = to_int_indices(raw)  # np.int64 -> int
values = [float(v) for v in raw_values]
sv = SparseVector(indices=indices, values=values)

Type guard

from typing import List

def is_int_index_list(xs: object) -> bool:
    """Matches Chroma's check: isinstance(idx, int) for every element."""
    return isinstance(xs, list) and all(isinstance(x, int) for x in xs)

Try / catch

try:
    sv = SparseVector(indices=indices, values=values)
except ValueError as e:
    raise ValueError(f'invalid sparse embedding for doc {doc_id}: {e}') from e

Prevention

When it happens

Trigger: Constructing SparseVector(indices=..., values=...) where indices came from NumPy operations without conversion, e.g. np.argwhere(...).flatten(), indexing a numpy array (arr[i] yields np.int64), or from JSON/YAML/config data where indices were parsed as strings ('3') or floats (3.0).

Common situations: Custom sparse embedders whose tokenizer vocab IDs are NumPy scalars; ML pipelines that pass tensor/array elements straight into Chroma; config- or JSON-driven dimension indices that were never cast to int.

Related errors


AI-assisted analysis of chroma-core/chroma@aecdd12c8a (2026-08-16). Data as JSON: /api/errors/c8cbf4e22f3a1845. Report an issue: GitHub.