Sub topic 3
Tokens, embedding input limits, and context budgets
Prerequisites
This chapter assumes you know what a token is in a language model, what an embedding is, and how vector similarity search ranks results. It also assumes you can read basic Python. Earlier chapters showed where chunking sits in a RAG pipeline and why we chunk at all. This chapter covers the hard numeric limits that decide how large a chunk is allowed to be.
Why characters and words are the wrong unit
Chunking code often counts words or characters, as in the fixed-size splitter earlier in this tutorial. Models do not. An embedding model and a chat model both read tokens, which are the pieces produced by a tokenizer. A token can be a whole common word, part of a rare word, a single punctuation mark, or a run of whitespace.
For ordinary English prose, a token averages roughly four characters, or about three quarters of a word. That ratio is only a rule of thumb. It breaks down in several common cases:
- Source code, with its symbols, indentation, and long identifiers, usually produces more tokens per character.
- Text in languages other than English often produces more tokens per word, and sometimes many more.
- Numbers, URLs, hashes, and base64 strings split into many short tokens.
- Tables rendered as Markdown or HTML spend tokens on pipes, dashes, and tags.
A 200-word chunk of prose may be about 270 tokens. A 200-word chunk of dense code or log output can be twice that. If your limits are in tokens, your chunker should measure in tokens.
Three limits that shape chunk size
Three separate limits apply, and they constrain different parts of the pipeline.
| Limit | Applies to | What happens when you exceed it |
|---|---|---|
| Embedding model input limit | Each chunk, and each query, at indexing and search time | Truncation (silent in many libraries) or an API error |
| LLM context window | The whole prompt plus the generated answer | An API error, or the oldest content is dropped by your framework |
| Your own prompt budget | The number of retrieved chunks you insert | Wasted cost, noise, and weaker answers, even when nothing fails |
Embedding model input limits
Every embedding model accepts a maximum number of input tokens. Typical values range from a few hundred tokens for small open-source sentence encoders to several thousand for hosted models. For example, many sentence-transformers models default to 256 or 512 tokens, and some hosted embedding APIs accept around 8,000. Look up the number for the exact model and version you use. It is in the model card or API documentation, and some libraries let you change it.
The failure mode matters more than the number. Many libraries truncate input that is too long and return a vector without warning. The vector then represents only the first part of the chunk. The text after the cut is stored and shown to the LLM, but it was never part of the vector, so a search for its content will not find it. This is a retrieval bug that produces no error message.
A model that accepts long inputs does not make long chunks a good idea. An embedding is a single vector for the whole input. A 6,000-token chunk covering five topics produces a vector that blurs all five. The input limit is the ceiling, and your chosen chunk size should usually sit well below it.
The LLM context window
The context window is the total number of tokens the chat model can handle in one request. It covers everything: system prompt, instructions, retrieved chunks, conversation history, the user's question, and the generated answer. Providers often count the answer against the same window, or enforce a separate cap on output tokens. Check which rule your provider uses.
A large window changes the arithmetic but not the problem. Cost and latency grow with prompt length. Many models also use information in the middle of a long prompt less reliably than information at the start or end. Filling the window with marginal chunks can lower answer quality.
Your prompt budget
The prompt budget is the share of the window you choose to spend on retrieved text. You set it, and it determines how many chunks of a given size you can include.
Counting tokens in code
Use the tokenizer that matches your model. If you use an OpenAI-family model, the tiktoken library provides one. Install it with pip install tiktoken. The first call to get_encoding may download the vocabulary file, so it needs network access once.
def count_tokens(text, encoding_name="cl100k_base"):
try:
import tiktoken
except ImportError:
# Rough fallback: about 4 characters per token for English prose.
return max(1, len(text) // 4)
enc = tiktoken.get_encoding(encoding_name)
return len(enc.encode(text))
if __name__ == "__main__":
prose = "Chunking decides what the retriever can find."
code = "def f(x):\n return {k: v for k, v in x.items() if v}\n"
print(count_tokens(prose), len(prose))
print(count_tokens(code), len(code))For other model families, use that vendor's tokenizer. Hugging Face models expose one through AutoTokenizer. The fallback above is a rough estimate for planning only. Do not use it to enforce a hard limit.
Different tokenizers give different counts for the same text. A chunk that is 480 tokens under one tokenizer may be 530 under another. If the embedding model and the chat model use different tokenizers, you need two counts: one checks the chunk against the embedding limit, and the other checks the assembled prompt against the context window.
Checking chunks against the embedding limit
Run a check after chunking and before embedding. It catches oversized chunks while they are still cheap to fix.
def count_tokens(text):
# Replace with a real tokenizer for your embedding model.
return max(1, len(text) // 4)
def find_oversized(chunks, limit, count=count_tokens):
"""Return (index, token_count) for every chunk above the limit."""
oversized = []
for i, chunk in enumerate(chunks):
n = count(chunk)
if n > limit:
oversized.append((i, n))
return oversized
chunks = ["short chunk", "x" * 3000]
print(find_oversized(chunks, limit=512))With the fallback counter, the second chunk has 750 estimated tokens, so the call prints [(1, 750)]. In a real pipeline, treat any result as a failure: re-split those chunks or stop the run. Leave some headroom under the limit, for example 10 to 20 percent. Headroom absorbs tokenizer differences and any text you add later.
Count the text you actually embed. If you prepend a title, a heading path, or other metadata to each chunk before embedding (covered in a later chapter), those tokens count toward the limit. Many embedding models also add special tokens at the start and end of each input, which use a small part of the allowance.
Queries have a limit too. Short questions rarely hit it, but if you embed long user messages or pasted documents as queries, check them the same way.
Budgeting the prompt
Work through the budget from the top. Subtract everything that is not retrieved text from the context window, then divide what remains by the cost of one chunk.
def max_chunks_in_prompt(
context_window,
output_reserve,
fixed_prompt,
question,
chunk_tokens,
separator_tokens=5,
):
available = context_window - output_reserve - fixed_prompt - question
if available <= 0:
return 0
return available // (chunk_tokens + separator_tokens)
# 8,192-token window, 1,024 tokens reserved for the answer,
# 300 for instructions, 50 for the question.
# Each chunk is 400 tokens plus 30 tokens of metadata.
print(max_chunks_in_prompt(8192, 1024, 300, 50, chunk_tokens=430))This prints 15. The available space is 8192 − 1024 − 300 − 50 = 6818 tokens, and each chunk costs 430 + 5 = 435 tokens, so 15 chunks fit with room left over.
Chat history, tool definitions, and citations in the output format also use window space. Add them to the fixed part of the budget if your application has them.
The budget also constrains your choice of k, the number of chunks retrieved. Doubling chunk size roughly halves the number of chunks that fit. A pipeline that retrieves k = 10 chunks of 300 tokens spends about 3,000 tokens on context. The same k with 1,200-token chunks spends 12,000, which may not fit and will cost four times as much.
Edge cases and gotchas
- Single paragraphs above the limit. Separator-based splitters fall back to character splitting when a piece has no separators left, as the recursive splitter does. Character splitting can cut tokens or words in half, so verify token counts after the fallback runs.
- Chunk size measured in characters. A
max_chars=500limit is safe for prose but can exceed a 256-token embedding limit on code or non-English text. Convert the limit to tokens or measure with a tokenizer. - Overlap inflates stored text. With 200-token chunks and 40 tokens of overlap, each chunk repeats 20 percent of its neighbor. This does not affect the per-chunk embedding limit, but it raises the total tokens you embed and store, and it can put near-duplicate chunks into the top
k. Duplicates waste prompt budget. - Model changes. Switching embedding models can change both the limit and the tokenizer. Re-run the oversize check, and re-embed the whole corpus. Vectors from different models are not comparable.
- Cost. Embedding APIs bill per token, so your total corpus tokens, including overlap and prepended metadata, determine the indexing cost.
A practical order of decisions
- Find the embedding model's input limit and tokenizer.
- Pick a target chunk size well below that limit, for example half of it, and adjust after testing.
- Decide the output reserve and fixed prompt cost for the chat model.
- Compute how many chunks fit, and set
kbelow that number. - Add a pre-embedding check that rejects any chunk above the limit, counting any metadata you prepend.
The next chapter uses these numbers to weigh smaller chunks against larger ones.
Exercise
Your embedding model accepts 512 tokens. Your chunker splits by 1,800 characters, and you prepend a 25-token heading path to each chunk before embedding. Most documents are English prose, but one folder contains JSON logs. Explain why the logs may cause problems, and name two changes that make the pipeline safe. Then compute how many chunks of 350 tokens plus 20 tokens of metadata fit in a 4,096-token window, with 600 tokens reserved for the answer, 250 for instructions, and 100 for the question, ignoring separators.
Show answer
A 1,800-character English chunk is roughly 450 tokens, and with the 25-token heading path it is close to 475, which is near the limit. JSON logs contain many short tokens such as braces, quotes, digits, and hashes, so 1,800 characters can exceed 512 tokens. The embedding library may then truncate the chunk silently, and the end of each log chunk becomes unsearchable. Safe changes: measure chunk size in tokens with the embedding model's tokenizer (including the heading path), and add a check that fails or re-splits any chunk above the limit, with some headroom. Lowering the target size for log content also helps. Budget: 4096 − 600 − 250 − 100 = 3146 tokens available. Each chunk costs 350 + 20 = 370 tokens, and 3146 // 370 = 8. Eight chunks fit.