Sub topic 3
RAG, Fine-Tuning, and Long Context: Choosing Between Them
This chapter assumes you know the basics of Python, how LLMs are prompted, and what the previous chapter said about the limits of model knowledge: a model's training data has a cutoff date, it knows nothing about your private documents, and its context window is finite. Three techniques address those limits. They solve different problems, and choosing the wrong one is an expensive mistake.
The three options
Retrieval-augmented generation (RAG) looks up relevant passages from an external store at query time and places them in the prompt. The model's weights do not change.
Fine-tuning continues training a model on your own examples, so the weights change. It is good at teaching behavior: a tone, an output format, a classification scheme, or a domain's vocabulary. It is poor at teaching facts reliably.
Long context means putting whole documents, or a whole corpus if it fits, directly into the prompt. There is no retrieval step. The model reads everything on every request.
The useful question is not "which is best?" but "what is missing?" If the model lacks knowledge, you supply it at query time (RAG or long context). If it lacks a skill or style, you train it (fine-tuning).
What each approach changes
| Property | RAG | Fine-tuning | Long context |
|---|---|---|---|
| What it adds | Facts, at query time | Behavior, style, format | Facts, at query time |
| Updating knowledge | Re-index changed documents | Retrain | Change the prompt |
| Source citations | Natural, since you know which chunk was used | Not available | Possible, but you must label the documents |
| Per-request cost | Small prompt plus a search | Often a smaller prompt | Large prompt on every request |
| Upfront cost | Build and maintain a pipeline | Collect data, train, evaluate | Almost none |
| Access control | Filter at retrieval time | Cannot be removed after training | Control what you include in the prompt |
| Main failure | Relevant passage not retrieved | Confident but wrong facts | Detail lost in a very long prompt |
Why fine-tuning is a poor way to add facts
Training on documents does not make the model a reliable database. The facts end up spread across the weights, and the model may blend them or invent plausible variations. You also cannot point to the source of a statement, and you cannot remove a fact later, such as a document a user is no longer allowed to see. If a policy changes next week, you must retrain.
Fine-tuning works well when the problem is behavior:
- Output must follow a strict schema or house style.
- A narrow task (such as routing support tickets) needs higher accuracy than prompting alone gives.
- A smaller, cheaper model must imitate a larger one on a fixed task.
- Domain jargon is handled badly by the base model.
Why long context does not replace RAG
Context windows now hold hundreds of thousands of tokens, so a small corpus can simply be pasted in. This is a legitimate choice, and for a few documents it is often the simplest one. Limits appear as the corpus grows:
- Cost and latency. You pay for every input token on every request. A 200,000-token prompt sent a thousand times a day costs far more than a 3,000-token RAG prompt.
- Accuracy. Models tend to use information in the middle of a long prompt less reliably than information near the start or end. More text also gives more irrelevant material to distract the model.
- Size. Many corpora are millions of tokens and will never fit.
- Access control. Anything in the prompt is visible to the model for that user. With RAG you can filter by permission before the text enters the prompt.
Long context and RAG also combine well. Retrieve generously, then use a larger window to include whole sections instead of tiny chunks.
A decision flow
Encoding the criteria in code
A rough cost estimate often settles the long-context question. The function below compares the input cost of the two approaches for a given workload. It uses a price per million input tokens that you supply from your provider's price list.
def monthly_input_cost(tokens_per_request, requests_per_day, price_per_million, days=30):
total_tokens = tokens_per_request * requests_per_day * days
return total_tokens / 1_000_000 * price_per_million
price = 3.00 # example price in dollars per million input tokens
long_context = monthly_input_cost(150_000, 2_000, price)
rag = monthly_input_cost(4_000, 2_000, price)
print(f"Long context: ${long_context:,.2f} per month")
print(f"RAG: ${rag:,.2f} per month")
print(f"Ratio: {long_context / rag:.1f}x")With these numbers, long context costs $27,000 per month and RAG costs $720, a ratio of 37.5. The RAG figure leaves out embedding, search infrastructure, and engineering time, so it understates the true cost. At low volume the comparison reverses: with 20 requests per day, long context costs $270 per month, which may be cheaper than running a vector database.
Some providers cache a repeated prompt prefix at a discount. If every request starts with the same large document set, caching can narrow the gap. Check whether your provider offers it and what the cache lifetime is.
Edge cases and common errors
- Using fine-tuning to fix stale answers. If the complaint is "the model doesn't know our new pricing," the cause is missing knowledge, so fine-tuning is the wrong tool. Retrieve the pricing page instead.
- Using RAG to fix style problems. If answers are correct but badly formatted, adding retrieved text does not help. Improve the prompt first, then consider fine-tuning.
- Skipping the baseline. Before building a pipeline, test long context on a sample. If it meets your quality and cost needs, you have saved yourself the pipeline.
- Treating the choices as exclusive. Production systems often fine-tune for format and tone, retrieve for facts, and use a generous window for the assembled prompt.
- Ignoring data sensitivity. Training data can leak through model outputs, and a trained-in fact cannot be revoked per user. Where permissions differ across users, retrieval-time filtering is the safer design.
Worked scenarios
- Internal HR policy assistant, 400 pages, updated monthly, answers must cite sections. The knowledge changes, citations are required, and permissions may differ by region. Use RAG.
- Assistant that must always reply in a fixed JSON schema for a downstream system. The need is behavior. Try prompting with examples, then fine-tune if errors persist.
- One 30-page contract, reviewed by a lawyer a few times a day. The document is small and volume is low. Use long context.
- Support bot that must match the company's voice and answer from a changing knowledge base. Combine them: fine-tune for voice, RAG for facts.
Exercise
A team's chatbot gives out-of-date return policies. A colleague proposes fine-tuning the model on the new policy documents each quarter. Give two reasons RAG is a better fit, and name one situation where fine-tuning would still be useful for this chatbot.
Show answer
First, the problem is missing or stale knowledge, and RAG fixes it by re-indexing the changed documents without retraining, so updates take effect immediately instead of quarterly. Second, RAG can cite the specific policy passage used, and it can filter by region or user permission, which fine-tuning cannot do. Fine-tuning would still help if the bot must follow a fixed tone, response template, or escalation format, because those are behaviors rather than facts.
Exercise
Using monthlyinputcost with a price of 3.00 dollars per million tokens, compute the monthly input cost for a long-context design with 100,000 tokens per request and 50 requests per day. Is it likely cheaper than a RAG system, and what costs does the comparison leave out?
Show answer
100,000 50 30 = 150,000,000 tokens, which is 150 million, so the cost is 150 * 3.00 = $450 per month. At this volume it may well be cheaper than RAG, because RAG adds embedding costs, a vector store or search service, ingestion pipelines, evaluation, and engineering time that the token-only comparison omits.