IamBishal
AI Engineering

Fine-Tuning vs RAG vs Prompt Engineering: A Decision Framework

Diagnose whether your LLM feature is missing knowledge, misbehaving, breaking format or costing too much, then try the cheapest lever and let an eval decide.

Bishal Saha

16 min read

A vector store with no eval is as speculative as a training job with no eval.
Bishal Saha

Picture a feature that works in the demo. In production, the assistant quotes a policy that was replaced last quarter, wraps its JSON in a friendly paragraph, and costs more per request than anyone budgeted. One person in the review says it's time to fine-tune. Another says you need RAG. A third says the prompt just needs work.

The usual way to settle this is a feature table comparing fine-tuning vs RAG vs prompt engineering. A table compares tools. It can't tell you what is broken in your system.

The three levers fix different problems. Retrieval supplies knowledge that changes. Fine-tuning shapes behaviour, style and format that instructions can't fix. Prompting is the cheapest lever for both, so it goes first. My work centres on LLM applications, RAG and AI backend services, and this is the order I'd want the decision made in: diagnose the failure, try the cheapest lever, let an eval set settle the rest.

1. Name the failure before you pick a lever

Pull real failing outputs from logs or user reports and give each one a label:

  • Knowledge gap. The model lacks the facts or can't see them, like last year's leave allowance quoted after the policy changed.
  • Behaviour or style gap. The content is right but the conduct is wrong: a breezy tone for a regulated audience, or a refusal on a legitimate request.
  • Format or structure gap. The output breaks the contract your code depends on: Sure! The category is "billing". when the parser expects billing.
  • Cost or latency constraint. Quality is acceptable, but each request costs too much or takes too long.

Label each failure, not the feature. A support assistant can quote a stale price in one response and break the schema in the next: two problems, two fixes, each routed through its own branch.

The common mistake is mismatch: a behaviour fix for a knowledge problem, or the reverse. The label decides which lever to try and which eval proves it worked.

2. The decision flow

Every path tries the cheaper lever before any training. A knowledge gap usually reaches RAG when the facts are too large to send with every request, counting both the tokens and the work of assembling the right subset. Per-user permissions, per-document deletion or mandatory citations can justify retrieval over a small corpus too.

flowchart TD
    A["Label each failing output"] --> B{"Failure type"}
    B -->|Knowledge| FIT{"Facts small enough to send with every request, with no per-user access rules?"}
    FIT -->|Yes| KC["Put the facts in the prompt, with sources"]
    FIT -->|No| RAG["Permission-aware RAG"]
    RAG --> RH{"Right passages retrieved for eval questions?"}
    RH -->|No| FR["Fix retrieval: chunking, hybrid search, query rewriting, filters"]
    FR --> RQ{"Right passages retrieved now?"}
    RQ -->|Yes| E
    RQ -->|No| TR["Tune the embedder or a re-ranker"]
    TR --> E
    RH -->|Yes| E["Re-run the eval"]
    B -->|Behaviour or format| P["Improve instructions, few-shot examples, structured output"]
    P --> PQ{"Still failing on the eval?"}
    PQ -->|Yes| FT["Fine-tune for behaviour or format consistency"]
    PQ -->|No| E
    B -->|Cost or latency| SP["Trim the prompt, test a smaller model"]
    SP --> SQ{"Still over budget at equal quality?"}
    SQ -->|Yes| DS["Fine-tune for shorter prompts or distil"]
    SQ -->|No| E
    KC --> E
    FT --> E
    DS --> E
    E -.->|new failures, labelled again| A

Read it one failure type at a time. Every branch ends at the eval, which sends new failures back with a fresh label. That loop is how combinations happen: if RAG answers now cite the right passage but break the output format, those failures re-enter as format failures, and only if the prompt can't fix them does the system become RAG plus a fine-tuned generator. Nobody picks "both" up front.

3. Prompting is the cheapest lever, and it has a ceiling

Prompting changes only the request: instructions, examples and context. With no pipeline and no training run, iteration is fast. Some "the model is bad at this" complaints turn out to be a prompt that never said what a good answer looks like. For the ticket classifier in the scenarios below, the difference is concrete:

