LevelUpWith

Explore / Retrieval Engineering for LLM Apps: RAG That Works / Lesson 2

Lesson 2: Retrieval vs Long Context vs Fine-Tuning

Decide when to build retrieval, when to put the whole corpus in a long context window, and when to fine-tune, based on corpus size, update rate, cost per query and the kind of knowledge involved.

Free to read, no account needed. Part of Retrieval Engineering for LLM Apps: RAG That Works.

By the end of this level you'll be able to

  • Estimate tokens, cost per query and latency for a long-context approach and a retrieval approach on the same corpus
  • Explain why fine-tuning changes behaviour and format more reliably than it adds facts that can be looked up and updated
  • Write a one-page decision record choosing an approach for a given use case, with the trade-offs stated

Three ways to give a model knowledge

Your first RAG demo gave wrong answers, and it's natural to wonder whether retrieval was the right tool at all. Maybe you could paste the whole corpus into the prompt, or fine-tune the model on your documents. Each of these is right for some jobs, and it's worth deciding on purpose before you spend 48 more levels tuning retrieval.

Here's an analogy. Long context is handing a contractor the whole filing cabinet with every question. Retrieval is a librarian who pulls the five relevant folders first. Fine-tuning is sending the contractor on a training course. The course changes how they work. It's a poor way to make them memorise this quarter's price list.

Four questions decide the choice:

  1. Corpus size. Does it fit in a context window, with room left over?
  2. Update rate. How often do documents change, and do you need to delete things?
  3. Cost and latency per query at your real traffic.
  4. Kind of knowledge. Is it facts to look up (prices, policies, specs) or behaviour (tone, output format, domain style)?

Step 1: Count tokens before you argue

A rough rule for English text is that one token is about 4 characters, or about ¾ of a word. Use a real tokenizer once you have the files.

# pip install tiktoken  -- exact counts for OpenAI-style encodings
import tiktoken, pathlib

enc = tiktoken.get_encoding("o200k_base")
total = 0
for p in pathlib.Path("corpus/").rglob("*.txt"):   # text you have already extracted
    total += len(enc.encode(p.read_text(errors="ignore")))
print(f"corpus tokens: {total:,}")
# corpus tokens: 201,344   <- a 300-page employee handbook

Today's hosted frontier models offer windows of hundreds of thousands of tokens, and around a million at the top end. A 200k-token handbook fits. A 40M-token support archive won't fit in any hosted window.

Step 2: Cost per query, side by side

The prices below are placeholders, so put in your provider's current rates. Prompt caching matters here. Providers bill a repeated prompt prefix at a reduced rate. On Anthropic's API, for example, a cache read costs a fraction of base input (0.1× on most models) and a cache write costs more (1.25× for the default 5-minute cache).

PRICE_IN, PRICE_OUT = 2.00 / 1e6, 10.00 / 1e6   # $/token, ILLUSTRATIVE only
CACHE_READ = 0.10                                 # cached input multiplier
Q, OUT = 50, 300                                  # question and answer tokens

def cost(ctx_tokens, cached=False):
    ctx_rate = PRICE_IN * (CACHE_READ if cached else 1)
    return ctx_tokens * ctx_rate + Q * PRICE_IN + OUT * PRICE_OUT

lc       = cost(200_000)               # whole handbook every call
lc_cache = cost(200_000, cached=True)  # handbook as a cached prefix
rag      = cost(8 * 500)               # 8 retrieved chunks of ~500 tokens

for name, c in [("long ctx", lc), ("long ctx cached", lc_cache), ("rag", rag)]:
    print(f"{name:16} ${c:.4f}/query   ${c*10_000:,.0f}/day at 10k queries")
# long ctx         $0.4031/query   $4,031/day at 10k queries
# long ctx cached  $0.0431/query   $431/day at 10k queries
# rag              $0.0111/query   $111/day at 10k queries

Retrieval also has costs this leaves out: embedding the corpus, running the vector store, and the engineering time. At 50 queries a day, long context costs about $20 a day, and you may never need to build an index. At 10k queries a day the gap pays for an index many times over.

Gotcha: caches are fragile. A cached prefix expires (5 minutes by default on Anthropic, and you can pay more for an hour). Any edit to the corpus text invalidates it, so if documents change hourly you keep paying cache writes.

Latency grows with prompt length, because the model has to process every input token before it writes the first output token. Measure time-to-first-token yourself with a 200k-token prompt and with a 4k one, on your provider, rather than trusting a blog figure.

Step 3: Fitting in the window isn't the same as being used well

A corpus that fits can still be answered badly. In Lost in the Middle (Liu et al., TACL 2024), accuracy followed a U-shape. Models did best when the relevant passage sat at the start or end of the context, and worse when it sat in the middle. Chroma's 2025 Context Rot report tested 18 models and found answers grew less reliable as input length grew, especially when the context held distractors similar to the answer. Chroma sells a vector database, so read the report with that in mind. Still, the direction matches independent work. Newer models may do better, which is one more reason to test your own corpus.

Step 4: What fine-tuning is actually good at

Fine-tuning updates weights. That reliably teaches behaviour: a JSON schema, a house tone, how to classify tickets, how to use a domain's jargon. It's an unreliable way to add facts you can look up:

  • Ovadia et al. (EMNLP 2024) compared unsupervised fine-tuning with RAG on knowledge-heavy QA. RAG did better, both on facts the model had seen before and on new ones.
  • Gekhman et al. (EMNLP 2024) found that fine-tuning examples with new facts were learned more slowly. As the model learned them, it became more likely to hallucinate. Their conclusion: models get facts mostly from pre-training, and fine-tuning teaches them to use what they already know.
  • Operations: you can't cite a weight, delete one document from it, or apply per-user permissions to it. In an index, each of those is one operation.

The approaches combine. A common pattern is to fine-tune for format and use retrieval for facts.

Step 5: Write the decision record

# ADR-007: Knowledge access for HR policy assistant
Context: 201k-token handbook, edited ~monthly, 300 queries/day, all staff see all of it.
Options: (a) long context + cache  (b) RAG  (c) fine-tune
Decision: (a) long context with cached prefix.
Why: fits the window; ~$13/day at 300 queries (cached, placeholder prices);
     no index to run; monthly edits rarely invalidate the cache.
Trade-offs accepted: higher TTFT; possible mid-context misses; no per-doc ACLs.
Revisit when: corpus > 50% of the window, traffic > 5k/day, or ACLs are needed.
Rejected: (c) because policies change and answers must cite sections.

The Revisit when line matters most. It turns the decision into a test you can rerun when things change.

Exercise

Pick a real document set (your team's docs, or a public one such as a project's documentation). (1) Count its tokens with a tokenizer. (2) Run the cost script with your provider's current prices at 100, 1k and 10k queries/day. (3) Time one long-context call and one 4k-token call. (4) Write a one-page decision record in the format above, including a "Revisit when" line.

Key takeaways

  • Decide using four inputs: corpus size, update rate, cost and latency per query, and kind of knowledge.
  • Long context is simplest for a small, stable corpus with low traffic. Caching cuts the cost but breaks when content changes.
  • Retrieval wins on large, changing or permissioned corpora, and when traffic is high.
  • Fine-tune for behaviour and format, not for facts that change or need citing and deleting.
  • Write the choice down with explicit conditions for revisiting it.

A 6-question knowledge check follows this lesson in the app, free and without an account.

Keep going: levels 3 and 4 are free

Create a free account to open the next two levels, try the AI tutor, save your progress and pick up where you left off. No card needed.

Next: Level 3, Failure Triage: Reading a Broken Demo.

Create a free account →See the whole course

More like this