🎨 THEME ENGINE
PROMETHEUS OS · 23 THEMES
Trial version: Dark + Light themes only.
Full theme access with PROMETHEUS OS license.
Dark theme active
Experience all 23 themes in PROMETHEUS OS

RAG vs Long Context vs Fine-Tuning: Choosing an Architecture

Advanced 18 min· 4 exercises

Choose between retrieval, long-context prompting, fine-tuning and tool use for a given knowledge problem by comparing freshness, cost, latency, accuracy, citations, privacy and maintenance with real numbers, and combine them when one is not enough.

By the end of this lesson you will be able to
  • Explain what kind of knowledge or behaviour each approach changes: retrieval, long-context prompting, fine-tuning and tool use.
  • Calculate and compare per-query token cost, prefill latency and KV-cache memory for long-context and RAG designs.
  • Compare the approaches on freshness, accuracy, citations, privacy and maintenance using a decision table.
  • Apply a step-by-step decision procedure to a concrete product scenario and justify the choice.
  • Design hybrid architectures such as RAG plus fine-tuning, retrieval-routed long context and cached long context.

Before this: Embeddings and Retrieval-Augmented Generation, KV Cache and Context Cost, Fine-Tuning vs Prompting, Evaluating RAG Systems

Every team building on language models eventually asks the same question: our model does not know our material, so should we retrieve it, paste all of it into a very long prompt, or train it in? Since context windows grew into the hundreds of thousands of tokens and beyond, the question has become sharper, and it is often argued as a matter of taste. It should not be. Each approach changes something different about the system, and the right choice follows from the data, the query volume, the latency budget and the governance requirements. This lesson gives you a framework and the arithmetic to decide.

Intuition: three ways to prepare for an exam, plus a phone

Imagine a consultant preparing to answer clients' questions about a 2,000-page regulation.

  • Long-context prompting is reading the entire regulation immediately before every single client call. Nothing is missed in principle, but it is slow and expensive each time, and attention flags in the middle of a long read.
  • RAG is keeping a well-indexed binder and flipping to the three relevant sections when a question comes in. It is fast and cheap, and you can show the client the page, but if the index is bad you look in the wrong place.
  • Fine-tuning is a training course that changes how the consultant thinks and talks: the jargon, the style of the memo, the habit of always checking exemptions. It is poor at memorising every clause reliably, and when the regulation is amended the course is out of date.
  • Tool use is picking up the phone to the registry for things that change by the minute, such as the status of a particular filing. No amount of reading or training substitutes for a live lookup.

The central insight: fine-tuning mostly changes behaviour; retrieval and long context supply knowledge; tools supply live state and actions. Most confusion comes from using fine-tuning to inject facts or using retrieval to change style.

What each approach actually does

Long-context prompting puts the whole relevant corpus, or a large part of it, into the prompt on each request. Nothing is built offline. The model can reason across the whole text at once, which helps with global questions ("summarise all the changes across these contracts") that chunked retrieval handles poorly. Costs scale with prompt length on every call, though prompt caching (reusing the computed key-value state of an unchanged prompt prefix across requests, offered by many providers at a discounted price for cache hits) changes the economics substantially for a fixed corpus. Quality can degrade when relevant facts sit in the middle of long inputs (Liu et al., 2023), although models have improved on this.

Retrieval-augmented generation (Lewis et al., 2020, for the original formulation) indexes the corpus offline, retrieves a few relevant chunks per query and puts only those in the prompt. Cost per query is small and nearly independent of corpus size; updates mean re-indexing changed documents; and answers can cite exact passages. Its weakness is retrieval misses: if the right chunk is not retrieved, the model cannot use it.

Fine-tuning updates model weights on examples. Full fine-tuning updates all weights; parameter-efficient methods such as LoRA (Hu et al., 2021) train small low-rank adapter matrices instead. Fine-tuning is excellent for format, tone, domain vocabulary, classification and extraction tasks, tool-calling conventions, and distilling a big model's behaviour into a small one. It is unreliable for injecting large numbers of new facts: Ovadia et al. (2023) compared the two for knowledge injection and found that retrieval consistently outperformed unsupervised fine-tuning, both for knowledge seen in pre-training and for entirely new knowledge. Fine-tuned facts also cannot be cited, and removing a fact requires retraining.

