chroma-core/chroma · error · ValueError

Expected requested number of results to be a int, got {n_res

Error message

Expected requested number of results to be a int, got {n_results}

What it means

validate_n_results requires n_results to be a Python int. A string ("5"), float (5.0), numpy integer (np.int64(5)), or None fails the isinstance check and raises this ValueError. Note that bool passes (bool subclasses int) but is almost never what you want.

Source

Thrown at chromadb/api/types.py:1362

        # Get the valid items from the Literal type inside the List
        valid_items = get_args(get_args(Include)[0])
        if item not in valid_items:
            raise ValueError(
                f"Expected include item to be one of {', '.join(valid_items)}, got {item}"
            )

        if dissalowed is not None and any(item == e for e in dissalowed):
            raise ValueError(
                f"Include item cannot be one of {', '.join(dissalowed)}, got {item}"
            )


def validate_n_results(n_results: int) -> int:
    """Validates n_results to ensure it is a positive Integer. Since hnswlib does not allow n_results to be negative."""
    # Check Number of requested results
    if not isinstance(n_results, int):
        raise ValueError(
            f"Expected requested number of results to be a int, got {n_results}"
        )
    if n_results <= 0:
        raise TypeError(
            f"Number of requested results {n_results}, cannot be negative, or zero."
        )
    return n_results


def validate_embeddings(embeddings: Embeddings) -> Embeddings:
    """Validates embeddings to ensure it is a list of numpy arrays of ints, or floats"""
    if not isinstance(embeddings, (list, np.ndarray)):
        raise ValueError(
            f"Expected embeddings to be a list, got {type(embeddings).__name__}"
        )
    if len(embeddings) == 0:
        raise ValueError(
            f"Expected embeddings to be a list with at least one item, got {len(embeddings)} embeddings"

View on GitHub (pinned to aecdd12c8a)

Solutions

  1. Coerce before the call: n_results=int(n_results)
  2. Parse CLI/HTTP params explicitly: parser.add_argument('--k', type=int)
  3. Guard numpy scalars: int(np.int64(k)) — numpy integers are not Python ints and fail the isinstance check

Example fix

# before
k = config.get("top_k", 5.0)
results = collection.query(query_embeddings=[q], n_results=k)

# after
k = int(config.get("top_k", 5))
results = collection.query(query_embeddings=[q], n_results=k)
Defensive patterns

Strategy: type-guard

Validate before calling

def coerce_n_results(n) -> int:
    if isinstance(n, bool):
        raise TypeError("n_results must be an int, not bool")
    if not isinstance(n, int):
        n = int(n)  # accepts "5", 5.0, np.int64(5)
    if n <= 0:
        raise ValueError("n_results must be >= 1")
    return n

res = collection.query(query_embeddings=[q], n_results=coerce_n_results(raw_k))

Type guard

import numpy as np

def is_valid_n_results(n) -> bool:
    return (isinstance(n, int) or isinstance(n, np.integer)) and not isinstance(n, bool) and n > 0

Try / catch

try:
    res = collection.query(query_texts=[q], n_results=k)
except ValueError as e:
    if "requested number of results" in str(e) and str(k).lstrip("+-").isdigit():
        res = collection.query(query_texts=[q], n_results=int(k))
    else:
        raise

Prevention

When it happens

Trigger: collection.query(query_texts=..., n_results="10") from an un-cooked CLI arg or HTTP query param; n_results=5.0 from a config parsed as float; n_results=np.int64(k) from numpy-derived top-k computations.

Common situations: CLI tools and web handlers passing string parameters straight through; YAML/JSON configs where 5 parses as float 5.0; pandas/numpy code computing k as np.int64; LangChain-style wrappers forwarding user input unvalidated.

Related errors


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