liveBook · Manning

Text chunk

As explained in Generative AI in Action

Chunking is the partitioning of data, especially text, into smaller units for processing, indexing, or retrieval.

A text chunk is a smaller segment of a longer document or passage. In retrieval-augmented generation (RAG), chunking makes large collections easier to search and helps fit retrieved information within an LLM’s limited context window, while leaving room for the response. section 7.7.1 section 7.6

Searching smaller units can retrieve relevant passages more precisely than searching whole documents. When a dense retriever embeds each chunk, chunk size also affects retrieval efficiency. A useful starting rule is to make each chunk understandable to a person without additional context; chunks that are too large or too small can produce inaccurate results. section 7.7.1

Common approaches balance simplicity, context, and redundancy:

  • Fixed length divides text by a set number of words or tokens. It is straightforward but can split information that belongs together. section 7.7.2
  • Sliding windows use fixed-size segments, optionally with overlap. Overlap helps preserve context across boundaries but can introduce redundant information. section 7.7.2 section 7.7.3
  • Punctuation, paragraphs, or document sections provide more natural boundaries, although resulting chunks can vary in size. section 7.7.2
  • Adaptive chunking adjusts chunk size to query length and complexity; retrieval windows or fallback strategies can also change when initial results are unsatisfactory. section 7.7.3
Table 7.3 Chunking approaches
Chunking approach
Description
Fixed length
Divide documents into chunks of a fixed number of words or tokens. This is straightforward but may sometimes split information that ideally should be kept together.
Sliding window
Use a fixed-sized sliding window with or without overlapping data. This can ensure that important boundaries within the text are not missed, but it can also lead to redundancy if there’s significant overlap.
Punctuation based
Divide the text based on punctuation, such as paragraphs or sections. This is less arbitrary than fixed-length chunking and often preserves the semantic integrity of the content. However, it can result in variable chunk sizes.
Topic or section breaks
In structured documents such as Wikipedia articles, natural breaks like sections or subsections can be used to define chunks. This method ensures that the content within a chunk is semantically coherent.
Adaptive
Use algorithms or models that adaptively determine the best way to chunk documents based on their content. This can be more complex but might yield semantically cohesive chunks.

Compare chunking approaches and their boundary and size trade-offs. section 7.7.2

Choose a strategy for the content, query, application, LLM, and embedding model. Short posts may be grouped, while long reports may need splitting. More complex queries may require more context or separate subqueries. Evaluate whether retrieved chunks capture the query’s meaning without exhausting the context window or introducing excessive overlap. section 7.7.2 section 7.7.1 section 7.7.3

Customer service conversation

A mobile provider’s chatbot may begin by helping activate a phone. As the conversation grows, select how much prior dialogue is needed for the next turn: larger chunks can consume the context window and reduce relevance. section 7.7.1

For PDFs, extract content before chunking it. PyPDF2 can extract page text for subsequent processing, but it ignores images, and extraction accuracy depends on how the PDF encodes its text. Tables and images are harder to handle consistently; Azure AI Document Intelligence is one option for extracting document structures. section 7.8

Listing 7.7 Extracting text from PDF
import PyPDF2
def extract_text_from_pdf(pdf_path):
    with open(pdf_path, 'rb') as file:
        reader = PyPDF2.PdfReader(file)
        print("Number of PDF pages:", len(reader.pages))
        text = ""
        for  page in reader.pages:
            page_text = page.extract_text()
            text += page_text
            #print(page_text)
    return text

See a PyPDF2 example that extracts text from PDF pages; the extracted text still needs to be chunked. section 7.8

Unstructured provides preprocessing pipelines, while LangChain and Semantic Kernel support common chunking techniques and configurable overlap. In enterprise RAG, assess accuracy, performance, cost, privacy, security, and governance together rather than treating chunk size as an isolated setting. section 10.4.2 section 7.6 section 7.7.2

How Generative AI in Action covers it

How deep it goes
Compares boundary and size strategies, selection factors, and adaptive retrieval, with PDF extraction examples.
Examples
Illustrates conversational context with a mobile-provider chatbot and PDF extraction with PyPDF2.
What you can do after
Evaluate chunking strategies for content and query needs, including overlap, context limits, and PDF extraction constraints.
How it connects
Connects chunking to retrieval-augmented generation, embeddings, vector search, and context windows.

Also explained in

Compare how 20 books explain text chunk →

Related concepts

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