Sizing RAG Chunks in Tokens, Not Characters

JS
Jai Singh
02 Dec, 2026 3 min read 5 views

Embedding models and language models read tokens, not characters or words. If you size chunks in characters, some chunks will exceed the model's input limit and be silently truncated, while others will be much shorter than you intended. Measuring chunk size in tokens with the same tokenizer as your embedding model removes this guesswork.

What a token is

A tokenizer breaks text into pieces from a fixed vocabulary. Common English words are often one token, rarer words become several, and numbers, code and non-English text usually take many more tokens per character. A rough rule for English prose is that one token is a little under four characters, but this rule fails badly for source code, URLs, tables and languages such as Thai or Hindi. Never trust the rule for planning limits. Count.

Why truncation is dangerous

Every embedding model has a maximum sequence length. With sentence-transformers you can read it as model.max_seq_length. Text beyond that length is cut off before embedding. Nothing warns you. The stored chunk still contains the full text, but its vector represents only the first part. A query that matches the dropped tail will never find the chunk. This is one of the most common hidden causes of missing answers.

Count tokens with the model's tokenizer

A sentence-transformers model exposes its tokenizer. The code below measures chunks and flags those that exceed the limit.

from sentence_transformers import SentenceTransformer

model = SentenceTransformer("all-MiniLM-L6-v2")
tokenizer = model.tokenizer
limit = model.max_seq_length
print("limit:", limit)

def n_tokens(text: str) -> int:
    return len(tokenizer.encode(text, add_special_tokens=False))

def check(chunks):
    too_long = [c for c in chunks if n_tokens(c) > limit]
    print(f"{len(too_long)} of {len(chunks)} chunks exceed {limit} tokens")
    return too_long

text = "def parse_config(path): return json.load(open(path))"
print(len(text), "characters,", n_tokens(text), "tokens")

Run it on a sample of your real chunks. If the count of long chunks is not zero, shrink the chunk size or switch to a model with a longer limit.

Split by tokens

The splitter below builds chunks from sentences until a token budget is reached, with overlap measured in tokens too. It reuses the n_tokens function from above.

import re

def chunk_by_tokens(text, max_tokens=200, overlap_tokens=30):
    sentences = re.split(r"(?<=[.!?])\s+", text.strip())
    chunks, current, count = [], [], 0
    for s in sentences:
        n = n_tokens(s)
        if current and count + n > max_tokens:
            chunks.append(" ".join(current))
            # start next chunk with trailing sentences as overlap
            tail, tail_count = [], 0
            for prev in reversed(current):
                pn = n_tokens(prev)
                if tail_count + pn > overlap_tokens:
                    break
                tail.insert(0, prev)
                tail_count += pn
            current, count = tail, tail_count
        current.append(s)
        count += n
    if current:
        chunks.append(" ".join(current))
    return chunks

Overlap here is made of whole sentences, up to overlap_tokens, so you never start a chunk in the middle of a sentence. A sentence longer than the budget still becomes its own chunk, so run the check function afterwards.

Tokens for the language model

Your embedding model's tokenizer is not the same as the tokenizer of the model that writes the answer. The prompt budget is counted by the answer model. To plan how many chunks fit, use the provider's token counter. With the Claude SDK, client.messages.count_tokens returns the input token count for a request, as shown in an earlier post. Use the embedding tokenizer for chunk limits and the answer-model counter for prompt limits.

Choosing the numbers

  • Set the maximum chunk tokens below the embedding limit, leaving room for any prefix or heading you add to the embedded text.
  • If you prepend a title and heading path to each chunk before embedding, count those tokens too.
  • Typical targets are 150 to 400 tokens, but test on your data.
  • Budget the prompt: tokens per chunk times the number of chunks, plus instructions, question and room for the answer.

Common mistakes

  • Using the same character count for prose, code and non-English text.
  • Forgetting that the embedded text includes the heading you added.
  • Counting words and assuming one word is one token.
  • Changing the embedding model and keeping old chunk sizes, when the new model has a different limit.

Add a token check to your ingestion job and make it fail loudly or log a warning when a chunk is too long. This small guard prevents a whole class of silent retrieval failures.

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.