AI & XML / RAG study series / Part 2: Structured data and intelligent chunking strategies for RAG systems

Structured data and intelligent chunking strategies for RAG systems

Introduction

Retrieval-Augmented Generation (RAG) is considered one of the most promising approaches to enriching language models with dynamic, domain-specific information. Its success depends heavily on how well underlying content is structured, segmented and enriched with metadata. This study examines the crucial role of chunks —logically connected text units—and analyzes how different chunking strategies affect answer quality, contextual understanding and semantic depth in RAG systems.

The central question is: What forms of text structuring best enable high-quality, scalable RAG systems across models? Key strategies such as fixed chunk sizes, recursive chunking, semantic and sentence-based segmentation, agentic chunking and document-oriented methods are introduced and compared practically. Literary and normative texts, such as Franz Kafka’s “Die Verwandlung” or the “Universal Declaration of Human Rights”, serve as illustrative examples.

Beyond segmentation strategies, the study examines handling of metadata, integration of embedding software, technical limitations imposed by token windows and the role of data formats (e.g. PDF, HTML, Markdown, XML). The technological context spans classical transformation methods (XSLT, XML) through modern AI technologies (LLMs, embeddings, vector databases).

A central aim is to derive a structured, robust and future-proof architecture from today’s often fragmented RAG implementation landscape, independent of specific models or proprietary technologies.

Study summary

This study shows that structured data formats and intelligent chunking strategies are crucial to RAG performance. Different methods such as recursive, sentence-based, semantic or agentic chunking allow tailored preparation for different LLMs, provided they rely on cleanly structured, media-neutral source data.

Format analysis shows significant disadvantages in unstructured sources such as PDFs, especially for metadata, context preservation and referenceability. Markdown and XML, by contrast, explicitly structure information, providing a solid basis for automated chunking and semantic analysis.

A scholarly publisher case study shows how a central XML hub, dynamic chunk generation and a Content Delivery Service (CDS) can enable a sustainable, adaptable RAG ecosystem. It particularly highlights separation of data structuring and storage as the key to technological independence and future-proofing.

The study provides theoretical foundations and practical implementation recommendations, including suitable chunk sizes, overlap and redundancy design, semantic enrichment through metadata, and integration of embedding software and vector databases.

Outlook on further studies

Two further investigations follow this study:

  1. Automated chunking from all formats:
    Developing fully automated infrastructure for arbitrary chunking strategies, supported by the Octopus system, which also extracts media-neutral structures from PDFs.

  2. Working with CDS:
    Investigating the role of a Content Delivery Service (CDS) as a semantic mediation layer between structured content and RAG components, using RDF, SPARQL and container-based access concepts (e.g. iiRDS).

These next studies will show how structured content and intelligent architecture can create a powerful, model-agnostic RAG system.

1 Overview of RAG technology

Retrieval-Augmented Generation (RAG) extends classical AI text generation by integrating external knowledge sources. Large language models (LLMs) combine with a retrieval component to incorporate current, domain-specific information dynamically into answers, beyond static pretrained knowledge.

RAG addresses a central limitation of conventional LLMs: they generate syntactically correct, semantically plausible text but struggle with factual accuracy or specialist knowledge outside their training corpus. During answering, RAG retrieves relevant information from a searchable external knowledge base.

1.1 From document processing to indexing

Every RAG system is based on efficient, structured processing of data sources. The process begins with selecting and preparing suitable documents. Source-format diversity and structure are central. Typical formats include PDF, HTML, Markdown and XML. Structured formats such as XML or Markdown explicitly mark semantic information including headings, paragraphs, footnotes or metadata; PDF retains this information only implicitly or may lose it entirely, substantially complicating automation.

