langchain-ai/langchain · error · ValueError

Batch size must be a positive integer, got {size}.

Error message

Batch size must be a positive integer, got {size}.

What it means

Raised by the internal `_batch()` helper in `langchain_core.indexing.api`. `aindex`/indexing pipelines split the document stream into fixed-size chunks for batched writes; a chunk size of zero or a negative number would produce empty or infinite batches, so it is rejected upfront with a `ValueError`. The message interpolates the offending size.

Source

Thrown at libs/core/langchain_core/indexing/api.py:95

    if algorithm == "sha1":
        _warn_about_sha1()
    hash_value = _calculate_hash(input_string, algorithm)
    return uuid.uuid5(NAMESPACE_UUID, hash_value)


def _hash_nested_dict(
    data: dict[Any, Any], *, algorithm: Literal["sha1", "sha256", "sha512", "blake2b"]
) -> uuid.UUID:
    """Hash a nested dictionary to a UUID using the configured algorithm."""
    serialized_data = json.dumps(data, sort_keys=True)
    return _hash_string(serialized_data, algorithm=algorithm)


def _batch(size: int, iterable: Iterable[T]) -> Iterator[list[T]]:
    """Utility batching function."""
    if size <= 0:
        msg = f"Batch size must be a positive integer, got {size}."
        raise ValueError(msg)
    it = iter(iterable)
    while True:
        chunk = list(islice(it, size))
        if not chunk:
            return
        yield chunk


async def _abatch(size: int, iterable: AsyncIterable[T]) -> AsyncIterator[list[T]]:
    """Utility batching function."""
    if size <= 0:
        msg = f"Batch size must be a positive integer, got {size}."
        raise ValueError(msg)
    batch: list[T] = []
    async for element in iterable:
        if len(batch) < size:
            batch.append(element)

View on GitHub (pinned to e32fa9a52e)

Solutions

  1. Set an explicit positive batch_size, e.g. `index(vs, docs, record_manager, batch_size=100)`.
  2. Clamp computed values: `batch_size = max(1, computed)`.
  3. Validate configuration at startup so the failure surfaces before indexing begins.

Example fix

# before
index(vs, docs, rm, batch_size=len(docs) // num_workers)  # 0 when len(docs) < workers

# after
index(vs, docs, rm, batch_size=max(1, len(docs) // num_workers))
Defensive patterns

Strategy: validation

Validate before calling

batch_size = batch_size if isinstance(batch_size, int) and batch_size > 0 else 100
index(vs, docs, rm, batch_size=batch_size, cleanup="full")

Type guard

def is_valid_batch_size(n) -> bool:
    return isinstance(n, int) and not isinstance(n, bool) and n > 0

Prevention

When it happens

Trigger: Calling `index()`/`aindex()` with `batch_size=0` or a negative number, or with a value computed at runtime (e.g. `max(1, n // workers)` where n is 0 yields... actually that clamps; more typically `n // workers` with small n yields 0). Also direct use of `_batch` in custom code.

Common situations: Deriving batch_size from a config/env var that defaults to 0; dividing document count by a large concurrency factor; passing `batch_size=None` through untyped code that coerces to 0.

Related errors


AI-assisted analysis of langchain-ai/langchain@e32fa9a52e (2026-08-14). Data as JSON: /api/errors/14ae7646622e14a2. Report an issue: GitHub.