microsoft/graphrag · error · ValueError

k must be an integer > 0

Error message

k must be an integer > 0

What it means

When using DocSelectionType.AUTO chunk selection in GraphRAG prompt tuning (load_docs_in_chunks), a subsampling size k must be supplied and be a positive integer. AUTO mode samples min(k, len(chunks)) documents to embed for clustering-based selection, so k=None or k<=0 makes sampling impossible and raises this ValueError.

Source

Thrown at packages/graphrag/graphrag/prompt_tune/loader/input.py:83

        doc_dict = dataclasses.asdict(doc)
        chunks = chunk_document(doc_dict, chunker)
        all_chunks.extend(chunks)

    chunks_df = pd.DataFrame({"text": all_chunks})

    # Depending on the select method, build the dataset
    if limit <= 0 or limit > len(chunks_df):
        logger.warning(f"Limit out of range, using default number of chunks: {LIMIT}")  # noqa: G004
        limit = LIMIT

    if select_method == DocSelectionType.TOP:
        chunks_df = chunks_df[:limit]
    elif select_method == DocSelectionType.RANDOM:
        chunks_df = chunks_df.sample(n=limit)
    elif select_method == DocSelectionType.AUTO:
        if k is None or k <= 0:
            msg = "k must be an integer > 0"
            raise ValueError(msg)

        """Convert text chunks into dense text embeddings."""
        sampled_text_chunks = chunks_df.sample(n=min(n_subset_max, len(chunks_df)))[
            "text"
        ].tolist()

        embedding_results = await run_embed_text(
            sampled_text_chunks,
            callbacks=NoopWorkflowCallbacks(),
            model=model,
            tokenizer=tokenizer,
            batch_size=config.embed_text.batch_size,
            batch_max_tokens=config.embed_text.batch_max_tokens,
            num_threads=config.concurrent_requests,
        )
        embeddings = np.array(embedding_results.embeddings)
        chunks_df = _sample_chunks_from_embeddings(chunks_df, embeddings, k=k)

View on GitHub (pinned to f40e9a26ce)

Solutions

  1. Pass a positive integer for chunk_size/k, e.g. load_docs_in_chunks(..., select_method=DocSelectionType.AUTO, chunk_size=200)
  2. If you want all/limited/random selection, use DocSelectionType.ALL, TOP, or RANDOM which don't require k
  3. Validate k before calling: if using user input, coerce to int and check > 0

Example fix

# before
load_docs_in_chunks(df, select_method=DocSelectionType.AUTO, k=None)
# after
load_docs_in_chunks(df, select_method=DocSelectionType.AUTO, k=200)
Defensive patterns

Strategy: validation

Validate before calling

k = int(k) if k is not None else None
if select_method == DocSelectionType.AUTO and (k is None or k <= 0):
    k = 200  # sane default
chunks = load_docs_in_chunks(df, select_method=select_method, chunk_size=k)

Type guard

def is_valid_k(k: object) -> bool:
    return isinstance(k, int) and not isinstance(k, bool) and k > 0

Prevention

When it happens

Trigger: Calling load_docs_in_chunks(..., select_method=DocSelectionType.AUTO) with chunk_size/k omitted (None) or set to 0 or a negative number; programmatic calls to generate_indexing_prompts that forward a user-supplied k without validation.

Common situations: CLI prompt-tuning runs where --chunk-size wasn't passed with auto selection; passing k as a string like '0'; refactors where the k parameter default changed to None.

Understand the failure class

Background: "Must be a positive integer", "Invalid value", "Unsupported": the invalid-argument-value error family, when a library rejects the value you pass — this error's family across 35 libraries.

Related errors


AI-assisted analysis of microsoft/graphrag@f40e9a26ce (2026-08-27). Data as JSON: /api/errors/11e343671d6671e7. Report an issue: GitHub.