Fine-Tuning vs RAG vs Prompting vs Long Context
Four ways to change what a model does, what each one really fixes, and how to pick without guessing.
First read your failures and name their causes. Fix unclear behavior with a better prompt. Supply large or changing facts with retrieval. Use long context when the material is bounded and must be reasoned over as a whole. Consider fine-tuning last, for behavior that must be very consistent, that you can show with many good examples, and that cheaper changes did not fix.
What you will learn: what each of the four levers changes, how to diagnose which one you need, what long context costs compared with retrieval, when fine-tuning pays off, and how to combine them.
Prerequisites: How LLMs Power Agents: Transformers, Tokens and Sampling and, ideally, Choosing Models: Reasoning, Open-Weight and Hosted.
Start with two kinds of gap
When an agent gets something wrong, it usually lacks one of two things. It may lack knowledge: it does not know your refund policy, last week's incident, or the contents of a customer's file. Or it may lack behavior: it knows enough, but it answers in the wrong format, picks the wrong tool, ignores a rule or varies from one run to the next.
The distinction matters because the remedies differ. Teaching facts through training is slow and hard to undo. Supplying facts at the moment of use is quick and easy to correct. Changing behavior, on the other hand, can often be done with a clearer instruction, and only sometimes needs training.
The four levers
| Lever | What changes | Good for | Weak at |
|---|---|---|---|
| Prompting | Instructions and examples sent with each request | Role, rules, format, tone, how to use tools | Large bodies of knowledge; perfect consistency |
| Retrieval (RAG) | Relevant passages are searched for and added to the request | Large, changing or permission-controlled facts; citations | Questions that need the whole collection at once |
| Long context | The whole document or set of files is sent | Bounded material: one contract, one codebase module, one case file | Cost and delay at high volume; material that keeps growing |
| Fine-tuning | The model's weights, or a small add-on to them | Stable style, narrow classification, specialized formats, replacing long prompts | Facts that change; explaining where an answer came from |
Retrieval augmented generation (RAG) means searching your own material for passages that match the question and placing them in the prompt. Long context means skipping the search and sending everything, which models with large context windows allow. Fine-tuning means continuing the model's training on examples of the behavior you want.
Diagnose before you build
Collect the cases that failed. Have a person who knows the work read each one and write down a single main cause. Then count. This takes a few hours and often changes the plan, because the loudest complaint is rarely the most common cause. The script below uses invented labels for 40 failures:
"""Let error analysis choose the remedy. Count causes before building."""
from collections import Counter
REMEDY = {
"unclear instruction": "improve the prompt",
"missing example": "improve the prompt",
"fact not available": "retrieval",
"fact out of date": "retrieval",
"evidence in context, ignored": "shorten and order the context",
"style or format drifts": "structured output, then consider fine-tuning",
"skill not learned": "stronger model, then consider fine-tuning",
"bad tool or data": "fix the tool or data",
}
def diagnose(failures):
causes = Counter(cause for _, cause in failures)
remedies = Counter()
for cause, count in causes.items():
remedies[REMEDY.get(cause, "investigate further")] += count
return causes, remedies
if __name__ == "__main__":
# 40 failed cases, each labeled by a person who read it. Invented data.
labels = (["fact not available"] * 14 + ["fact out of date"] * 5
+ ["unclear instruction"] * 9 + ["bad tool or data"] * 6
+ ["style or format drifts"] * 4
+ ["evidence in context, ignored"] * 2)
failures = [(f"case-{n:02}", cause) for n, cause in enumerate(labels, 1)]
_, remedies = diagnose(failures)
total = len(failures)
for remedy, count in remedies.most_common():
print(f"{count:>3} of {total} ({count / total:>4.0%}) {remedy}")
Output:
19 of 40 ( 48%) retrieval
9 of 40 ( 22%) improve the prompt
6 of 40 ( 15%) fix the tool or data
4 of 40 ( 10%) structured output, then consider fine-tuning
2 of 40 ( 5%) shorten and order the context
In this invented set, almost half the failures need facts the model did not have, so training a model would not have helped with them. A further share comes from broken tools or bad data, which no model change fixes. Only a tenth point toward fine-tuning, and even those should try structured output first. See Message Roles, Structured Output and Function Calling.
Paste the correct source material into the prompt by hand and run the failing case again. If the answer becomes right, you have a knowledge-supply problem. If it stays wrong with the facts in front of it, look at instructions, context order, or the model itself.
Prompting comes first
A prompt change takes minutes, costs nothing to build, and is reversed by restoring the old text. Before you try anything else:
- State the task, the rules and the finished result plainly, with the reason behind each rule that is not obvious.
- Give a few varied examples, including a hard one and a case where the agent should decline or ask.
- Separate instructions from data with clear markers, as shown in Prompt Templates and Tool-Use Prompting.
- Describe each tool so that a new colleague could choose correctly between them. See Designing Tool Schemas and Contracts.
- Use a stronger model for one test run. If it succeeds with the same prompt, you know the gap is capability.
Prompting reaches its limit when the instructions grow long and contradictory, when adding one rule breaks another, or when you need the same output in thousands of cases and still see variation. Those are the signals to look further.
Retrieval for facts
Retrieval keeps knowledge outside the model. To update a policy you update a document. To delete a customer's data you delete it from the index and its sources. You can show which passage supported an answer, and you can filter results by what the current user is allowed to see, which a trained model cannot do. See RAG Security, Freshness and Cost.
The price is a second system to build and run: collecting documents, splitting them, indexing, searching and checking that the search finds the right thing. When retrieval fails, the model may answer confidently from the wrong passage. Measure the search separately from the answer, as RAG Evaluation, Grounding and Debugging explains.
Long context: simple, until volume grows
If the material fits in the context window and you have few requests, sending all of it is the simplest design. There is no index to maintain and no search to go wrong. It also suits questions such as "which clauses in this agreement conflict with each other?", where the relevant parts cannot be found by searching for the question.
Two costs rise with size. Money and time grow with every token sent, and attention is not perfectly even: the study Lost in the Middle found that models could use information at the start or end of a long input better than information in the middle. Newer models may behave differently, so test with your own documents.
Provider prompt caching lowers the price of a repeated beginning. The next script compares three designs with invented prices:
"""Input cost: send the whole handbook, or only the relevant passages?"""
def monthly(requests, fixed, reference, price, cached_price=None, hit=0.0):
"""Prices are US dollars per million input tokens."""
if cached_price is None:
cached_price = price
per_request = fixed * price + reference * (
hit * cached_price + (1 - hit) * price)
return requests * per_request / 1_000_000
if __name__ == "__main__":
PRICE, CACHED = 2.00, 0.20 # invented example prices
FIXED = 2_000 # instructions and question
HANDBOOK, PASSAGES = 150_000, 4_000
print("requests whole, no cache whole, 80% cached retrieval")
for requests in (1_000, 20_000, 500_000):
a = monthly(requests, FIXED, HANDBOOK, PRICE)
b = monthly(requests, FIXED, HANDBOOK, PRICE, CACHED, hit=0.8)
c = monthly(requests, FIXED, PASSAGES, PRICE)
print(f"{requests:>8,} ${a:>13,.0f} ${b:>15,.0f} ${c:>9,.0f}")
Output:
requests whole, no cache whole, 80% cached retrieval
1,000 $ 304 $ 88 $ 12
20,000 $ 6,080 $ 1,760 $ 240
500,000 $ 152,000 $ 44,000 $ 6,000
Caching cuts the whole-handbook bill sharply, yet retrieval remains far cheaper in this example because it sends much less. The calculation deliberately leaves out items that you must add for a real decision: fees some providers charge to write the cache, cache expiry between quiet periods, the cost of building and running a search system, and output tokens. At 1,000 requests a month the difference may not repay a day of engineering. At 500,000 it clearly can.
Fine-tuning: training for behavior
Fine-tuning continues training on your examples. Several forms exist:
| Form | You provide | Typical use |
|---|---|---|
| Supervised fine-tuning | Inputs paired with ideal outputs | Consistent format, classification, house style |
| Preference tuning | Pairs of outputs with the better one marked | Tone and judgment that are easier to compare than to write |
| Reinforcement fine-tuning | Tasks and a grader that scores results | Problems with checkable answers |
| Distillation | Outputs from a stronger model, filtered for quality | Moving a narrow task to a smaller, cheaper model |
With open-weight models, a common technique is LoRA (low-rank adaptation), which trains a small set of extra weights and leaves the original ones unchanged. The add-on is small, cheap to store and can be removed.
Fine-tuning tends to pay off when a task is narrow and stable, volume is high, you hold hundreds of reviewed examples, and a small tuned model could replace a large model with a long prompt. It tends to disappoint when the goal is to teach facts, when the rules change monthly, or when nobody has time to maintain the training data.
Fine-tuning services change. OpenAI's deprecations page records a wind-down of self-serve fine-tuning: organizations that had never run a job lost the ability to create one on May 7, 2026, further restrictions followed on July 2, 2026, and from December 15, 2026, no organization will be able to create new self-serve training jobs. Inference on existing tuned models continues until the base model is retired. Verify the current position with any provider, and consider open-weight models where you need control over training. See Open-Source Stack and Local LLM Agents.
Decision matrix
Score your own situation against this table. It is a guide to likely fit, not a rule.
| Need | Prompting | Retrieval | Long context | Fine-tuning |
|---|---|---|---|---|
| Facts that change weekly | Poor | Strong | Good if small | Poor |
| Cite the source of an answer | Poor | Strong | Good | Poor |
| Different users see different data | Poor | Strong | Good with filtering | Poor |
| Reason across one whole document | Fair | Weak | Strong | Fair |
| Fixed output format | Good | Poor | Poor | Strong |
| Very low cost per request at scale | Fair | Good | Weak | Strong with a small model |
| Ready this week | Strong | Fair | Strong | Weak |
| Easy to correct a mistake | Strong | Strong | Strong | Weak |
What this means for agents
Agents add failures that a question-and-answer system does not have. Match each to the right remedy:
| Agent failure | Try first | Then |
|---|---|---|
| Picks the wrong tool | Fewer tools, clearer descriptions, examples | Routing by task type, or tuning on tool-choice examples |
| Malformed arguments | Strict schemas and validation with a helpful error | Tuning for that tool set |
| Does not know a procedure | Put the procedure in the instructions or retrieve it | Encode the steps as a workflow in code |
| Breaks a hard business rule | Enforce the rule in code before the action runs | Add the rule to the prompt so the agent plans around it |
| Stops early or loops | Explicit completion criteria and limits | A stronger model; see Agent Decisions: Confidence, Stopping, Loops and Budgets |
A limit such as "refunds above 100 dollars need approval" must be enforced by the system that executes the refund. Training makes a behavior likely, not certain. See Action Guardrails and Policy Engines.
Most real systems combine them
A useful hybrid retrieves documents and then gives the model a generous amount of each one, rather than tiny fragments. Another routes simple, frequent requests to a small tuned model and sends everything else to a general model. See Model Routing, Fallbacks and Gateways.
What fine-tuning commits you to
- Data duties. Training examples may contain personal or confidential data, and a model can reproduce parts of them. Removing one person's data from a trained model is far harder than deleting a row. Remove sensitive values before training. See PII Redaction and Data Leakage Prevention.
- Safety checks. Research has shown that fine-tuning can weaken a model's safety behavior, even when the training data looks harmless. Run your safety tests again on every tuned version.
- Retirement. A tuned model usually depends on a base model. When the base is retired you repeat the work, so keep the data, the recipe and the evaluation set under version control.
- Hidden drift. If your policy changes, old examples teach the old policy. Assign an owner for the training data.
- Hosting. Tuned models may be priced or deployed differently from shared ones. Include that in the estimate.
Prove that a change helped
Hold back a test set that is never used for prompts or training. Compare the old and new designs on the same cases, repeating runs because outputs vary. Report quality, cost per completed task and delay together, and look at the cases that newly fail, not only at the average. Model Evaluation and Failure Modes gives the method.
An invented insurer finds that its assistant gives outdated cover limits and writes summaries in inconsistent layouts. It moves the policy documents into retrieval filtered by product and date, which addresses the limits. It then adds a required output schema, which addresses the layout. It considers fine-tuning for tone, measures reviewer corrections for a month, and concludes that the remaining edits do not justify maintaining a trained model.
Before work starts, write down the result that would be good enough, for example the share of cases accepted without edits and the maximum cost per task. Without that line, teams keep adding machinery because each new lever is interesting.
Decision checklist
- Failures are collected, read and labeled with causes.
- Pasting the right source by hand has been tried on failing cases.
- Prompt, tool descriptions and structured output were improved first.
- Facts that change or need permissions live outside the model.
- Long-context cost has been calculated at expected volume.
- Hard rules are enforced in code.
- Any fine-tuning plan names the data owner, the test set and the retirement plan.
Frequently asked questions
Does a long context window make RAG unnecessary?
For small, stable collections it can. For large or changing collections, per-user permissions or high volume, retrieval still reduces cost and gives control over what the model sees.
Can I fine-tune a model on my company documents so it knows them?
Training on documents does not give reliable recall, cannot show sources and goes stale. Retrieval is normally the better way to supply knowledge.
How many examples does fine-tuning need?
It depends on the model and the task. Start with a few dozen to a few hundred carefully reviewed examples, measure on held-out cases, and add more where errors cluster.
References and further reading
- Lewis et al., Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks
- Liu et al., Lost in the Middle: How Language Models Use Long Contexts
- Hu et al., LoRA: Low-Rank Adaptation of Large Language Models
- Qi et al., Fine-tuning Aligned Language Models Compromises Safety
- OpenAI: Deprecations, including the fine-tuning wind-down
Next steps
RAG Explained and Agentic RAG
Build the retrieval lever from the ground up.
Model Evaluation and Failure Modes
Measure whether a change really helped.
Inference Optimization and Quantization
Make the chosen model faster and cheaper to serve.