Tool use lets the model call APIs and databases at run time: order status, inventory, prices, calendars, calculations, SQL over live tables. It is the only option for data that changes continuously or must be exact and authoritative, and the only one that can take actions.

The comparison

CriterionRAGLong contextFine-tuningTool use
FreshnessGood: re-index changed documents in minutesExcellent: whatever you send is currentPoor: needs retraining and redeployExcellent: live
Per-query costLow; grows with chunks retrievedHigh; grows with corpus size (caching helps for fixed prefixes)Lowest prompt cost; possibly higher per-token price for custom models; training is an upfront costLow to moderate; plus API costs
LatencyRetrieval (tens to hundreds of ms) plus short prefillLong prefill on uncached input; cached prefixes are much fasterFastest: short promptsAdds a round trip per call
Accuracy on specific factsGood if retrieval recall is goodGood for moderate lengths; can degrade with length and mid-context positionWeak and hard to verify for many factsExact, if the source is authoritative
Global or cross-document reasoningWeak: sees only retrieved chunksStrong within the windowIndirectOnly what the API exposes
Citations and auditabilityNatural: cite retrieved chunk IDsPossible: quote spans from the promptNot possible from weightsNatural: cite the call and its result
Privacy and access controlFilter retrieval by the user's permissions per queryMust assemble a per-user context; everything sent is exposed to the modelData is baked into weights; can be extracted; deletion requires retrainingEnforced by the API's own authorisation
Corpus size limitEffectively unlimitedBounded by the context windowBounded by training data and capacityNot applicable
MaintenanceIngestion pipeline, index, evaluationMinimal infrastructure; prompt assembly and cachingDatasets, training runs, model versioning, re-evaluation on base-model updatesAPI contracts, permissions, error handling

Worked cost and latency comparison

Scenario: a customer-support assistant over a product knowledge base of 300,000 tokens (small enough to fit in a large context window), handling 10,000 questions per day. Each answer is about 300 output tokens.

We use hypothetical prices chosen for easy arithmetic: USD 3.00 per million input tokens, USD 0.30 per million cached input tokens, and USD 15.00 per million output tokens. Real prices vary by provider and model and change often; substitute your own. Output cost is the same for every option: 300×15/106=0.0045300 \times 15 / 10^6 = 0.0045 USD per query.

Option 1: long context, no caching. Input = 300,000 corpus + 200 question tokens = 300,200 tokens.

300,200×3.00106=0.9006,total=0.9006+0.0045=0.9051 USD per query300{,}200 \times \frac{3.00}{10^6} = 0.9006, \quad \text{total} = 0.9006 + 0.0045 = 0.9051 \text{ USD per query}

Times 10,000 queries: about USD 9,051 per day.

Option 2: long context with prompt caching, assuming every request hits the cache for the 300,000-token prefix (optimistic: real systems pay a premium on cache writes and lose the cache when it expires or the corpus changes):

300,000×0.30106+200×3.00106+0.0045=0.0900+0.0006+0.0045=0.0951 USD300{,}000 \times \frac{0.30}{10^6} + 200 \times \frac{3.00}{10^6} + 0.0045 = 0.0900 + 0.0006 + 0.0045 = 0.0951 \text{ USD}

About USD 951 per day, roughly a tenfold reduction.

Option 3: RAG, retrieving 8 chunks of 500 tokens plus 500 tokens of instructions and question, so 4,500 input tokens:

4,500×3.00106+0.0045=0.0135+0.0045=0.0180 USD4{,}500 \times \frac{3.00}{10^6} + 0.0045 = 0.0135 + 0.0045 = 0.0180 \text{ USD}

About USD 180 per day, plus the cost of embedding queries (negligible at these sizes) and running the vector index.

Option 4: fine-tuned model with a 700-token prompt, assuming (for simplicity) the same per-token price, although many providers charge more for custom models:

700×3.00106+0.0045=0.0021+0.0045=0.0066 USD700 \times \frac{3.00}{10^6} + 0.0045 = 0.0021 + 0.0045 = 0.0066 \text{ USD}

About USD 66 per day, plus training costs and, crucially, no citations and stale knowledge after every documentation change.