text
Before: Classify this support ticket.

After:  Reply with exactly one label: billing, technical, account or other.
        No punctuation and no explanation. If none fits, reply other.
        Ticket: "I was charged twice this month."   -> billing
        Ticket: "The export button does nothing."   -> technical

The second states the contract, then shows it.

The ceiling is real. Prompting can't supply a corpus bigger than one request can carry, or teach behaviour that needs more examples than the context window holds. Treat your best prompt as the baseline that RAG or fine-tuning has to beat on the eval.

4. RAG changes what the model can see, not how it behaves

Lewis et al.'s original RAG paper paired a pre-trained seq2seq model (parametric memory) with a dense vector index of Wikipedia (non-parametric memory), read through a neural retriever. They named providing provenance and updating world knowledge as open problems that explicit non-parametric memory can overcome. Those remain the reasons to choose RAG: knowledge that changes, private knowledge the base model never saw, and answers that must cite a source someone can check.

It doesn't fix tone, format consistency or reasoning habits. If the model ignores the retrieved passage, or answers in a shape your parser rejects, better retrieval won't help.

Its operational cost starts with ingestion and parsing for PDFs, wikis and tickets, and chunking decisions that quietly decide what the model can find. Every request then carries the retrieved passages as extra input tokens, with a retrieval hop and any re-ranker in the latency path. You also get a second eval surface, because retrieval and answers fail separately: the right passage can come back and be misused, or the wrong one can be summarised fluently. A RAG system is a data pipeline with an LLM at the end; plan ownership and on-call on that basis.

5. Fine-tuning shapes behaviour; it is a poor way to teach facts

OpenAI's fine-tuning guide says fine-tuning can be time-consuming, but can enable consistent response formatting or handling of novel inputs. It lets you train on more example inputs and outputs than fit in one request's context window, which is where few-shot prompting runs out. And it allows shorter prompts, saving tokens at scale and possibly lowering latency, so it is a cost lever as well as a quality one.

OpenAI's accuracy-optimisation guide puts numbers on that trade-off for an Icelandic-language task scored with BLEU. Few-shot prompting gave a real but bounded gain: gpt-4 went from 62 zero-shot to 70 with three examples. Fine-tuning on 1,000 examples reached 78 with gpt-3.5-turbo and 87 with gpt-4, so the tuned gpt-3.5-turbo beat few-shot gpt-4. That is one task, in one language, on one vendor's model snapshots, so read it as the shape of the trade-off, not a rate to expect.

Two variants matter for cost and control. Distillation trains a smaller student model on a stronger teacher's outputs for one task; the cost scenario below covers when that pays. On open-weight models, LoRA freezes the pre-trained weights and trains small low-rank matrices added to each Transformer layer, which sharply cuts the number of trainable parameters. I treat it as the same lever for the same jobs, except that the weights, the data and the serving stay with you.

Knowledge is where fine-tuning is weak. Ovadia et al. found that LLMs struggle to learn new facts through unsupervised fine-tuning, and that exposure to many variations of the same fact can help. In practice, that means generating and curating paraphrases for each fact you want learned, a data-preparation burden RAG doesn't carry.

Gekhman et al. ran a controlled closed-book QA study that varied the share of fine-tuning examples introducing new knowledge. Those examples were learned significantly more slowly than ones consistent with what the model already knew, and once learned, they linearly increased its tendency to hallucinate. Their conclusion: LLMs mostly acquire factual knowledge in pre-training, and fine-tuning teaches them to use it more efficiently.

Both studies date from 2023 and 2024 and concern factual knowledge, not every RAG-versus-tuning trade-off. Teaching a model your vocabulary, conventions and answer style is behaviour, and fine-tuning handles it well. Treating it as a database write for changing facts is where it goes wrong.

6. Where the data lives is a security decision

With RAG, documents stay in a store you control. I'd filter retrieval by the requesting user's permissions from the start, so nobody gets a passage from a document they couldn't open, and a deleted document stops appearing in answers once it leaves the index. Retrieved text is still untrusted input: I'd treat instructions found inside a document as data, never as commands.

