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.

BeginnerIntermediateExpert · 14 min read · Last updated:

In short

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.

Beginner Four levers and two kinds of gap

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

LeverWhat changesGood forWeak at
PromptingInstructions and examples sent with each requestRole, rules, format, tone, how to use toolsLarge bodies of knowledge; perfect consistency
Retrieval (RAG)Relevant passages are searched for and added to the requestLarge, changing or permission-controlled facts; citationsQuestions that need the whole collection at once
Long contextThe whole document or set of files is sentBounded material: one contract, one codebase module, one case fileCost and delay at high volume; material that keeps growing
Fine-tuningThe model's weights, or a small add-on to themStable style, narrow classification, specialized formats, replacing long promptsFacts 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.

Read failures30 to 100 real cases
Name the causeknowledge, behavior, tool or data
Cheapest fixprompt before training
Measure againsame cases
↺ Repeat until the result is good enough, then stop adding machinery
The choice of method comes after the diagnosis, not before it.

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.

A quick test for knowledge versus behavior

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.

Intermediate What each lever can and cannot do

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:

FormYou provideTypical use
Supervised fine-tuningInputs paired with ideal outputsConsistent format, classification, house style
Preference tuningPairs of outputs with the better one markedTone and judgment that are easier to compare than to write
Reinforcement fine-tuningTasks and a grader that scores resultsProblems with checkable answers
DistillationOutputs from a stronger model, filtered for qualityMoving 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.

Check availability before you plan around it

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.

NeedPromptingRetrievalLong contextFine-tuning
Facts that change weeklyPoorStrongGood if smallPoor
Cite the source of an answerPoorStrongGoodPoor
Different users see different dataPoorStrongGood with filteringPoor
Reason across one whole documentFairWeakStrongFair
Fixed output formatGoodPoorPoorStrong
Very low cost per request at scaleFairGoodWeakStrong with a small model
Ready this weekStrongFairStrongWeak
Easy to correct a mistakeStrongStrongStrongWeak

What this means for agents

Agents add failures that a question-and-answer system does not have. Match each to the right remedy:

Agent failureTry firstThen
Picks the wrong toolFewer tools, clearer descriptions, examplesRouting by task type, or tuning on tool-choice examples
Malformed argumentsStrict schemas and validation with a helpful errorTuning for that tool set
Does not know a procedurePut the procedure in the instructions or retrieve itEncode the steps as a workflow in code
Breaks a hard business ruleEnforce the rule in code before the action runsAdd the rule to the prompt so the agent plans around it
Stops early or loopsExplicit completion criteria and limitsA stronger model; see Agent Decisions: Confidence, Stopping, Loops and Budgets
Rules are not a training problem

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.

Expert Combining levers and owning the consequences

Most real systems combine them

Code and policyPermissions, limits and validation that always apply
PromptRole, rules, tool guidance, a few examples
Retrieved or full documentsCurrent facts for this request
Model, tuned only if neededFormat and judgment for a narrow task
Each layer handles what it handles best.

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.

Illustrative example: a claims assistant

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.

Set a stopping rule in advance

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

Next steps