Latency and memory. Using the site's methodology, prefill costs about 2×2 \times (active parameters) FLOPs per prompt token. For a self-hosted model with 8 billion active parameters on hardware sustaining an effective 100 TFLOPS:

tprefill≈2×8×109×300,200100×1012≈48 st_{\text{prefill}} \approx \frac{2 \times 8 \times 10^{9} \times 300{,}200}{100 \times 10^{12}} \approx 48 \text{ s}

for the uncached long prompt, versus 2×8×109×4,500/1014≈0.722 \times 8 \times 10^9 \times 4{,}500 / 10^{14} \approx 0.72 s for RAG. This counts only the linear term; attention adds a cost that grows with the square of the length, so the long-context figure is an underestimate. Caching avoids recomputing the prefix, which is why cached long-context requests have a much shorter time to first token.

The KV cache (the stored keys and values for every token in the context) must also fit in memory. For a common 8B configuration with 32 layers, 8 KV heads and head dimension 128 at 2 bytes per element:

2×32×8×128×2=131,072 bytes per token≈128 KiB2 \times 32 \times 8 \times 128 \times 2 = 131{,}072 \text{ bytes per token} \approx 128 \text{ KiB}

so 300,200 tokens need about 300,200×131,072≈39.3300{,}200 \times 131{,}072 \approx 39.3 GB per concurrent request, against about 0.59 GB for a 4,500-token RAG prompt. On self-hosted hardware, long context limits how many users you can serve at once.

The calculation in code, so you can plug in your own prices and model shapes:

PRICE = {"in": 3.00, "cached_in": 0.30, "out": 15.00}   # hypothetical $ per 1M tokens

def cost_per_query(fresh_in, cached_in=0, out=300, p=PRICE):
    return (fresh_in * p["in"] + cached_in * p["cached_in"] + out * p["out"]) / 1e6

def prefill_seconds(fresh_tokens, active_params=8e9, eff_flops=100e12):
    """Linear-term estimate; cached prefix tokens are not recomputed."""
    return 2 * active_params * fresh_tokens / eff_flops

def kv_cache_gb(tokens, layers=32, kv_heads=8, head_dim=128, bytes_per=2):
    return 2 * layers * kv_heads * head_dim * bytes_per * tokens / 1e9

strategies = {                     # (fresh input tokens, cached input tokens)
    "long context, no cache": (300_200, 0),
    "long context, cached":   (200, 300_000),
    "RAG (8 x 500-token chunks)": (4_500, 0),
    "fine-tuned, short prompt":   (700, 0),
}
for name, (fresh, cached) in strategies.items():
    c = cost_per_query(fresh, cached)
    print(f"{name:28s} ${c:.4f}/q  ${c * 10_000:>7,.0f}/day  "
          f"prefill~{prefill_seconds(fresh):6.3f}s  KV~{kv_cache_gb(fresh + cached):5.2f} GB")

Running it reproduces the figures above (USD 0.9051, 0.0951, 0.0180 and 0.0066 per query) and shows the cached long-context prefill dropping to milliseconds while its KV memory stays at about 39 GB.

What the numbers do not say. Cost is only one axis. If the support corpus changes daily and answers must cite the article, fine-tuning is ruled out no matter how cheap it is. If many questions need cross-document synthesis, RAG's savings may come with an accuracy loss that costs more in escalations. Always pair the cost model with measured accuracy on your evaluation set.

Accuracy: what the research suggests

Results comparing RAG and long context depend heavily on model, task and retrieval quality, so treat any single study as indicative. Li et al. (2024) compared the two across several benchmarks and found that sufficiently capable long-context models outperformed RAG on average, while RAG was far cheaper. They proposed Self-Route: the model first tries to answer from retrieved chunks and declares whether the question is answerable from them; only questions it judges unanswerable are routed to the full long-context prompt. Because most queries were answerable from retrieval, this recovered most of the long-context quality at a fraction of the cost. The broader lesson is that the choice need not be global: it can be made per query.

Hybrid patterns