Fine-tuning moves data into the weights, and a weight has no per-user permission. I'd assume anything in the training set can resurface for anyone who can call the model, and that removing it means rebuilding the dataset and retraining. For confidential records, that favours permission-aware retrieval.

Retrieval can enforce each user's permissions at request time, but model weights hold no per-user boundary.

7. When the answer is both: stacking retrieval and tuning

OpenAI's accuracy guide describes the techniques as stacking, and says that when early evals show both context and behaviour problems, production will likely end up with fine-tuning plus RAG.

Tuning can sit in two places inside a RAG system. The first is the retriever. When generic embeddings miss your domain vocabulary, such as internal product codes or legal terms of art, you can tune the embedding model or a re-ranker on domain query–document pairs. Someone then owns a labelled set of pairs. A new embedding model means re-indexing the corpus; a re-ranker avoids that but adds a step to every query. Either way, it fixes retrieval, not generation.

The second is the generator: tuning it to use retrieved context faithfully, cite in a fixed format and say "not in the documents" instead of improvising. Try those as grounding instructions and few-shot examples first, and tune only if the eval shows the prompt can't hold them.

Tuning can sit in the retriever, the generator or both, but each one adds a component to version and evaluate again.

8. Three failures, three levers

These are illustrative scenarios, not client projects.

An internal policy assistant whose policies change weekly. Employees get confident answers based on last month's rules: a knowledge gap, with facts that are fresh, private and need citing. If the whole policy set were small enough to send with each request, I'd start there and refresh the text each week. RAG becomes the right call once the corpus outgrows that. Then the lever is permission-aware retrieval over the policy repository, citations in every answer, and a prompt that requires grounded responses and an explicit "I can't find this" when retrieval comes back empty. Fine-tuning would bake in whatever the policy said on training day.

A ticket classifier that ignores the output format. The labels are mostly right, but some responses come back as a sentence or invent a category: a format gap. Start with the tighter prompt shown earlier and the platform's structured-output or schema-constrained decoding where available. Then validate in code with a bounded retry that tells the model what was wrong, so a malformed response never reaches the queue. This TypeScript sketch is illustrative; wire callModel to your own client and test it before relying on it:

classify.ts
// Illustrative sketch: callModel stands in for your model client.
const LABELS = ["billing", "technical", "account", "other"] as const;
type Label = (typeof LABELS)[number];

const MAX_ATTEMPTS = 2;

function parseLabel(raw: string): Label | null {
  const value = raw.trim().toLowerCase();
  return (LABELS as readonly string[]).includes(value) ? (value as Label) : null;
}

export async function classify(
  ticket: string,
  callModel: (input: string, correction?: string) => Promise<string>,
): Promise<Label | "needs_review"> {
  let correction: string | undefined;
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
    const raw = await callModel(ticket, correction);
    const label = parseLabel(raw);
    if (label) return label;
    // Resending the same input may repeat the same mistake, so say what was wrong.
    correction = `Your reply ${JSON.stringify(raw.slice(0, 80))} is not one of: ${LABELS.join(", ")}. Reply with one label only.`;
  }
  return "needs_review"; // an invalid label never reaches the queue
}

If the eval still shows format failures at production volume, fine-tune for format consistency. RAG adds nothing here, because nothing is missing from the model's knowledge.

A high-volume endpoint where cost and latency dominate. Quality is fine with a large model and a long prompt; the bill and the tail latency are not. Trim the prompt, then test a smaller model with the tightened prompt alone, scored against the large model's eval results. If the gap remains and the volume justifies a training pipeline, fine-tune so the prompt can shrink, or distil into the smaller model. Google Cloud's documentation says distillation is most effective when the teacher is substantially more capable than the student on the target task. If your teacher is only marginally better, I'd expect little gain for the pipeline cost.

9. Operational costs over the life of the feature

