AI Hints
Home›RAG Tutorial›Chains and Context
RAG · Lesson 48 of 120

The Context Budget

How much to send.

⏱ 2 min read▶ Video at 47:59🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Every chunk we send costs tokens, money, and time. Too much context can also confuse the model. So we set a budget, and stop adding chunks when it's full.

The Context Budget
From the video: The Context Budget
  • Chunks cost tokens
  • Too much confuses
  • Set a budget

Filling a budget

We estimate tokens as characters divided by four, a common rule of thumb. Fit adds chunks in score order, until the next one would break the budget. We try three budgets. Run it. A bigger budget lets in more chunks.

budget.pypython
from rag_kit import load_docs, make_chunks, Index

index = Index(make_chunks(load_docs()))
tokens = lambda text: len(text) // 4

def fit(hits, budget):
    kept, used = [], 0
    for score, c in hits:
        if used + tokens(c["text"]) > budget: break
        kept.append(c); used += tokens(c["text"])
    return kept, used

hits = index.search("What does the warranty cover?", k=10)
for budget in [100, 300, 1000]:
    kept, used = fit(hits, budget)
    print(f"budget {budget}: {len(kept)} chunks, about {used} tokens")
Output
budget 100: 1 chunks, about 68 tokens
budget 300: 5 chunks, about 237 tokens
budget 1000: 10 chunks, about 380 tokens
Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]

Setting the budget

A few thousand tokens of context is plenty for most questions. Leave room for the answer. Measure cost per question. And remember, better ranking beats a bigger budget.

keyvalue
Typical1,000 to 4,000 tokens
Leave roomfor the answer
Measurecost per question
Betterranking over size

Summary

Set a token budget, and add chunks in score order until it's full. Next, why the order of chunks matters.

Key takeaways
  • Characters / 4
  • Add until full
  • Ranking first
Next up: Order Matters — lost in the middle