The strongest production systems usually combine approaches, each doing what it is best at:

  • RAG plus fine-tuning. Fine-tune for behaviour (output schema, tone, citing chunk IDs, refusing when context is insufficient) and use retrieval for facts. RAFT (Zhang et al., 2024) fine-tunes models specifically to answer from retrieved documents while ignoring distractor documents, improving domain RAG performance.
  • Retrieve, then read long. Use retrieval to select whole documents or large sections rather than small chunks, then rely on a long context to reason across them. This reduces the chunk-boundary problems of classic RAG while keeping prompts far below the full corpus.
  • Self-Route and escalation. Answer cheaply with RAG first, and escalate to long context, more retrieval rounds or a human when the model reports insufficient evidence.
  • Cached long context for small, stable corpora. A product manual or a codebase of moderate size can live in a cached prompt prefix, with no index to maintain.
  • Tools for live and exact data. Route prices, stock, account status and aggregates to APIs or SQL, and keep retrieval for unstructured text.
  • Distillation. Use a large long-context or agentic system to generate high-quality answers, then fine-tune a small model on them for a high-volume, narrow task, keeping retrieval for facts.

A decision procedure in words

Work through these questions in order. The first decisive answer usually settles the main architecture; later questions refine it.

  1. Is the problem behaviour or knowledge? If the model already knows enough but answers in the wrong format, tone or task framing, try prompting first and then fine-tune. Retrieval will not fix style.
  2. Does the information change continuously, or must it be exact and authoritative (prices, balances, inventory, status)? Use tool use or SQL, not documents.
  3. Do answers need citations, per-user permissions, or the ability to delete specific facts quickly? That rules out fine-tuning as the knowledge source; use RAG or long context built per user.
  4. Does the relevant corpus fit comfortably in the context window (say, well under half of it, leaving room for instructions and output)?
    • If no, use RAG, possibly retrieving whole documents into a long context.
    • If yes, go to 5.
  5. What is the query volume and latency budget?
    • Low volume, tolerant latency, or many global cross-document questions: long context, with prompt caching if the corpus is stable.
    • High volume or tight latency: RAG, or Self-Route, with long context as an escalation path.
  6. After building the knowledge path, are there remaining behaviour gaps (schema compliance, refusal behaviour, domain jargon, cost of a large model)? Add fine-tuning or distillation on top.
  7. Validate with your evaluation set: measure accuracy, faithfulness, cost and latency for the top two candidates before committing.

Decision table

SituationPrimary choiceAdd
Large, frequently updated document corpus; citations requiredRAGReranking; fine-tune for citation format if needed
One long contract or report per session, questions span the whole documentLong contextCaching if the same document is queried repeatedly
Small, stable manual; modest volumeCached long contextRAG later if volume or corpus grows
Live account or inventory questionsTool useRAG for policy text around the data
Strict output format, house style, classification at high volumeFine-tuningRAG for any facts the outputs depend on
Mixed questions, high volume, quality mattersRAG with Self-Route escalationLong context for escalated queries
Per-user private data with strict access rulesRAG with permission filters, or toolsNever fine-tune shared models on private user data

Common pitfalls

  • Fine-tuning to teach facts, then discovering the model mixes them up, cannot cite them and is stale after the next document update.
  • Assuming long context makes retrieval obsolete without measuring cost at production volume, latency, and quality on facts buried mid-context.
  • Comparing uncached long-context cost with a cached deployment or ignoring cache-write premiums and expiry when estimating savings.
  • Ignoring access control: a single long prompt or a fine-tuned model shared across users can leak documents a user is not entitled to see.
  • Treating the choice as global instead of routing per query by type and difficulty.
  • Deciding on cost alone, without measured accuracy and faithfulness on a golden set.
  • Forgetting maintenance: fine-tuned models must be retrained and re-evaluated when the base model is updated or deprecated, and RAG indexes need ingestion monitoring.

In practice

Begin with prompting plus the simplest knowledge path that satisfies your constraints: cached long context for small stable corpora, RAG for anything large, changing, permissioned or requiring citations, and tools for live data. Build the evaluation set first, then measure accuracy, faithfulness, cost per query and p95 latency for the two most plausible designs on it. Add per-query routing when your traffic mixes easy lookups with hard synthesis questions, and add fine-tuning last, for behaviour that prompting cannot reliably produce or to cut cost on a narrow high-volume task. Revisit the decision whenever prices, context limits or model capabilities change, because the break-even points move, while the underlying logic of knowledge versus behaviour versus live state does not.

