Sub topic 1
Three levers for adapting a model
A general-purpose large language model (LLM) rarely fits a specific task out of the box. You can change its output in three main ways: change the input (prompting), change the information it sees at query time (retrieval-augmented generation, or RAG), or change the model's weights (fine-tuning). This chapter introduces the three levers, shows what each one touches, and explains why the rest of the tutorial treats them as a sequence of choices instead of a menu.
Prerequisites
This chapter assumes you have:
- Basic experience calling an LLM through a chat-style API, including the idea of system, user, and assistant messages.
- Python familiarity at a reading level. You do not need to write much code, but you should follow short functions.
- Awareness of what embeddings are (vectors that represent the meaning of text) and what a context window is (the maximum amount of text the model can read in one request).
You do not need prior experience training models.
The core idea: three places to intervene
A model call has three parts you can influence:
- The instructions and examples you put in the prompt.
- The knowledge the model can see when it answers.
- The weights, the learned numbers inside the model.
Each lever maps to one of these.
| Lever | What changes | When the change takes effect | Model weights touched? |
|---|---|---|---|
| Prompting | Instructions, examples, output format | Every request | No |
| RAG | Retrieved passages added to the prompt | Every request | No |
| Fine-tuning | The model itself | After a training run | Yes |
Prompting and RAG both work by changing the text the model receives. That is why they are fast to try and easy to undo. Fine-tuning produces a new version of the model, which you then have to host, version, and evaluate.
Lever 1: prompting
Prompting means writing better instructions, adding examples, and specifying the output format. It costs nothing beyond the tokens you send, and you can change it in seconds.
Here is a few-shot prompt for classifying support tickets. The examples sit in the message list as earlier turns of the conversation, so the model sees the pattern you want it to follow.
def build_messages(question, examples):
messages = [{
"role": "system",
"content": "Classify the support ticket as billing, bug, or other. Reply with one word.",
}]
for text, label in examples:
messages.append({"role": "user", "content": text})
messages.append({"role": "assistant", "content": label})
messages.append({"role": "user", "content": question})
return messages
examples = [
("I was charged twice this month.", "billing"),
("The export button crashes the app.", "bug"),
]
messages = build_messages("My invoice shows the wrong amount.", examples)Nothing about the model changed. You only changed what it reads. This is the lowest-cost way to steer behavior without changing the model or adding data.
Prompting has limits. It cannot give the model facts it does not have, and long prompts use context window space and add cost and latency on every call.
Lever 2: retrieval-augmented generation
RAG adds knowledge at query time. Your system searches a collection of documents, picks the passages most relevant to the question, and places them in the prompt. The model then answers from that material.
The core of the retrieval step is ranking stored text chunks by similarity to the query. Both the query and the chunks are converted to embedding vectors, and cosine similarity measures how closely two vectors point in the same direction.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b)
def top_k(query_vec, chunks, k=3):
# chunks is a list of (text, vector) pairs
ranked = sorted(chunks, key=lambda c: cosine(query_vec, c[1]), reverse=True)
return [text for text, _ in ranked[:k]]
def grounded_prompt(question, passages):
context = "\n\n".join(passages)
return (
"Answer using only the context below. "
"If the answer is not in the context, say you don't know.\n\n"
"Context:\n" + context + "\n\nQuestion: " + question
)The instruction "If the answer is not in the context, say you don't know" matters. Without it, the model may fill gaps from its training data and produce a confident but unsupported answer.
RAG fits cases where facts are private (internal policies, customer records), fresh (prices, inventory, recent events), or too large to fit in a prompt. Updating knowledge means updating the document store, not retraining anything. The cost is a retrieval system you now have to build and maintain, plus extra latency on each request.
Lever 3: fine-tuning
Fine-tuning continues training a model on your own examples so that its weights shift toward the behavior you want. The training data is a set of example inputs paired with the exact outputs you want. For chat models, it is commonly stored as JSONL (one JSON object per line). One line looks like this:
{"messages": [{"role": "system", "content": "You write release notes in our house style."}, {"role": "user", "content": "Fixed crash when exporting empty reports."}, {"role": "assistant", "content": "Fix: exporting an empty report no longer crashes the app."}]}Fine-tuning is best at changing how the model responds: a consistent tone, a strict output format, a specialized task pattern, or shorter prompts because the instructions are now learned. It is a poor way to add facts that change often. Facts baked into weights are hard to update, hard to verify, and may be recalled unreliably.
The cost is higher up front. You need curated training data, a training run, an evaluation of the result, and a plan to repeat the process when the base model or your requirements change.
Two kinds of gap
The levers line up with two kinds of failure, which the next chapter develops in detail.
- A knowledge gap means the model does not have the information needed. It might answer "What is our refund window?" wrongly because it never saw your policy. RAG addresses this.
- A behavior gap means the model has the information but responds in the wrong way: wrong format, wrong tone, ignored constraints. Prompting addresses it first, and fine-tuning addresses it when prompting is not enough.
Mixing these up is the most common mistake in this area. Teams fine-tune to teach facts, then find the model still gets them wrong. Others stuff long style guides into every prompt when a short fine-tune would be cheaper and more consistent.
Why order matters
The levers differ in cost, speed of iteration, and reversibility.
| Property | Prompting | RAG | Fine-tuning |
|---|---|---|---|
| Time to first result | Minutes | Hours to days | Days to weeks |
| Setup effort | Low | Medium (index, retrieval, chunking) | High (data, training, hosting) |
| Updating knowledge | Edit the prompt | Update the document store | Retrain |
| Per-request overhead | Longer prompts | Retrieval step plus longer prompts | Often shorter prompts |
| Easy to roll back | Yes | Yes | Requires keeping old model versions |
The usual order follows this table: try prompting, add RAG if the failure is missing knowledge, and add fine-tuning if the failure is behavior that prompts cannot fix. A simplified version of that rule looks like this:
def suggest_approach(needs_private_or_fresh_facts, needs_consistent_style_or_format, prompt_baseline_passes):
if prompt_baseline_passes:
return ["prompting"]
approaches = ["prompting"]
if needs_private_or_fresh_facts:
approaches.append("rag")
if needs_consistent_style_or_format:
approaches.append("fine-tuning")
return approachesNotice the first line. If a prompt-only baseline already passes your evaluation, you stop. The function takes prompt_baseline_passes as an input, which means you need a way to measure that. Later chapters cover how to build an evaluation set and baseline before you change anything.
Edge cases to keep in mind
- Prompting can fail for capacity reasons. If the instructions and examples needed are too long for the context window, or too costly per call, that pushes you toward fine-tuning even if prompting would technically work.
- RAG can fail at retrieval, not generation. If the right passage is never retrieved, the model cannot use it. A wrong answer may be a search problem.
- Fine-tuning can change more than you intended. Training on narrow data can degrade behavior on other tasks, so you need to evaluate outside your target task too.
- Some problems are neither. If the model lacks the reasoning ability the task needs, none of the three levers fully fixes it, and a more capable base model may be the right change.
Where this tutorial goes next
The remaining chapters follow the order of work: diagnose the gap, build an evaluation set, try prompting, add RAG or fine-tuning as needed, compare costs, and combine approaches with a repeatable decision framework.
Exercise
Your support assistant answers questions about a return policy that changed last week, and it keeps quoting the old policy. Which lever addresses this most directly, and why is fine-tuning a poor first choice?
Show answer
RAG. The failure is a knowledge gap about fresh, private information, so you should retrieve the current policy at query time and place it in the prompt. Fine-tuning would bake the policy into the weights, which makes it hard to update when the policy changes again and does not reliably prevent the model from recalling the old one.
Exercise
A model has all the information it needs in the prompt but keeps returning a long paragraph when you need exactly one of three labels. Is this a knowledge gap or a behavior gap, and what do you try first?
Show answer
It is a behavior gap. Try prompting first: tighten the instruction (for example, "Reply with one word"), add few-shot examples that show the exact format, and measure the result against an evaluation set. Consider fine-tuning only if prompting cannot reach the required consistency.
Exercise
Why does the suggest_approach function return early when prompt_baseline_passes is true?
Show answer
Prompting is the cheapest and most reversible lever. If it already meets your evaluation criteria, adding retrieval or training would add cost and maintenance without improving results.