liveBook · Manning

Top-k sampling

As explained in Spring AI in Action

Top-k is a language-model generation parameter that limits token candidates to a specified count of the highest-probability tokens.

Top-k limits a choice to a fixed number of highest-probability candidates. In language generation, it narrows the tokens eligible for random selection; in document retrieval, it specifies how many similar documents to return. section 3.4.1 section 4.4.1

Use top-k to control the size of a candidate set:

  • Set generation top-k alongside temperature or Top-P when configuring ChatOptions, either globally in application.properties or programmatically. section 3.4.1
  • Set retrieval top-k on SearchRequest to return at most the requested number of most-similar documents. section 4.4.1
  • Balance retrieval coverage against prompt size: larger values add context and token cost, while smaller values may omit information needed for a correct answer. section 4.4.1

Spring AI configuration

Configure generation with spring.ai.ollama.chat.options.top-k=4 or ChatOptions.builder().topK(4).build(). Configure retrieval with SearchRequest.builder().query(question).topK(6).build(), optionally combining it with metadata filtering and a similarity threshold. section 3.4.1 section 4.4.1

ChatOptions chatOptions = ChatOptions.builder()
    .topK(4)
    .build();

Shows the programmatic ChatOptions setting for limiting generation candidates. section 3.4.1

var searchRequest = SearchRequest.builder()
    .query(question)
    .topK(6)
    .filterExpression(
        new FilterExpressionBuilder()
            .eq("gameTitle", normalizeGameTitle(gameName)).build())
    .build();

Shows a retrieval request returning at most six documents while filtering results by game metadata. section 4.4.1

How Spring AI in Action covers it

How deep it goes
Defines candidate or result counts and configuration trade-offs, but stops short of mathematical sampling or retrieval internals.
Examples
Uses ChatOptions.topK(4), spring.ai.ollama.chat.options.top-k=4, and SearchRequest.topK(6) in filtered game-rules retrieval.
What it assumes
Assumes familiarity with Spring AI chat clients, prompts, vector stores, and similarity search while treating top-k behavior concretely.
What you can do after
Operate/configure Spring AI generation and retrieval by setting top-k globally, per client, per prompt, or on SearchRequest.
How it connects
Connects temperature and Top-P for generation, and similarity search, metadata filtering, similarity threshold, and vector stores for retrieval.

Also explained in

Compare how 8 books explain top-k sampling →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring AI in Action. The section links point to the parts of the book it draws on.