chroma-core/chroma · error · ValueError

Invalid task: {self.task}

Error message

Invalid task: {self.task}

What it means

HuggingFaceSparseEmbeddingFunction.__call__ dispatches on self.task: 'document' calls SparseEncoder.encode_document, 'query' calls encode_query; anything else (including None, since task is Optional) falls into the else branch and raises ValueError(f"Invalid task: {self.task}"). The constructor parameter is only typed as Literal["document","query"] (TaskType), so an invalid value is not caught at construction time — it surfaces on the first add/query. The default task is 'document'.

Source

Thrown at chromadb/utils/embedding_functions/huggingface_sparse_embedding_function.py:90

            Embeddings for the documents.
        """
        try:
            from sentence_transformers import SparseEncoder
        except ImportError:
            raise ValueError(
                "The sentence_transformers python package is not installed. Please install it with `pip install sentence_transformers`"
            )
        model = cast(SparseEncoder, self._model)
        if self.task == "document":
            embeddings = model.encode_document(
                list(input),
            )
        elif self.task == "query":
            embeddings = model.encode_query(
                list(input),
            )
        else:
            raise ValueError(f"Invalid task: {self.task}")

        sparse_vectors: SparseVectors = []

        for vec in embeddings:
            # Convert sparse tensor to dense array if needed
            if hasattr(vec, "to_dense"):
                vec_dense = vec.to_dense().numpy()
            else:
                vec_dense = vec.numpy() if hasattr(vec, "numpy") else np.array(vec)

            nz = np.where(vec_dense != 0)[0]
            sparse_vectors.append(
                normalize_sparse_vector(
                    indices=nz.tolist(), values=vec_dense[nz].tolist()
                )
            )

        return sparse_vectors

View on GitHub (pinned to aecdd12c8a)

Solutions

  1. Use exactly 'document' for indexing documents and 'query' for queries: HuggingFaceSparseEmbeddingFunction(model_name=..., device=..., task='document')
  2. Omit the task argument entirely (default is 'document') instead of passing None
  3. To use different tasks for documents vs queries, keep task='document' and pass query_config={'task': 'query'}

Example fix

# before
ef = HuggingFaceSparseEmbeddingFunction(
    model_name="prithivida/Splade_PP_en_v1", device="cpu", task="docs"  # invalid
)

# after
ef = HuggingFaceSparseEmbeddingFunction(
    model_name="prithivida/Splade_PP_en_v1", device="cpu", task="document",
    query_config={"task": "query"},
)
Defensive patterns

Strategy: validation

Validate before calling

VALID_TASKS = {"document", "query"}

def make_ef(task: str):
    if task not in VALID_TASKS:
        raise ValueError(f"task must be one of {sorted(VALID_TASKS)}, got {task!r}")
    return HuggingFaceSparseEmbeddingFunction(
        model_name="prithivida/Splade_PP_en_v1", device="cpu", task=task
    )

Type guard

from typing import Literal

Task = Literal["document", "query"]

def is_valid_task(t: object) -> bool:
    return t in ("document", "query")

Try / catch

try:
    ef(docs)
except ValueError as e:
    if str(e).startswith("Invalid task:"):
        log.error("task must be 'document' or 'query', got %s", ef.task)
        raise
    raise

Prevention

When it happens

Trigger: Passing task='docs', 'search_document', 'embedding', or task=None to the constructor and then calling the function or collection.add(); also copying a task name valid for a different EF (e.g. Nomic's 'search_document') into this one.

Common situations: Porting config between embedding functions that use different task vocabularies; explicitly passing task=None expecting the default; typos from hand-written YAML/JSON config dicts fed to the constructor.

Related errors


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