ApproachFixesDoesn't fixUpfront costOngoing cost
Prompt engineeringUnclear instructions, missing constraints, format and tone via few-shot examplesCorpora too big for one request; behaviour needing many examples; per-request token costAn eval set and iteration timePrompt versioning; tokens on every request; re-testing on model changes
RAGFresh, private and citable knowledgeTone, format consistency, reasoning habitsIngestion, chunking, embeddings, index, access controlRetrieved tokens and retrieval latency on every request; re-indexing, freshness monitoring, permission sync, retrieval evals; full re-embed if the embedding model changes
Fine-tuning (hosted or LoRA)Behaviour, tone, format consistency, shorter prompts, distillationFacts that change; reliable injection of new knowledgeCurated input/output dataset, training runs, eval setDataset upkeep, retraining on requirement or base-model changes; provider dependency (hosted) or serving (open-weight)
RAG plus fine-tuningKnowledge and behaviour failures togetherAnything the eval hasn't diagnosedBoth of the aboveBoth, plus coordinating versions across retriever, index and model

Training data needs an owner. Someone labels and reviews the pairs, redacts personal data before it reaches the weights, keeps eval cases out, and decides what triggers a retrain: a new label, a tone rule or a base-model change.

Model upgrades hit every lever, unevenly. OpenAI states that LLM output is non-deterministic and that behaviour changes between model snapshots and families, so a new base model means re-running your evals. I'd expect a fine-tune to need retraining on the new base and a prompt to need adjustment, while a RAG index can stay if the embedding model does.

Lock-in depends on where the lever lives. A hosted fine-tune is tied to one provider's base model and tuning workflow. Your dataset and eval set are portable by construction; check whether your provider lets you export tuned weights, and if it doesn't, plan to retrain from the dataset when you switch. Keep datasets and evals in your own repository, in formats no single vendor's tooling owns.

10. The eval that settles each branch

OpenAI advises setting up evals before investing in fine-tuning. I'd apply the same rule to RAG: a vector store with no eval is as speculative as a training job with no eval.

Each branch has its own measure:

  • Knowledge: retrieval hit rate on labelled questions, plus groundedness of the answer against the retrieved passage.
  • Behaviour: rubric scoring or pairwise comparison against the prompt baseline.
  • Format: schema-validity rate and label accuracy, measured separately so a valid-but-wrong label doesn't pass.
  • Cost and latency: tokens per request and tail latency, at equal or better quality.

Start with 50 cases: real failing inputs weighted toward the diagnosed type, plus cases that pass today, so you catch regressions. A set this size can separate large gaps between levers, not small ones, so grow it where failures cluster. Because OpenAI notes that LLM output is non-deterministic, I'd pin sampling settings where the API allows and run each case several times; otherwise you're measuring noise and calling it a lever.

Keep eval cases out of any fine-tuning data and few-shot examples, or the tuned model is graded on its own homework. Run every lever on the same cases and compare case by case, to see what each lever fixed and what it broke. If an LLM judge does the scoring, I'd check it against human labels on a sample before trusting it. Version the set next to the code; a plain data shape is enough:

eval_case.py
from dataclasses import dataclass
from typing import Literal

# Illustrative only: version the starter set alongside the code.
FailureType = Literal["knowledge", "behaviour", "format", "cost_latency", "passing"]
Grader = Literal["exact", "schema", "rubric", "pairwise", "grounded"]

@dataclass(frozen=True)
class EvalCase:
    id: str
    input: str                 # real input from logs, sensitive data redacted
    expected: str              # reference answer, label or JSON
    failure_type: FailureType  # from the diagnosis; "passing" marks regression cases
    grader: Grader             # how this case is scored
    runs: int = 3              # repeats per case, to separate lever effects from noise

The decision rule: a lever earns its operational cost only if it beats the best prompt baseline by a margin the team wrote down before seeing results, with no regressions on the passing cases.

11. Before you pick a lever

None of these levers wins in general, and the order assumes real failing cases to test against. Before anyone opens a training job or provisions a vector store, write down which of the four failure types your feature has. Then build the starter eval that will decide it. That eval set will probably outlast whichever lever you pick.

View All Articles

Bishal SahaLet's build together

Have a system to design, or an AI feature to get right?

Tell me about the problem. You'll get a clear, honest view of the best way forward.

  • Reply within 24 hoursOn business days, with my honest view and a next step.
  • Accepting select engagementsArchitecture, AI features and full builds.
  • Remote, worldwideWorking with startups, SMEs and enterprises.