Howwise RSS
AI & Automation6 min read

RAG vs Fine-Tuning: Which to Use and Why Costs Spike

Short answer

RAG vs fine-tuning comes down to facts versus behavior: RAG supplies facts at query time from your documents, while fine-tuning changes style, format and task skill. For document Q&A, use RAG, and fix the settings that inflate cost.

Key takeaways
  • Fine-tuning teaches behavior (tone, format, task skill); it is unreliable for injecting new facts and can increase confident hallucination.
  • A normal RAG question sends only the top-k chunks, often 2k to 4k input tokens, so cost per query stays flat as the corpus grows.
  • A surprisingly large bill usually comes from whole-document modes such as SummaryIndex, tree_summarize or refine, which read every chunk by design.
  • Cut cost by lowering similarity_top_k, using response_mode='compact', picking a small model, caching summaries and counting tokens before judging.
  • Combine both when needed: fine-tune for tone or JSON format, and use retrieval for the facts.

What is the difference between RAG and fine-tuning?

Fine-tuning continues training a model on example prompt/completion pairs so it behaves differently: a consistent tone, a strict JSON schema, a classification label, a task it was weak at. It adjusts weights, which is a blunt way to store information.

Retrieval-augmented generation (RAG) leaves the model alone. Your documents are split into chunks, embedded once, and stored in a vector index. At query time the system finds the few most relevant chunks and pastes them into the prompt, and the model answers from that text.

A useful rule: fine-tuning teaches the model how to answer, retrieval tells it what to answer from. If the question is "what does our refund policy say?", that is a retrieval problem.

Does fine-tuning add new knowledge to an LLM?

Not reliably. Training on a few hundred or thousand passages nudges probabilities, so the model may reproduce phrasing it saw but blend it with its prior knowledge. The result is fluent answers that are sometimes wrong, with no way to tell which.

Fine-tuning on raw documents is also the wrong data shape. Providers expect supervised examples (for chat models, JSONL with messages ending in an assistant reply), usually hundreds or more of good ones. Raw text does not teach the model to answer questions about it.

So "can you fine-tune GPT to learn your own documents?" Technically you can train on them, but the model will not behave like a searchable knowledge base. Other practical limits:

NeedFine-tuningRAG
Data changes weeklyRetrain every timeRe-embed changed chunks only
Source citationsNot possibleReturn chunk metadata with answer
Per-user permissionsNone, the weights are sharedFilter by metadata at retrieval
Delete one factHard, needs retrainingDelete the chunk from the index
Inference priceFine-tuned models usually cost more per tokenBase model price

Why was my LlamaIndex query so expensive?

Most likely you ran a whole-document operation, not a question-answering one. Two query types behave very differently:

A needle query ("what is the notice period in section 4?") retrieves 3 to 5 chunks and sends them once. A summarization query ("summarize this PDF") needs every chunk, so SummaryIndex, tree_summarize and refine modes deliberately read the entire document.

A 50-page PDF is roughly 25k to 40k tokens. Refine mode makes one sequential LLM call per chunk, re-sending the running answer each time, so the input tokens add up beyond the document size. At $10 per million input tokens, that comes to about $0.50 to $0.80 per run; at original GPT-4 pricing of roughly $30 per million, it is more than $1.50. The table below shows the full comparison.

Warning: Many tutorials default to the most expensive model. Setting a model explicitly and counting tokens first prevents a repeat bill. Also set a spending limit in your provider dashboard.

How much does each approach cost? A worked example

Cost = tokens / 1,000,000 x price per million tokens. The prices below are illustrative round numbers; substitute your model's current rates.

Assume a 35k-token document, a small model at $0.15 per million input tokens and a premium model at $10 per million input tokens.

ApproachInput tokensSmall modelPremium model
RAG, top-k=4, 800-token chunksabout 3,500about $0.0005about $0.035
Full document stuffed in promptabout 35,000about $0.005about $0.35
Refine over all chunks (many calls, growing context)about 50,000 to 80,000about $0.01about $0.50 to $0.80
Embedding the document once (text-embedding-3-small, about $0.02 per million)35,000 one timeabout $0.0007same
Tip: Output tokens cost more than input tokens, so cap answer length. Fine-tuning adds a training bill (priced per training token, times epochs) and then a higher per-token inference price.

How do I reduce LlamaIndex query cost?