Fig. 1.1: Training a RAG system
(Source: https://medium.com/@BitsOfChris/what-is-rag-and-how-can-it-be-used-to-train-llms-on-your-own-data-91a0bab96842)

Figure: Training a RAG system

Content extraction is followed by chunking. Text is divided into smaller units for easier language-model processing. Chunk size may follow word, character or token counts. Tokens are especially relevant because LLMs use them internally and have maximum context lengths. Chunking meets technical limits and improves contextualization. Overlap prevents information discontinuities at segment boundaries.

Optionally, semantic tagging can enrich chunks with topic, author or chapter metadata, facilitating later context-relevant searches. An embedding model then converts chunks to multidimensional vectors representing semantic meaning. Stored in a vector database such as FAISS, ChromaDB or Pinecone, they form the RAG retrieval module’s index.

1.2 From user query to answer generation

A RAG system’s second core component is answering. It starts with a user query in natural language, first converted into a semantic vector using the same or a compatible embedding model, just as in document-chunk indexing.

Fig. 1.2: Querying RAG
(Source: https://medium.com/@BitsOfChris/what-is-rag-and-how-can-it-be-used-to-train-llms-on-your-own-data-91a0bab96842)

Figure: Querying RAG

The next step is retrieval. The query vector is compared with chunks in the vector database to identify text semantically closest to the query, typically using cosine similarity. The most relevant chunks, usually the top N retrievals, become context for the language model.

Finally, the LLM generates an answer using the retrieved chunks, a process termed context-supported generation. The model uses document excerpts as knowledge but formulates its own natural-language answer, combining data-driven precision with linguistic flexibility.

Success depends heavily on chunk quality, embeddings and effective retrieval. A precisely coordinated pipeline linking document preparation, vectorization and answering is essential for practical value.

1.3 Format dependence and model preferences

RAG implementation often underestimates format dependence on the chosen LLM. Models do not process every format equally well. Structured Markdown often improves answers, especially with models that extract and contextualize explicit semantic structures. Its headings, lists, tables and footnotes add a semantic layer readily interpreted by modern LLMs.

Plain text, by contrast, has no semantic markup. It can suffice in some cases but often lacks the depth to represent complex contexts accurately. Data preparation should therefore suit the model architecture and application. A format-adaptive strategy can significantly improve answer quality and should become best practice.

2 What are chunks, and why split text into them?

2.1 What are chunks?

Chunks are small, logically connected text segments into which a larger text is divided. This is especially important when working with large language models (LLMs) such as GPT or Claude. These models process only limited text at once (e.g. 4,000–32,000 tokens), so longer content needs manageable units.

A chunk might contain:

  • 300 words

  • 500 characters

  • 200 tokens (as used by language models)

Strategies depend on model and application: some systems split by paragraphs, others by semantic units or fixed lengths.

Definition 2.1

Comparing tokens and chunks:

Aspect

tokens

Chunks

Granularity

Smallest text unit (e.g. characters, character sequences, word parts, words, symbols, punctuation)

Larger groups of tokens (e.g. clauses, sentences, paragraphs, token-count or semantic units)

Creation

By tokenization

By chunking

Example

["Das", "ist", "ein", "Beispiel", "."]

Or (depending on language model)

["D", "as", " ist", " ein", " Be", "ispiel", "."]

["Das ist ein Beispiel"]

Properties

  • Indivisible processing units

  • Limited token count (“context length”)

  • More computation, higher costs and response times

  • Coherent units of meaning

  • Making long texts processable

  • Optimizing computation and memory needs

2.2 Why chunk text?

There are technical, structural and semantic reasons for splitting text into chunks:

  1. Model limitations
    LLMs support only limited context lengths. Without chunking, longer texts would be unusable.

  2. Easier analysis
    Smaller units are easier to search, analyze and evaluate, for example in information retrieval or embedding creation.

  3. Preserving context
    Intelligent chunking, such as overlapping segments, preserves relationships across boundaries.

  4. More efficient prompting
    Chunks can be selectively included in prompts, giving the model only relevant passages, reducing cost and improving precision.

2.3 Simplified example: chunking Kafka’s “Die Verwandlung”

Original text (opening sentence excerpt):

„Als Gregor Samsa eines Morgens aus unruhigen Träumen erwachte, fand er sich in seinem Bett zu einem ungeheueren Ungeziefer verwandelt.“

Word-based chunking (10-word chunks):

  • Chunk 1: „Als Gregor Samsa eines Morgens aus unruhigen Träumen erwachte fand“

  • Chunk 2: „er sich in seinem Bett zu einem ungeheueren Ungeziefer verwandelt“

Token-based chunking (simplified GPT-4 tokenizer example):

  • Chunk 1: ["Als", "Gregor", "Samsa", "eines", "Morgens", "aus", "unruhigen", "Träumen", "erwachte", "fand"]

  • Chunk 2: ["er", "sich", "in", "seinem", "Bett", "zu", "einem", "ungeheueren", "Ungeziefer", "verwandelt", "."]

Chunking with semantic annotation encoded in JSON

{
  "content": "Als Gregor Samsa eines Morgens ...",
  "metadata": {
    "person": "Gregor Samsa",
    "motiv": "Verwandlung",
    "werk": "Die Verwandlung"
  }
}

Note 2.1

Through chunking, text remains machine-processable and human-interpretable.

For literary works such as Die Verwandlung, it is especially important not to lose relationships of meaning, such as characters, motifs or symbolic elements, when splitting text.

3 Chunk sizes: recommendations for different LLMs

3.1 Chunk size as a strategic control

Choosing chunk size is central to an effective RAG system. It directly affects:

  • how much context the model can process,

  • answer precision and completeness,

  • efficient use of memory and computation.

Oversized chunks may truncate relevant content or embed unnecessary context. Undersized chunks increase chunk counts, complicate retrieval and break relationships.

3.2 Recommended sizes for common LLMs

Model

Maximum context length (tokens)

Recommended chunk size

Comment

GPT-3.5 Turbo

4,096 tokens

200–600 tokens

Leave a 20–30 % buffer

GPT-4 (32k)

32,768 tokens

1,000–2,000 tokens

Relatively large chunks possible

Claude 2

100,000 tokens (theoretical)

1,500–4,000 tokens

Ideal for large contexts

Mistral

8,192 tokens

300–1,000 tokens

Buffer for prompt components

LLaMA 2

4,096–8,192 tokens

300–800 tokens

Tokens highly model-dependent

These are guidelines, not rigid rules. Purpose matters: ordinary question-answer scenarios often need only 300–500 tokens, while semantic search with context aggregation may benefit from larger chunks.

Practical recommendations

  1. Allow a buffer
    At least 20–30 % of context length should remain reserved for prompts, instructions and model responses.

  2. Adapt chunk size dynamically
    Instead of fixed token counts, chunk along semantic boundaries such as paragraphs and subheadings, supplemented by token limits.

  3. Combine size with overlap
    For 600-token chunks, an overlap of 100–150 tokens may smooth context transitions.

  4. Consider analysis and answer type

    • For factual answers: smaller, concise chunks.

    • For creative/analytical tasks: larger chunks, more context.

  5. Test and iterate
    Ideal sizes vary by genre (fiction ≠ research ≠ news). A/B tests or recall/precision measurements help optimize them.

3.3 Why not use maximum context length as chunk size?

3.3.1 What is an LLM’s context length?

The context length of a large language model (LLM) is the maximum number of tokens it can process simultaneously. These tokens include everything passed to the model—not just text content such as a chunk, but also:

  • the prompt (e.g. the question or task),

  • system messages (e.g. role information such as “You are a helpful assistant”),

  • any example answers or other control information,

  • and the model’s answer itself (if fed back in the same context, as in chat models).

Example: GPT-3.5 with 4,096 tokens

Suppose a model such as GPT-3.5 has a maximum context of 4,096 tokens. Passing a chunk of exactly 4,096 tokens causes:

  • There is no space left for the prompt.

  • The model may see only part of the chunk or abort processing.

  • In chat models, the answer may also be truncated or not generated at all because no space remains.

Result: incomplete answers; the model behaves incorrectly or returns nothing.

3.3.2 Why a buffer is necessary

To avoid these problems, allow a 20–30 % buffer of total context length for:

  • Prompt: questions or instructions (“Summarize the following text”, “Answer in simple language”, etc.).

  • System configuration: role assignment, language settings, answer format.

  • Subsequent interactions: earlier chat entries may be sent again.

  • Answer headroom: the model needs room for complete answers.

Example:
For GPT-3.5 (4,096 tokens), the chunk should be no larger than about 2,800–3,000 tokens to leave a reliable buffer for everything else.

3.3.3 Risks of oversized chunks

  • Truncation: the model stops mid-sentence, losing important information.

  • Distorted answers: without a full prompt or answer buffer, responses become inaccurate or hallucinated.

  • System errors: some APIs reject inputs exceeding the context limit entirely.

4 Chunking strategies

Chunking strategies systematically divide large texts into smaller, manageable units. They are central to RAG because LLMs process limited text at once. Depending on purpose and genre, different strategies preserve context, improve discoverability and make answering more efficient. The following eight strategies use literary and normative examples, especially Franz Kafka’s “Die Verwandlung” and the “Universal Declaration of Human Rights”.

4.1 Fixed-size chunking

Fixed-size chunking is one of the simplest basic methods for preparing text for RAG. It divides text into equal-sized chunks regardless of content structure or semantic coherence. Size follows words, characters or tokens according to application; typical settings are 100 words, 500 characters or 300 tokens per chunk.

Its main aim is standardization: uniform division efficiently prepares and processes large text collections, especially in automated pipelines where semantic depth is initially secondary. It is particularly useful under strict length constraints, such as APIs or vector-database storage optimization.

This simplicity sacrifices contextual coherence. Boundaries ignore sentences and paragraphs and may split meaningful units, harming language-model answers when important information spans chunks and context disappears.

An example from Franz Kafka’s “Die Verwandlung” illustrates this: splitting the famous opening sentence into 10-word chunks yields:

{
    "text": "Als Gregor Samsa eines Morgens aus unruhigen Träumen erwachte, fand"
},
{
    "text": "er sich in seinem Bett zu einem ungeheueren Ungeziefer verwandelt."
},
{
    "text": "Er lag auf seinem panzerartig harten Rücken und sah, wenn"
},

Although each chunk is formally segmented correctly, the sentence’s unity is broken, weakening semantic coherence.

Here with tokens and text for easier interpretation:

{
     "text": "Als Gregor Samsa eines Morgens aus",
     "token_ids": [
        77968,
        16431,
        269,
        328,
        4214,
        64,
        37208,
        79160,
        729,
        9608
        ]
},
{
      "text": " unruhigen Träumen erwachte,",
      "token_ids": [
        653,
        2739,
        71,

Despite these weaknesses, fixed-size chunking remains widespread, especially in early preprocessing or combined with overlap and later context reconstruction. Its strengths are simplicity, predictability and efficiency on large corpora, particularly automatically generated PDF chunks whose fixed lengths are easy to calculate. Semantic breaks, split grammatical units and context loss are often deliberately accepted for fast, scalable processing.

Tables are especially problematic: fixed blocks often lose column headings, cell relationships and row connections, making tables semantically “dead”. Models cannot capture or reconstruct them as functional units. Complex layouts in scholarly publications, business reports and standards are especially affected, already prone to fragmentation during PDF parsing. Semantic analysis and AI retrieval answer quality suffer substantially.

Fixed-size chunking also affects semantically meaningful metadata, such as footnotes, citations, marginalia or source references. In body text these often appear outside their semantic context and lose their reference function. For example, a footnote at a paragraph’s end can fall in a separate chunk without its quotation, completely losing meaning for readers and models. This is critical in scholarly or legal texts, where evidence and formal relationships are central to comprehension.

More information on affected structures is in Part 1 of the RAG study series, “Structured versus unstructured data in RAG training: a comparison”.

4.2 Recursive chunking

The recursive chunking is an extended, much more flexible segmentation method based on hierarchical analysis of text structure. Instead of equal-sized units immediately, it divides in stages into the next smaller meaningful or formal unit whenever a defined threshold, such as maximum tokens, is exceeded.

4.2.1 Principle and aim

The method aims to preserve semantic coherence as far as possible while meeting technical limitations, especially language-model token limits. It usually starts with paragraphs or sections. Oversized units are recursively split into sentences. If a sentence is still too long, as with complex nested syntax, a further step splits at token level.

This enables highly adaptive processing that dynamically follows text structure. Large semantic units are not cut mechanically but divided meaningfully wherever possible.

4.2.2 Application and example

A classic example uses Franz Kafka’s “Die Verwandlung”: its famous opening is one very long sentence:

„Als Gregor Samsa eines Morgens aus unruhigen Träumen erwachte, fand er sich in seinem Bett zu einem ungeheuren Ungeziefer verwandelt.“

Fixed chunking could break this sentence awkwardly. Recursion recognizes it as the smallest meaningful unit and does not split it further, since it fits the token limit. A subsequent paragraph of multiple sentences or hundreds of tokens would first be assessed as a chunk, then divided into sentences if too long. Only oversized sentences are split at token level.

4.3 Document-based chunking

Document-based chunking is structure-oriented, consistently following the natural document organization. Unlike word-, character- or token-count approaches, it follows the text’s inherent organization, using formal units such as chapters, paragraphs, subheadings or sections. It aims to retain semantically connected sections completely and preserve contextual connections and logical coherence within the chunk.

4.3.1 Aim and scope

Document-based chunking particularly suits formalized, structured texts found in scholarly articles, laws, reports, textbooks and digital publications. Content typically has clear typographic or structural organization: chapter headings, numbered paragraphs, subheadings or marginalia. Markup languages such as XML, Markdown, LaTeX or automated PDF layout parsing can expose that structure.

Preserving these units ensures that every chunk represents a meaningful content section fully usable for semantic retrieval or LLM processing. It also enables targeted navigation and context control, for example in search or dialogue applications (“Jump to section 3.2”).

4.3.2 Methodology

Technically, document-based chunking uses a structure-aware parser to analyze and segment along predefined structural elements, at different levels depending on source format:

  • In XML files, for example, by <section>, <para>, <div> or <article> elements.

  • In Markdown, by heading levels (#, ##, ###) and paragraph breaks.

Every identified section, such as a paragraph or chapter block, becomes a complete chunk without artificial interruption. Only when it exceeds the maximum permitted size, such as an LLM token limit, is further recursive division applied (see recursive chunking, section 4.2).

4.3.3 Example: document-based chunking of the UN human rights declaration (Markdown, as JSON)

  {
    "chunk_id": "1",
    "struktur": "Präambel",
    "content": "Da die Anerkennung der angeborenen Würde und der gleichen und unveräußerlichen Rechte aller Mitglieder
    der Gemeinschaft der Menschen ...",
    "metadata": {
      "typ": "prambel",
      "abschnitt": "Einleitung"
    }
  },
  {
    "chunk_id": "2",
    "struktur": "Artikel",
    "artikel_nummer": 1,
    "titel": "Artikel 1",
    "content": "Alle Menschen sind frei und gleich an Würde und Rechten geboren. Sie sind mit Vernunft und Gewissen
    begabt und sollen einander im Geist der Brüderlichkeit begegnen.",
    "metadata": {
      "typ": "artikel",
      "quelle": "UN-Charta 1948",
      "rechtstyp": "Menschenrecht"
    }
  },
  {
    "chunk_id": "3",
    "struktur": "Artikel",
    "artikel_nummer": 2,
    "titel": "Artikel 2",
    "content": "Jeder hat Anspruch auf alle in dieser Erklärung verkündeten Rechte und Freiheiten ...",
    "metadata": {
      "typ": "artikel",
      "quelle": "UN-Charta 1948",
      "rechtstyp": "Antidiskriminierung"
    }
  }
]

Features:

  • Chunk boundaries = document structure (Markdown level)
    → Each H1/H2 heading marks a logical section

  • Metadata contains semantically useful information (e.g. artikel_nummer, typ, quelle)

  • No artificial length limit, since Article 1, for example, stays below the token limit

4.3.4 Benefits and challenges

A major benefit is semantic stability: coherent units suit targeted lookup, annotation, semantic retrieval and LLM processing. Structured documents also allow clear assignment of footnotes, captions or source references.

However, this method depends on availability of clean document structure.

4.4 Semantic chunking

The semantic chunking is an advanced method based on contextual meaning rather than external structure. It follows thematic, argumentative or narrative units: topics, actor roles, intentions, legal relationships or discourse focuses. It aims for coherent, semantically self-contained sections independent of layout and formatting.

4.4.1 Aim and applications

Semantic chunking particularly suits complex or highly interpretable texts such as philosophy, laws, political declarations or literature, where language models need meaning-driven retrieval or contextually precise answer generation.

4.4.2 Methodology

Semantic analysis implements this strategy. Depending on text type, methods include Named Entity Recognition, Topic Classification, Intent Detection or Large Language Models (LLMs). Unlike structural methods, it follows a passage’s content function: what is said, who acts, and which right, demand or norm is central?

Existing semantic information can also be used, for example from XML-based text formats. These structural clues combine with the methods above to automatically increase semantic depth.

One example is fully automated keyword or metadata generation through a hybrid workflow combining XSLT transformation, Python processing and LLM-assisted classification. Text can then be chunked, analyzed with rich structure and classified by topic, actor role or argumentative function. This opens new machine-analysis opportunities for normative texts, legal commentary and literary interpretation.

4.4.3 Example: semantic chunking of the UN human rights declaration

The Universal Declaration of Human Rights (UDHR) is formally divided into articles, but each may contain statements with different meanings or semantic agent roles, for example references to “people”, “state” or “law”.

Article 1 (original text):

„Alle Menschen sind frei und gleich an Würde und Rechten geboren. Sie sind mit Vernunft und Gewissen begabt und sollen einander im Geist der Brüderlichkeit begegnen.“

Semantically chunked representation (two semantic units):

[
  {
    "chunk_id": 1,
    "article": "1",
    "content": "Alle Menschen sind frei und gleich an Würde und Rechten geboren.",
    "metadata": {
      "rolle": "Mensch",
      "thema": "Menschenwürde",
      "rechtsstatus": "angeboren"
    }
  },
  {
    "chunk_id": 2,
    "article": "1",
    "content": "Sie sind mit Vernunft und Gewissen begabt und sollen einander im Geist der Brüderlichkeit begegnen.",
    "metadata": {
      "rolle": "Mensch",
      "thema": "Verantwortung",
      "norm": "Brüderlichkeit"
    }
  }
]

4.4.4 Benefits and challenges

Semantic chunking enables meaning-preserving processing of complex content, crucial for legal, political and moral-philosophical texts. RAG can target topical units, such as all chunks concerning “dignity” or “discrimination”.

However, it is not easy to automate: it requires deep content analysis and either manual annotation or powerful LLMs. Overlap can arise when sections concern several topics at once.

4.4.5 Agentic chunking

Agentic chunking is a semantic strategy following the acting or addressed actors (agents) appearing in text. Roles such as “individual”, “state”, “organization”, “teacher” or “student” receive particular rights, duties or scopes of action in normative or declarative documents. Content is divided not by formal structural features but by distribution of substantive responsibility.

It particularly suits texts where different roles are clearly distinguishable, such as constitutions, international conventions, policy statements or education. Agent-based segmentation maintains coherence within roles and prevents mixing and context loss. State responsibility, parental choice and individual rights can each become separate, self-contained units.

Agentic chunking often relies on LLM-assisted analysis, first interpreting small preliminary units (mini-chunks) independently, then grouping them by agent. Context overlap stabilizes this grouping; recursive or token-based methods can supplement it when length requires.

Comparing traditional and agentic chunking

The table compares aspects of traditional and agentic chunking:

Aspect

Traditional chunking

Agentic chunking

Segmentation principle

Sentence, paragraph, token

Role / actor

Context preservation

limited

high (semantically self-contained)

Perspective separation

not provided

explicit

Technical implementation

rule-based

LLM-assisted, dynamic

Suitability for normative texts

limited

very high

Automation level

high but superficial

complex but precise

Agentic chunking helps substantially to capture content role distributions cleanly, making it especially relevant where responsibilities, rights and roles need differentiated analysis, for example in law, education or normative knowledge analysis.

4.5 Token-based chunking

The token-based chunking is a precise method following the internal processing unit of language models, namely tokens. Tokens differ from words: depending on language and word structure, one word may contain several tokens while short words may use just one. “Gregor” counts as one token and “Samsa” as another, for example.

This is primarily used with Large Language Models (LLMs) such as GPT-4, Claude or LLaMA, which have specific token limits per input, typically 2048–8192 tokens depending on version. To avoid exceeding context, input is first split into token-exact units.

4.5.1 Aim and use

Token-based chunking aims for optimized text preparation for LLM queries for RAG, prompt engineering or finely tuned question-answer systems. It offers precise control, matching input exactly to technical limits, ideal for fixed contexts such as GPT-3.5’s 4096 tokens.

An example from Kafka’s Die Verwandlung illustrates tokenization granularity:

Fig. 4.1: Visualizing tokens

Figure: Visualizing tokens

Fig. 4.2: Token IDs for the previous figure

Figure: Token IDs for the previous figure

4.5.2 Combining strategies

Token-based chunking is not necessarily standalone and may or must combine with other methods. Semantic chunking, driven by content, often inevitably needs token limits too. Even a coherent or argumentatively complete section may exceed model limits. Further division is then technically forced rather than content-driven. This can break connected arguments or topical transitions but is often unavoidable for model compatibility.

For example, a semantically consistent chapter on “human dignity” in a foundational text may contain more than 400 tokens. The semantically defined chunk is then additionally split by a token limit:

 {
  "strategy": "semantisch + token-basiert",
  "max_tokens": 400,
  "chunk_id": 12,
  "content": "...",
  "metadata": {
    "thema": "Menschenwürde",
    "quelle": "Artikel 1",
    "rolle": "Mensch"
  }
}

Token-based chunking thus serves as a precise limiting layer, especially for automatically generated, thematically complex chunks from longer passages.

4.5.3 Practical implications

Token-based chunking efficiently keeps text within model constraints. Combined with semantic, structural or recursive methods, it can theoretically balance coherence and technical efficiency, essential to robust RAG.

In practice this combination is technically nontrivial, since tokenization is model-dependent: models use different tokenizers, so actual token counts can be determined only afterwards. Semantic or structural chunks must first be generated, then checked for token length and adjusted if necessary. The challenge is to minimize harm to original content coherence even when boundaries must change purely for technical reasons.

4.6 Sentence-based chunking

The sentence-based chunking is a linguistic strategy with boundaries following complete sentences. Each chunk contains one or more whole sentences, with boundaries automatically detected by language tools. It is considered particularly robust, easy to implement and semantically stable, generally preserving natural language flow.

4.6.1 Aim and operation

It aims to retain a coherent, self-contained semantic unit without artificial character or token cuts. Sentences are complete thought or information units, making this useful where contextual coherence, readability or transparent traceability matter, including automatic annotation, LLM question-answering, semantic search and classification preparation.

Implementation generally uses sentence segmentation through NLP tools such as spaCy, Stanza, nltk or LLM-integrated preprocessing. They reliably detect endings through punctuation, syntax and statistical probabilities, even in complex texts.

4.6.2 Benefits and limits

Its benefits are clear:

  • Content completeness through syntactically complete units

  • Linguistic clarity and readability

There are limits, however. In texts with very long sentences, such as literature, law or scholarly writing, one sentence can contain several hundred tokens and exceed model context. Such cases require supplementary strategies, such as an additional token-based limit or recursive subdivision of information. Very short sentences, conversely, lack context and may produce fragmented chunks and suboptimal answers.

Sentence-based chunking is a linguistically grounded, practically robust strategy proven in many applications, especially where coherence, interpretable structure and technical simplicity all matter. It often serves as a basic method for more complex semantic or recursive procedures.

4.7 Additional chunking functionality

Regardless of semantic, sentence-based, recursive or document-based strategy, supplementary procedures substantially improve chunk performance, contextual fidelity and flexibility. The most important are:

4.7.1 Overlapping

Overlapping explicitly carries part of the preceding chunk into the next to prevent context breaks and preserve understandable transitions even when a query or LLM processes only one chunk.

Example:

  • Chunk A: „... Gregor erwachte. Er lag auf dem Rücken und sah ...“

  • Chunk B: „Er lag auf dem Rücken und sah ... Seine Beine flimmerten ...“

The sentence “Er lag auf dem Rücken ...” appears in both chunks to ensure semantic continuity.

4.7.2 Duplication (redundancy for reuse)

Duplication means identical content appears in several chunks to meet different semantic, technical or structural requirements. It is useful when a passage is needed both with and without supplementary information.

Example:

A section contains a passage with a footnote:

„Bildung ist ein Menschenrecht¹.“
¹ Vgl. UNESCO, Bildung für alle, 2022.

Duplication can work as follows:

  • Chunk X (complete): contains text including footnote

  • Chunk Y (shortened): contains the same sentence without footnote

This redundancy enables precise processing and traceability.

4.7.3 Referencing (metadata links)

Referencing means explicit semantic links between chunks, for example when another chunk explains or applies a term, concept or article. These links are central to navigation, semantic retrieval and contextual answers.

Implementation depends heavily on a range of technical parameters:

  • LLMs or rule-based models recognizing semantic relationships

  • Embedding software (e.g. FAISS, Weaviate) calculating similarity between chunks

  • the data’s structural format: Markdown supports explicit links, HTML uses IDs and anchors, TXT needs additional metadata

Metadata reference example:

{
  "chunk_id": 17,
  "article": "Artikel 1",
  "content": "Menschenwürde ist unantastbar.",
  "metadata": {
    "verweist_auf": "chunk_id_4",
    "kontext": "Definition Menschenwürde",
    "quelle": "Grundgesetz"
  }
}

Chunk 17 is linked to a definitional chunk (ID 4), enabling semantic traceability.

4.7.4 Strategic findings

These additional methods— overlap, duplication and referencing —are integral to modern chunking architectures, working from technical interoperability through redundancy management to deep semantic analysis. Combined with classical strategies, they enable powerful, robust and application-adaptable chunk systems, especially in complex domains such as law, education, science and administration.

5 embedding software

5.1 How embedding software works in RAG systems

Embedding software is central to RAG: it converts text into machine-readable vectors representing semantic meaning. This makes external content, such as literature, searchable and interpretable by AI. This chapter illustrates the process through the classic “Die Verwandlung” by Franz Kafka.

5.1.1 From literary sentence to semantic vector

Consider the famous opening sentence of “Die Verwandlung”:

„Als Gregor Samsa eines Morgens aus unruhigen Träumen erwachte, fand er sich in seinem Bett zu einem ungeheueren Ungeziefer verwandelt.“

An embedding model such as text-embedding-ada-002 (OpenAI) or a BERT derivative transforms this sentence into a multidimensional vector, for example:

[0.023, -0.785, 1.202, ..., -0.091]

This vector encodes the sentence’s semantic meaning rather than its wording: themes such as “identity loss”, “transformation” and “nightmare”. Similar statements from thematically related works lie near each other in vector space.

This representation enables content-based search even when a query uses very different wording:

Question: “In which story does a person turn into an animal overnight?”

The query also becomes a vector and is compared with stored embeddings. Kafka’s text is recognized as relevant without mentioning “Gregor Samsa” or “Ungeziefer”.

5.1.2 Storage and semantic search in vector databases

The embedded Kafka sentence is stored in a vector database (e.g. FAISS, Pinecone, ChromaDB), where all chunks—paragraphs, scenes or chapters—are managed as separate embeddings.

A user or LLM query triggers this pipeline:

  1. The query also becomes an embedding.

  2. Semantic similarity search: compare the query vector with stored Kafka vectors.

  3. Top N results: return the most relevant passages, such as “Was ist mit mir geschehen? dachte er. Es war kein Traum.”
    (Kafka, “Die Verwandlung”)

These matches rely not on keywords but on semantic proximity in vector space, a significant improvement over keyword searching.

5.1.3 Integration into RAG architectures

The RAG system passes relevant passages (for example through LlamaIndex or LangChain) to a language model (LLM), which generates an answer. A Kafka analysis might give a literary explanation such as:

“In Franz Kafka’s ‘Die Verwandlung’, the opening sentence addresses Gregor Samsa’s existential crisis. His sudden transformation into vermin symbolizes social alienation and loss of identity.”

Background and quotations come from embedded text, not the model alone— embedding software makes the text usable at all for AI.

5.1.4 Practical implications

The example of “Die Verwandlung” shows that embedding software unlocks semantic analysis of complex literature, enabling meaning-based search independent of language, style or structure. Combined with dynamic paragraph-based chunking and metadata enrichment, it creates a flexible, AI-ready literature database for RAG.

5.2 Metadata in embedding-based RAG

5.2.1 Metadata as semantic amplifiers

Embeddings alone may not capture full context, especially for ambiguous, literary or domain-specific content. Here metadata provide structured supplementary information assigned to text to make context, provenance, structure and meaning machine-usable.

Example from “Die Verwandlung”:

{
  "content": "Als Gregor Samsa eines Morgens ...",
  "metadata": {
    "autor": "Franz Kafka",
    "titel": "Die Verwandlung",
    "kapitel": 1,
    "literaturgattung": "Erzählung",
    "sprache": "de",
    "entstehungsjahr": 1912
  }
}

These metadata are stored separately rather than embedded, for example as JSON or RDF, and can support filtering, sorting or targeted prompt engineering, for example searching “only German-language modernist literature with surreal motifs”.

5.2.2 How metadata interact with embedding software

Although metadata do not directly enter the embedding vector, they influence:

  • chunking (e.g. separating chapters, scenes or speaker roles)

  • Retrieval filters (e.g. only “Kafka” content or “Chapter ≥ 3”)

  • LLM answer context (e.g. “The following passage is from an expressionist story of 1912 ...”)

Search often uses a hybrid approach:

  • Semantic search: through embeddings

  • Symbolic filtering: through metadata queries (e.g. WHERE author = "Kafka")

5.2.3 Differences in embedding software metadata handling

Systems differ considerably in metadata support and integration:

Embedding system

Metadata processing

Features

OpenAI Embeddings

No native metadata binding

Separate vectors and information

ChromaDB

Native metadata fields

Integrated filtering through .where()

Weaviate

Fully semantic and symbolic

Graph structure with schema

FAISS

Vector similarity only

Metadata managed externally

Qdrant

JSON-based metadata

Supports tags, scores and filters

Systems such as ChromaDB or Weaviate allow jointly querying embeddings and structured metadata, for example with a query such as:

db.query(
    query_vector=embedding,
    filter={"autor": "Kafka", "kapitel": {"$gte": 2}},
    top_k=5
)

This makes search semantic and also context-aware.

5.2.4 Summary

Metadata add a symbolic layer to embedding software, enriching semantic vector spaces with structured contextual meaning. Embeddings detect proximity and relevance; metadata provide navigation and control points in complex corpora. Robust, transparent RAG, especially in literature, science and law, requires thinking of both together.

Note: Further metadata aspects appear in Part III of the RAG study series, “Automated chunks and XML: from PDF to flexible RAG”.

5.3 RAG system workflow

Using embedding software is central to modern RAG. The figure shows the typical pipeline from user query to AI answer and each component’s role in processing.

Fig. 5.1: Simplified RAG query workflow

Figure: Simplified RAG query workflow

1. User query (text)

It begins with a user’s natural-language input, such as a question or search query, starting the subsequent processing.

2. Embedding model (text → vector)

The text is transformed through an embedding model into a multidimensional vector representing semantic query meaning and supporting similarity search. Models include text-embedding-ada-002 from OpenAI or BERT variants mapping text into numeric vector space.

3. Vector database (similarity search)

Generated vectors are compared with entries in a vector database (e.g. FAISS, Weaviate, Pinecone). It contains pre-embedded document chunks. The aim is to identify those semantically similar to the query.

4. Relevant documents

Vector comparison retrieves the semantically closest chunks, containing potentially relevant information. Finding the right passages determines answer precision and completeness.

5. LLM (answer generation)

Selected documents and the original query are passed to a Large Language Model (LLM), which uses external context to formulate a substantiated answer, based on embedded information rather than training alone. RAG thus combines search engines and generative AI.

6. Final answer

Finally, the LLM generates the final answer shown to the user, combining retrievable knowledge (retrieved) and linguistic formulation skills (generated), hence Retrieval-Augmented Generation.

5.4 Comparing chunking strategies: structure, context and applicability

The table systematically surveys key Chunking strategies in RAG, comparing segmentation logic, context preservation, suitability for complex content and technical effort. It helps select strategies for specific applications such as normative text, technical documentation or education.

Category

Decision points

Options/details

Data structure in chunks

Content format within chunks

Markdown, plain text, HTML, XML, JSON

Structured versus unstructured data

Tables, lists, body text

Chunk metadata

Source references, timestamps, categories

Chunk file format

Storage file format

JSON, YAML, TXT, CSV, XML

Compression strategy

Gzip, Bzip2, no compression

LLM optimization

Adapting to specific models

Encoding strategy

Semantic encoding

Embeddings with extra information (e.g. tags)

Content referencing

IDs, hyperlinks, footnotes

Contextualization

Annotations, additional metadata

Chunking strategy

Chunk size

Fixed length, fixed tokens, dynamic

Chunk overlap

None, partial, adaptive overlap

Observe token limits

Yes (optimized for LLM limits) / No

embedding software

Embedding model selection

OpenAI, BERT, Cohere, SentenceTransformers

Preprocessing and tokenization

Remove stop words, lemmatization

Embedding fine-tuning

Domain-specific training

vector database

Database selection

Pinecone, Weaviate, FAISS, Chroma, Milvus

Indexing strategy

Flat, HNSW, IVF, PQ

Scalability

Cloud, on-premises, hybrid

LLM (Large Language Model)

LLM selection

GPT-4, Claude, Mistral, LLaMA, Custom

Model fine-tuning

Yes (fine-tuning), no (standard model)

Use cases

General, specialist, code, medicine

Evaluation and monitoring

Evaluation metrics

Accuracy, relevance, latency, recall

Include user feedback

Yes, no

Continuous optimization

Automated, manual

6 From disorder to structure: RAG problem areas and a clarifying case study

6.1 Findings from Part 1 of the RAG series

The central finding of Part 1, “Structured versus unstructured data for RAG training: a comparison”, fits one sentence: data structure determines RAG quality. Comparing structured Markdown or HTML with unstructured PDF showed more precise and substantiated answers when source content is clearly organized and enriched with metadata.

6.2 Aim: creating order through a case study

Instead of theoretically classifying possible problem areas, we will use a prototypical case study to organize previous findings. A realistic scenario shows how formats, chunking, metadata, references and model integration form a coherent pipeline.

This disentangles technical options, strategies and dependencies into meaningful, solution-oriented groups of actions.

6.3 Case study: RAG implementation at a scholarly publisher

A medium-sized scholarly publisher with over 50 specialized AI-assisted chatbots must build a consistent, extensible RAG infrastructure. Historically accumulated holdings pose technical and conceptual challenges.

Much content is XML, especially BITS and JATS, with rich structure, but many older titles exist only as unstructured PDF. Some XML holdings have also been converted into PDF and ePub, creating ambiguity and inconsistency. This heterogeneous mix complicates uniform preparation for RAG substantially.

In addition, content throughput is dynamic: new publications appear regularly while old editions must be removed or replaced. Continuous updates, automated versioning and synchronization are needed without redundancies or access to outdated content.

Dependence on specific LLM providers is central. The publisher wants long-term independence, but many systems tightly couple to proprietary models. Technical and financial flexibility conflicts with proprietary tokenization or context-limit standards.

Another issue is future-proofing: future LLM requirements for size, semantics and context are unpredictable, so today’s processes may not remain stable in two or three years. A rigid architecture could require costly adaptation to entirely different models.

It is also unclear how to chunk content optimally for current and future models, especially complex scholarly texts with cross-references, footnotes, tables and multilingual passages.

7 Data structuring and storage: two fundamental case-study dimensions

7.1 Stepping back: two core problems instead of many individual questions

To understand RAG’s complex overall problem, it helps to take an analytical step back. Practice and theory reveal two fundamental problem areas which, clearly separated, underpin sustainable RAG:

  1. Data structuring

  2. Data storage

This separation is analytically useful and practically necessary to achieve technological independence and long-term maintainability.

7.2 Data structuring: chunk-neutral and media-neutral

Automated media production has long known the structure problem. Preparing content for print, ePub, InDesign, PDF, web or apps shows that only media-neutral structuring enables flexible reuse. This is the core solution for RAG too.

The answer: chunk-neutral structuring.

Instead of predefining 300-token or 500-character chunks, content stays in a chunk-neutral format that supports automatically generating any chunking strategy. Appropriate chunks can then be generated whenever context requires: tokens for GPT, paragraphs for BERT, or overlap for particular search applications.

Technology core:

  • XML, the established media-neutral format, remains the basis as a hub/pivot format.

  • Additional technologies include:

    • XSLT for rule-based transformation,

    • Python for tokens and much more,

    • XProc for orchestrated pipelines,

    • XQuery for very large formats and analysis,

    • local LLMs for content enrichment or classification,

    • and XML databases.

Their interplay is complex but familiar and manageable, especially in environments experienced in cross-media publishing or technical documentation.

7.3 Data storage: flexible, semantic and automated

It also matters where and how structured content is stored. Requirements are high:

  • versioning,

  • semantic searchability,

  • efficient downstream RAG integration,

  • automated updates, e.g. new editions,

  • and technological openness.

The solution is Content Delivery Services (CDS), long proven in technical documentation.

Core concepts:

  • Store structured content in container-based formats (e.g. ZIP+XML, METS, iiRDS),

  • Enrich with RDF metadata for semantic analysis,

  • SPARQL-capable systems for targeted content queries,

  • Integrate with Git, CMS or XML databases, depending on editorial environment.

Separating structuring and storage is again crucial: content remains independent of output form and specific LLM/embedding combinations. Switching to new language models, vector databases or presentations is then possible at any time.

8 Outlook: next steps in RAG research

This chapter closes the study’s current phase, which established a systematic understanding of RAG. Its quality and future viability essentially depend on two factors: data structuring and storage within a flexible, automated ecosystem.

Two dedicated studies will deepen and operationalize the case-study findings, each focusing on one central area.

8.1 Next study: data structuring and automated chunking

The next study will focus exclusively on structuring content media-neutrally and automatically deriving any conceivable chunk format for current and future LLMs.

The aim is to develop fully automated infrastructure generating any strategy—tokens, words, paragraphs, chapters, semantic units, etc.—at the push of a button, adapted to model, application or user-interface needs.

A central tool will be Octopus, converting diverse sources such as HTML, ePub, Word, InDesign and PDF into a chunk-neutral, media-neutral intermediate format. This will enable systematic extraction of structured RAG-ready content even from difficult PDFs, automatically, scalably and in compliance with standards.

8.2 Final study: working with a Content Delivery Service (CDS)

The final study will examine the role of CDS in overall RAG architecture, especially between structured content and retrieval/generation components.

The focus is CDS/RAG communication:

  • How do LLMs request specific CDS content?

  • How do RDF metadata, SPARQL queries and container formats such as iiRDS select content?

  • How can updates, versioning and model changes be automated and secured?

The aim is an intelligent, rule-based system in which data storage is an active participant in RAG rather than passive storage, with semantic understanding, feedback channels for evaluating answers, and integration into existing publishing and editorial systems.

   

back to top