Key takeaways

  • Fine-tuning mostly changes behaviour, retrieval and long context supply knowledge, and tools supply live state and actions.
  • Long-context cost and prefill latency scale with every token sent; prompt caching cuts the cost of a fixed prefix dramatically but not its memory footprint.
  • RAG keeps per-query cost low and supports citations, freshness and per-user permissions, at the price of possible retrieval misses.
  • Fine-tuning is a poor primary store for facts: it is hard to verify, cannot cite, goes stale and makes deletion require retraining.
  • The choice can be made per query: routing such as Self-Route uses cheap retrieval first and escalates to long context only when needed.
  • Decide with measured accuracy plus a cost and latency model at production volume, and revisit as prices and context limits change.

Terms in this lesson

Long-context prompting
Supplying a large portion of the relevant corpus directly in the prompt on each request instead of retrieving selected passages.
Prompt caching
Reusing the computed key-value state of an unchanged prompt prefix across requests to reduce cost and time to first token.
Fine-tuning
Further training a pre-trained model's weights, or small adapter weights, on task-specific examples.
LoRA
A parameter-efficient fine-tuning method that trains low-rank update matrices added to frozen weight matrices.
Prefill
The phase in which the model processes the entire prompt before generating the first output token.
Self-Route
A hybrid strategy in which the model answers from retrieved chunks when it judges them sufficient and otherwise falls back to long-context prompting.
Knowledge injection
Adding new factual knowledge to a language model system, whether through weights, retrieval or the prompt.

Check your understanding

  1. 1.

    A legal team wants answers grounded in 40,000 frequently amended internal documents, with citations and per-matter access restrictions. Which primary architecture fits best?

  2. 2.

    Using the lesson's hypothetical prices (USD 3/M input, 15/M output), what is the cost of a query with 50,000 uncached input tokens and 400 output tokens?

  3. 3.

    What does prompt caching NOT reduce for a long fixed prefix?

  4. 4.

    A company fine-tuned a model on its product catalogue to answer price questions. Prices change weekly and answers are often outdated. What is the best fix?

  5. 5.

    For a model with 48 layers, 8 KV heads, head dimension 128 and 2-byte elements, how much KV-cache memory does a 100,000-token context need?

Exercises