Pick the cheap path for the question type, then trim the settings. For needle questions, use a vector index with a small top-k and compact responses:

  1. Use a small model for generation, such as gpt-4o-mini, and a cheap embedding model.
  2. Lower similarity_top_k to 3 or 4 and use chunk_size around 512 to 1024.
  3. Set response_mode='compact', which packs retrieved chunks into as few LLM calls as possible instead of one call per chunk.
  4. Summarize once at ingestion, store the summary (or a per-document summary index), and reuse it instead of re-summarizing.
  5. Use provider prompt caching when you repeat a large static prefix, and use a long-context model only when retrieval fails.
  6. Attach a token counting callback and read the totals before drawing conclusions.
import tiktoken
from llama_index.core import Settings, VectorStoreIndex, SimpleDirectoryReader
from llama_index.core.callbacks import CallbackManager, TokenCountingHandler
from llama_index.llms.openai import OpenAI

counter = TokenCountingHandler(
    tokenizer=tiktoken.encoding_for_model("gpt-4o-mini").encode)
Settings.callback_manager = CallbackManager([counter])
Settings.llm = OpenAI(model="gpt-4o-mini", max_tokens=400)
Settings.chunk_size = 800

docs = SimpleDirectoryReader("data").load_data()
index = VectorStoreIndex.from_documents(docs)
qe = index.as_query_engine(similarity_top_k=4,
                           response_mode="compact")
print(qe.query("What is the notice period?"))
print(counter.prompt_llm_token_count,
      counter.completion_llm_token_count,
      counter.total_embedding_token_count)

When should I use fine-tuning, RAG, or both?

Fine-tuning wins when the problem is behavior: a consistent brand tone, strict output such as a JSON schema, classification or extraction at scale, distilling a large model into a small cheap one, or removing long repeated instructions from every prompt to shorten it.

RAG wins when the problem is knowledge. It scales to millions of records in pgvector, Pinecone, Chroma or Qdrant, because vector search narrows the corpus first. You never send millions of records per query, so cost per query stays roughly constant as the corpus grows; only storage and one-time embedding grow.

Both together is common: fine-tune for tone and format, retrieve for facts. Use this checklist:

QuestionLean toward
Knowledge changes often?RAG
Need citations or source links?RAG
Need per-user access control?RAG with metadata filters
Need fixed tone or output schema?Fine-tuning (or structured output first)
Hundreds of quality example pairs available?Fine-tuning is feasible
Corpus under roughly 100k tokens, rarely queried?Long context plus prompt caching
Latency and budget tight at high volume?Small model, possibly fine-tuned, plus RAG

What are the common RAG mistakes to avoid?

Expecting RAG to answer global questions. "Summarize everything" or "how many contracts mention X?" cannot be answered from 4 chunks. Use a pre-built summary index, structured extraction into a database, or a map-reduce pass at ingestion.

Poor chunking and missing metadata. Splitting mid-table or mid-sentence hurts retrieval, and without metadata (source, page, date, owner) you lose citations and filtering.

Weak retrieval. Combine BM25 keyword search with vectors (hybrid search) and add a reranker to reorder the top 20 candidates down to the best 4.

Fine-tuning on raw documents, and judging cost without measuring tokens. Count first, then optimize.

Common questions

Is fine-tuning cheaper than RAG?

Usually not for knowledge tasks. You pay for training, then a higher per-token price on every call, and you retrain when data changes. It can be cheaper when it lets a small model replace a large one or shortens long prompts at high volume.

Why use LlamaIndex instead of fine-tuning?

LlamaIndex handles loading, chunking, embedding, indexing and retrieval so answers are grounded in your current documents. Updating a file means re-indexing it, not retraining a model. You also get source nodes for citations.

Can a long-context model replace RAG?

For a small corpus such as one 50-page document, often yes, especially with prompt caching on the repeated document prefix. It stops being practical as the corpus grows past the context window or when you need citations and permissions.

Does RAG eliminate hallucinations?

No, it reduces them by grounding answers in retrieved text. If retrieval misses the right chunk, the model may still guess, so instruct it to say when the context lacks the answer and evaluate on real questions.

How many chunks should I retrieve?

Start with a top-k of 3 to 5 chunks of 500 to 1000 tokens. Raise it only if answers miss information that exists in the corpus, and consider reranking before simply increasing k.

Related topics:ragfine-tuningllamaindexllm-cost