Learning objectives
After reading this article you will be able to:
- Understand what RAG and fine-tuning each change in the model
- Compare updates, cost, latency, maintenance and source citation
- Decide when to combine both and when a prompt is enough
You have an LLM that answers general questions well but gets things wrong when the topic is your product, your refund policy or the way your team writes. The two answers every search turns up are RAG and fine-tuning. They are often pitched as rivals, but they solve different problems.
One question organizes the choice: is the model missing information or behavior? Information (facts, documents, prices) is best solved by handing over the data at question time. Behavior (a format, a tone, a repetitive task) is best solved with examples. And before either one, it is worth trying a better prompt.
What does each technique change in the model?#
RAG (retrieval-augmented generation) changes the context, not the model. On every question, your code searches your data for the most relevant passages, usually by embedding similarity, and puts them in the prompt. The weights stay the same, and the search decides what the model knows at that moment. The step-by-step is in what is RAG.
Fine-tuning changes the weights. You train an existing model on input and output examples, and the result is a new model that answers that way without long instructions. The most common method is supervised fine-tuning: each example is a conversation with the ideal answer. In the messages format, accepted by tools such as the SFTTrainer in Hugging Face's TRL library, the training file holds one conversation per line:
{"messages": [{"role": "system", "content": "Classify the ticket as: billing, technical or other."}, {"role": "user", "content": "My card was charged twice."}, {"role": "assistant", "content": "billing"}]}
{"messages": [{"role": "system", "content": "Classify the ticket as: billing, technical or other."}, {"role": "user", "content": "The bot won't start after the deploy."}, {"role": "assistant", "content": "technical"}]}Notice what the file teaches: an output format and a decision rule, not a manual.
Training every weight of a large model is expensive, so parameter-efficient fine-tuning is common: it updates only a small part of the model. The best-known technique, LoRA, freezes the original weights and trains small matrices added to each layer. In the paper that introduced it, compared with fully fine-tuning a 175-billion-parameter model, LoRA cut the trainable parameters by 10,000 times and GPU memory by 3 times, with no added inference latency.
What are the differences, side by side?#
| Criterion | RAG | Fine-tuning |
|---|---|---|
| What changes | The prompt of each question | The model's weights |
| Data that changes | Re-index only the changed documents, effective immediately | Needs a new training run for every relevant change |
| Upfront cost | Low: embeddings and an index | Building the examples, training and evaluating |
| Cost per answer | Higher: the passages enlarge the input | Shorter prompt, but the tuned model may be priced differently |
| Latency | Adds the search and a longer prompt | The model's own, no extra step |
| Maintenance | Search quality, chunks and the index | Training set, evals and retraining when the base model changes |
| Source citation | Yes, every passage has a known origin | No, the model doesn't know where it learned |
| Access control | Filter what each user can retrieve | What went into the weights applies to everyone |
| Best for | Facts, documents, changing data | Format, tone, classification, extraction |
Access control matters more than it looks: with RAG, a support agent and a customer can query different indexes, but what went into the weights cannot be taken out for a single user. The cost per answer of RAG grows with the number of passages you send, and the full math is in how much a RAG system costs.
Why is fine-tuning bad at teaching facts?#
It sounds intuitive: if the model doesn't know your product, train it on the documentation. In practice it works poorly, and there are studies that measure it.
A 2023 study, Fine-Tuning or Retrieval?, compared both ways of injecting knowledge and found that RAG consistently outperforms unsupervised fine-tuning, both for facts the model had already seen and for entirely new ones. A 2024 study, Does Fine-Tuning LLMs on New Knowledge Encourage Hallucinations?, showed that models learn examples with new facts much more slowly than examples consistent with what they already know and that, once learned, those examples increase the tendency to hallucinate. The authors' reading: models acquire most of their knowledge in pre-training, and fine-tuning teaches them to use it.
There are two practical problems on top of that. Facts change: today's price becomes tomorrow's error, and every fix needs a new training run. And a fine-tuned model doesn't cite sources: it answers with the same confidence when it is right and when it makes things up. See why that happens in chatbot hallucinations.
When is fine-tuning worth it?#
When the problem is behavior and the prompt doesn't fix it. Google's tuning documentation recommends supervised fine-tuning for tasks with well-defined output: classification, sentiment analysis, entity extraction, strict output formatting and a domain's style or tone. Other signs:
- You repeat the same long instructions on every call, and they still fail on part of the cases.
- You have hundreds of good examples, more than would fit in a prompt.
- The task is narrow and high-volume, and cutting the instructions from every call pays for the training.
Fine-tuning has a dependency few people consider: the tuned model lives as long as its base model does, and tuning offers change. Not every provider offers fine-tuning for every model, so check the provider's page before you plan. Keep the training set and the evals next to your code, because you will need to train again.
Where to do it: cloud providers offer tuning for their own models, and open-weight models can be fine-tuned with libraries such as Hugging Face's TRL and PEFT, on a GPU you own or rent. Running the resulting model also takes hardware, as local LLM vs an API shows.
When should you combine both?#
When you need consistent behavior and current facts. A support bot that always answers in JSON with category, answer and sources is a good example: fine-tuning locks in the format and tone, and RAG supplies the refund policy in force on every question.
There is also fine-tuning done for RAG. The RAFT method trains the model on questions paired with useful documents and with documents that only distract, so it learns to ignore the irrelevant ones and to cite the right passage. In the authors' tests, this improved performance on datasets such as medical papers (PubMed) and API documentation.
The sensible order is to start with RAG (how to build a RAG chatbot), measure where it fails and only then fine-tune. If the right passage never reached the prompt, the error is in the search, and fine-tuning won't fix it.
When do you need neither?#
More often than you'd think. OpenAI and Google both recommend starting with the prompt, and OpenAI's documentation says prompt engineering may be all you need. Before indexing or training, try this order:
- Clear instructions. State the role, the audience, the output format and what to do when the answer isn't in the context.
- Examples in the prompt. Three to five ideal question and answer pairs (few-shot) show the format with no training at all, and you can change them in a minute.
- The whole document in the prompt. If the knowledge base fits in the context window, send all of it: no chunks, no index, no risk of the search missing. What to do when the window overflows is in context_length_exceeded.
- Prompt caching. When the fixed part repeats on every call, some providers charge less for it. At OpenAI, caching is on by default for supported models, and the advice is to put stable content first and variable content last. Other ways to cut tokens are in how to reduce LLM token costs.
RAG comes in when the content doesn't fit, changes too often or needs access control. Fine-tuning comes in when the behavior is still wrong even with good examples.
How to do this on Square Cloud#
Square Cloud's AI Gateway doesn't do fine-tuning or generate embeddings, so the path through it follows the order in this article: prompt first, RAG next. From the Standard plan (R$44.99 a month), it is an OpenAI-compatible API for using the cubic model in your own products: you point the OpenAI SDK at https://api.squarecloud.app/v2/ai and use an account API key with the ai:chat scope. Hobby does not include the gateway.
The context goes up to 64k tokens on Standard, 128k on Pro and 256k on Enterprise, so many documents fit whole in the prompt before RAG becomes necessary. The gateway also has built-in web search (the model decides when to search and cites the URLs), useful when the knowledge is public. It keeps no state: send the history with every request.
When you do need RAG, embeddings come from another provider, and the index can live in PostgreSQL hosting (also from Standard), which comes with the pgvector extension, next to your documents. The application that ties it together runs in an isolated, always-on container. See the limits and examples on AI Gateway.
AI
Host AI apps in always-on containers
FAQs
Does fine-tuning teach the model new facts?
Poorly. Studies show models learn new facts slowly through fine-tuning and that doing so can increase hallucinations. For knowledge that changes or that only you have, RAG usually works better.
Is RAG cheaper than fine-tuning?
To get started, almost always: there is no training, and updating the knowledge base means re-indexing the documents that changed. In exchange, every question sends more tokens to the model, so the cost per answer goes up.
Can I use RAG and fine-tuning together?
Yes. Fine-tuning locks in the format and behavior, and RAG supplies current facts on every question. Some methods even train the model to make better use of the retrieved passages.
How many examples do I need to fine-tune a model?
It depends on the tool and the task. Google Cloud's tuning documentation suggests starting with around 100 examples and talks about hundreds to thousands of labeled examples for supervised tuning. The quality and consistency of the examples matter more than the count.
More in AI
See all 31 articles- How much does an AI chatbot cost to build and run?Running an AI chatbot costs model tokens, hosting, a database and, with RAG, extra context per message. See how to estimate the cost per conversation.
- How much does a RAG system cost? Embeddings, database and LLMA RAG system has three costs: embeddings, a vector database and the LLM. See the math for 1,000 questions a day, with hypothetical prices, and where the bill grows.
- Local LLM (Ollama) vs an API: cost, hardware and privacyRunning a local LLM with Ollama trades per-token cost for hardware and upkeep; an API gives you bigger models with no server. Compare RAM, cost and privacy.
- 429 errors from an AI API: rate limits, quota and how to handle themA 429 from OpenAI, Claude or Gemini means a rate limit or exhausted quota. Learn to tell them apart, read the limit headers and retry with backoff.