Work each problem before opening the solution.

  1. Exercise 1Core

    With the lesson's hypothetical prices, a corpus of 120,000 tokens, 2,000 queries per day, 250 output tokens per answer and 200-token questions, compute the daily cost of (a) uncached long context, (b) fully cached long context (ignore cache-write premiums), and (c) RAG with 6 chunks of 400 tokens plus 400 tokens of instructions and question.

    Show solution

    Output per query: 250×15/106=0.00375250 \times 15/10^6 = 0.00375.

    (a) Input 120,200×3/106=0.3606120{,}200 \times 3/10^6 = 0.3606. Per query 0.3606+0.00375=0.364350.3606 + 0.00375 = 0.36435. Daily: 0.36435×2000=728.700.36435 \times 2000 = 728.70, so USD 728.70.

    (b) Cached 120,000×0.30/106=0.036120{,}000 \times 0.30/10^6 = 0.036; fresh 200×3/106=0.0006200 \times 3/10^6 = 0.0006. Per query 0.036+0.0006+0.00375=0.040350.036 + 0.0006 + 0.00375 = 0.04035. Daily: 0.04035×2000=80.700.04035 \times 2000 = 80.70, so USD 80.70.

    (c) Input 6×400+400=2,8006 \times 400 + 400 = 2{,}800 tokens: 2800×3/106=0.00842800 \times 3/10^6 = 0.0084. Per query 0.0084+0.00375=0.012150.0084 + 0.00375 = 0.01215. Daily: 0.01215×2000=24.300.01215 \times 2000 = 24.30, so USD 24.30.

    Caching cuts long-context cost by about 9x here; RAG is a further ~3.3x cheaper, so the choice should rest on measured accuracy differences and on whether the corpus is stable enough to keep the cache warm.

  2. Exercise 2Core

    Apply the lesson's decision procedure to this scenario and state the architecture: An internal assistant answers engineers' questions about a 25,000-token API style guide that changes twice a year. Volume is about 50 questions per day. Engineers often ask questions that require comparing several sections. No access restrictions apply within the company.

    Show solution
    1. Knowledge problem, not behaviour.
    2. Not live data.
    3. Citations are helpful but not mandated; no per-user permissions; deletions rare. Fine-tuning is still a poor knowledge store, so not primary.
    4. 25,000 tokens fits comfortably in a large context window.
    5. Low volume (50/day), and questions span several sections, which favours whole-document reasoning.

    Choice: long-context prompting with the full guide, using prompt caching since the guide is stable and identical across requests. Ask the model to quote the relevant section headings for traceability. At 50 queries per day the cost is small even uncached (with the lesson's prices, about 25,000×3/106=0.07525{,}000 \times 3/10^6 = 0.075 USD of input per query). Revisit with RAG only if the guide grows substantially or volume rises sharply.

  3. Exercise 3Challenge

    Extend the lesson's cost model to Self-Route: a fraction ff of queries are answered by RAG alone, and the remainder first run RAG (and fail the self-check) and then run uncached long context. Using the lesson's support scenario per-query costs (RAG USD 0.0180, uncached long context USD 0.9051), write a Python function for expected cost per query, and find the minimum ff at which Self-Route is cheaper than a cached long-context deployment at USD 0.0951 per query.

    Show solution

    Queries answered by RAG cost 0.0180. The rest pay for both attempts: 0.0180+0.9051=0.92310.0180 + 0.9051 = 0.9231.

    E[c]=f×0.0180+(1−f)×0.9231=0.9231−0.9051fE[c] = f \times 0.0180 + (1 - f) \times 0.9231 = 0.9231 - 0.9051 f

    def self_route_cost(f, rag=0.0180, long_ctx=0.9051):
        return f * rag + (1 - f) * (rag + long_ctx)
    
    def break_even_f(target, rag=0.0180, long_ctx=0.9051):
        # solve rag + (1 - f) * long_ctx = target
        return 1 - (target - rag) / long_ctx
    
    f_star = break_even_f(0.0951)
    print(round(f_star, 4), round(self_route_cost(f_star), 4))   # 0.9148 0.0951
    

    Setting 0.9231−0.9051f=0.09510.9231 - 0.9051 f = 0.0951 gives f=0.828/0.9051≈0.915f = 0.828 / 0.9051 \approx 0.915. Self-Route with uncached fallback beats a fully cached long-context deployment only if more than about 91.5% of queries are answered by RAG alone. If the fallback itself uses the cached prompt (USD 0.0951), Self-Route costs 0.0180+(1−f)×0.09510.0180 + (1-f) \times 0.0951, which is below 0.0951 whenever f>0.189f > 0.189, so caching the fallback path matters a great deal.

  4. Exercise 4Challenge

    A hospital network wants an assistant that (1) drafts discharge summaries in a strict house format, (2) answers clinicians' questions about 3,000 internal clinical protocols updated monthly, and (3) shows the current bed availability. Propose a hybrid architecture, assigning each requirement to an approach, and list the privacy controls needed.

    Show solution

    Architecture

    • (1) Discharge format is behaviour: start with a strong prompt and templates; if format compliance remains insufficient, fine-tune (for example with LoRA) on de-identified, approved example summaries. The patient-specific facts come from the record at run time, not from weights.
    • (2) Protocols are a large, monthly-updated corpus needing citations: RAG over the protocol library with document version metadata, reranking, and answers that cite protocol ID and version. Re-index on each update and run the golden-set regression before publishing a new index.
    • (3) Bed availability is live state: tool use calling the bed-management system's API with the clinician's authorisation.
    • Routing: classify each request into drafting, protocol question or operational lookup; drafting calls the EHR tool for the patient's data plus the fine-tuned or prompted drafting model.

    Privacy controls

    • Never fine-tune on identifiable patient data unless a formal governance and legal review approves it; prefer de-identified examples.
    • Enforce access control in the tools and in retrieval filters using the clinician's identity, not the prompt.
    • Log access for audit, minimise what patient data enters prompts, and use a deployment whose data-handling terms meet the applicable health-privacy regulations.
    • Keep the assistant's role as drafting support with clinician review before anything enters the record.

Further reading

Go further

Sources

Fact-checked and last reviewed 2026-11-05

Stay in the loop
Prometheus OS™ · Native AI OS · Built for the future © 2025 - 2026