Why most teams pick the wrong one
Most fine-tuning vs RAG vs prompting debates are framed as a capability question: which one makes the model smarter? The decision that actually bites in production is maintenance. Who updates the knowledge, who re-runs the eval set, and what breaks on a Sunday night when a policy changes.
Fine-tuning bakes behaviour into weights and freezes it. RAG keeps knowledge outside the model where anyone can edit it. Prompting keeps everything in version control and readable by a non-engineer. A default order that survives contact with real traffic: prompting first, retrieval second, fine-tuning last — and only for shape, not facts.
Prompting, RAG, and fine-tuning in one sentence each
Prompting changes the instructions and examples you send with every request. Nothing is stored; the model's weights are untouched.
RAG (retrieval-augmented generation) fetches the relevant passages at inference time and pastes them into the prompt, so the answer is grounded in documents you control.
Fine-tuning continues training on your examples so the behaviour lives in the weights, not in the prompt.
Comparison at a glance
| Dimension | Prompting | RAG | Fine-tuning |
|---|---|---|---|
| What you change | Instructions and examples | Context passed at inference time | Model weights |
| Knowledge freshness | As fresh as the prompt | As fresh as your index | Frozen at training time |
| Data you need | A handful of examples | A document corpus | Hundreds to thousands of labelled pairs |
| Setup effort | Minutes | Hours to days (chunking, index, evals) | Days to weeks plus an eval harness |
| Per-call economics | Low, but long prompts add input tokens | Retrieval work plus longer prompts | Shorter prompts, but training and hosting costs |
| Citations | None | Built in if you carry source IDs | None |
| Typical failure | Brittle, unvalidated output | Confidently retrieves the wrong chunk | Confidently wrong facts that look on-brand |
| Best for | Format, behaviour, classification | Product docs, policies, support knowledge | Tone, schema enforcement, distillation |
A five-minute decision framework
Can you write the answer down for five examples? Then it is a prompting problem. If a sharp new hire could do it from instructions plus examples, so can the model.
Does the answer live in documents you already maintain, or do you need citations? That is RAG, not fine-tuning.
Do you need a rigid output shape, a house tone, or a narrow classifier with hundreds of labelled examples and no citations? Consider fine-tuning.
Is the knowledge going to change next quarter? If yes, fine-tuning will silently rot. Use retrieval.
Is prompt length dominating your bill at very high volume? Distillation into a smaller fine-tuned model is the only option that actually shrinks the prompt.
Step 1: prompting with a contract and a validator
The usual prompting failure is not a weak model, it is an unvalidated output contract. Ask for JSON, validate it in code, and give the model exactly one chance to repair itself. That single pattern removes most of the flakiness people blame on the model — and it costs one extra call only when something is actually wrong.
The snippet below uses few-shot examples plus a strict validator, and runs on deepseek-v4-flash, which is the right default for extraction work like this.
import json, os, re
from openai import OpenAI
client = OpenAI(
base_url='https://api.aicreditsapi.com/v1',
api_key=os.environ['AICREDITS_API_KEY'],
)
SYSTEM = '''You convert support tickets into JSON.
Return exactly one JSON object with these keys:
intent - one of: billing, bug, feature_request, account, other
severity - one of: low, medium, high
summary - one sentence, max 20 words
Rules:
- Use only information present in the ticket.
- If the intent is unclear, use 'other'.
- No prose, no markdown fences.'''
FEW_SHOT = [
{'role': 'user', 'content': 'Ticket: I was charged twice this month, please refund.'},
{'role': 'assistant', 'content': json.dumps({
'intent': 'billing', 'severity': 'high',
'summary': 'Duplicate charge this month, refund requested.'})},
]
ALLOWED = {'billing', 'bug', 'feature_request', 'account', 'other'}
def parse(text):
cleaned = re.sub(r'^```(?:json)?|```$', '', text.strip(), flags=re.MULTILINE).strip()
data = json.loads(cleaned)
if data.get('intent') not in ALLOWED:
raise ValueError('intent not in allowed set')
if data.get('severity') not in {'low', 'medium', 'high'}:
raise ValueError('bad severity')
return data
def classify(ticket, attempts=2):
messages = [{'role': 'system', 'content': SYSTEM}, *FEW_SHOT,
{'role': 'user', 'content': f'Ticket: {ticket}'}]
for _ in range(attempts):
resp = client.chat.completions.create(
model='deepseek-v4-flash',
temperature=0,
max_tokens=200,
messages=messages,
)
reply = resp.choices[0].message.content or ''
try:
return parse(reply)
except Exception:
messages.append({'role': 'assistant', 'content': reply})
messages.append({'role': 'user', 'content': 'That failed validation. Return only the JSON object with allowed values.'})
raise RuntimeError('model did not return valid JSON')
print(classify('App crashes every time I upload a CSV larger than 10 MB.'))
Step 2: RAG when the answer lives in documents
Do not start with a vector database. Start with lexical retrieval (BM25) — no embedding service, no index to rebuild, and scores you can actually read when something goes wrong. Move to embeddings only when you observe the real failure mode they fix: your users' words and your documents' words diverge ('cancel' vs 'terminate subscription').
The important part is the grounding contract: cite bracketed sources, and refuse when nothing was retrieved instead of letting the model improvise.
import math, os, re
from collections import Counter
from openai import OpenAI
client = OpenAI(
base_url='https://api.aicreditsapi.com/v1',
api_key=os.environ['AICREDITS_API_KEY'],
)
def tokens(text):
return re.findall(r'[a-z0-9]+', text.lower())
class BM25:
def __init__(self, docs, k1=1.5, b=0.75):
self.docs = docs
self.tf = [Counter(tokens(d)) for d in docs]
self.length = [len(tokens(d)) for d in docs]
self.avg = sum(self.length) / max(len(docs), 1)
self.df = Counter(w for t in self.tf for w in t)
self.n = len(docs)
self.k1, self.b = k1, b
self.idf = {w: math.log(1 + (self.n - c + 0.5) / (c + 0.5))
for w, c in self.df.items()}
def search(self, query, k=3):
scored = []
for i, tf in enumerate(self.tf):
score = 0.0
for w in tokens(query):
if w not in tf:
continue
num = tf[w] * (self.k1 + 1)
den = tf[w] + self.k1 * (1 - self.b + self.b * self.length[i] / self.avg)
score += self.idf.get(w, 0.0) * num / den
scored.append((score, i))
scored.sort(reverse=True)
return [(s, self.docs[i]) for s, i in scored[:k] if s > 0]
DOCS = [
'Refunds are issued to the original payment method within 5-10 business days after approval.',
'API keys are created in the dashboard under Settings > API Keys and can be rotated at any time.',
'Workspace owners can invite members by email from the Members tab.',
]
retriever = BM25(DOCS)
def answer(question):
hits = retriever.search(question, k=3)
if not hits:
return {'answer': 'Not covered by the documentation.', 'sources': []}
context = '\n'.join(f'[{i + 1}] {doc}' for i, (_, doc) in enumerate(hits))
resp = client.chat.completions.create(
model='deepseek-v4-flash',
temperature=0,
messages=[
{'role': 'system', 'content': 'Answer only from CONTEXT. Cite sources as [1], [2]. If CONTEXT is insufficient, say so plainly.'},
{'role': 'user', 'content': f'CONTEXT:\n{context}\n\nQUESTION: {question}'},
],
)
return {'answer': resp.choices[0].message.content, 'sources': [d for _, d in hits]}
print(answer('How long does a refund take?'))
Step 3: fine-tuning — and the cheaper alternative most teams should try first
Fine-tuning teaches form, not facts. It is genuinely good at enforcing an output schema, matching a house tone, teaching domain vocabulary, and shortening prompts. It is poor at knowledge that changes, at citations, and at anything you cannot describe with a few hundred consistent examples. A model tuned on last quarter's policy will state last quarter's policy with total confidence and no way to flag that it is stale.
Before you pay for training, run distillation: log real traffic through deepseek-v4-flash (escalating to deepseek-v4-pro where quality matters), keep only the outputs that pass your validators, and turn the best ones into few-shot examples. Many teams find that ten curated examples plus a validator removes the business case for training. If you still fine-tune — on a provider that offers it — use those same curated traces as training data and keep retrieval attached for the facts.
Step 4: escalate the model instead of inflating the prompt
A bigger prompt is not the same as a stronger model. Keep flash as the default and escalate to deepseek-v4-pro only on a signal: the sentinel for insufficient context, a missing citation line, or a validator failure. Cap it at one escalation so a bad request cannot quietly triple your spend.
import os
from openai import OpenAI
client = OpenAI(
base_url='https://api.aicreditsapi.com/v1',
api_key=os.environ['AICREDITS_API_KEY'],
)
SENTINEL = 'INSUFFICIENT_CONTEXT'
SYSTEM = ('Answer strictly from CONTEXT. Cite the bracketed source numbers you used on a '
'final line formatted as SOURCES: [1],[2]. If CONTEXT does not contain the answer, '
'reply with exactly ' + SENTINEL + ' and nothing else.')
def grounded_answer(question, context):
for model in ('deepseek-v4-flash', 'deepseek-v4-pro'):
resp = client.chat.completions.create(
model=model,
temperature=0,
messages=[
{'role': 'system', 'content': SYSTEM},
{'role': 'user', 'content': f'CONTEXT:\n{context}\n\nQUESTION: {question}'},
],
)
text = (resp.choices[0].message.content or '').strip()
if SENTINEL in text or 'SOURCES:' not in text:
continue
return {'model': model, 'answer': text}
return {'model': None, 'answer': 'Not covered by the documentation.'}
CONTEXT = ('[1] Refunds are issued to the original payment method within 5-10 business days.\n'
'[2] API keys can be rotated in Settings > API Keys.')
print(grounded_answer('How long do refunds take?', CONTEXT))
Cost and latency, qualitatively
Three levers dominate: which model, how many input tokens, and how many round trips. deepseek-v4-flash is the cheap default and deepseek-v4-pro costs more per call, so escalate deliberately rather than by habit. Off-peak usage costs less than peak, and cache hits are cheaper than fresh input — which rewards a stable prompt prefix with the volatile retrieved context placed after it.
RAG adds retrieval work plus extra input tokens; fine-tuning shifts cost into training and hosting while shrinking prompts a lot, and it can pay off at very high volume with a narrow task. Current rates for both models are on aicreditsapi.com/pricing.
Mistakes that cost the most
Fine-tuning to add knowledge you could have retrieved. You lose the ability to correct it without retraining.
Building a vector index before scoring lexical retrieval on twenty real questions. You will often find retrieval was never the bottleneck.
No eval set. Keep 30-50 questions with expected answers and rerun them whenever you touch a prompt, chunker, or model.
Trusting retrieved text. Treat documents as untrusted input, never let them override the system message, and keep the citation contract mandatory.
A giant system prompt that nobody version-controls. Every prompt change is a deploy; treat it like one.
Where AiCredits fits
AiCredits gives international developers access to deepseek-v4-flash and deepseek-v4-pro behind one OpenAI-compatible endpoint, payable by card or PayPal with no Chinese phone number or bank account. That matters for the escalation pattern above: swapping the model name is the only change, so you can start on flash, measure, and escalate selectively without a second vendor integration. There is also a linting tool if you want a second pair of eyes on the eval and prompt code you build around it.
Start with a prompt, a validator, and thirty real questions. Add BM25 the moment answers start depending on documents. Reach for fine-tuning only when you have the traces to prove that shape, not knowledge, is the problem.
FAQ
Yes, and most mature systems do: RAG for facts, few-shot prompting for behaviour and format, and fine-tuning (or distillation) only if prompt length or tone becomes the dominant cost. The layering matters more than any single choice.
Not reliably. It can memorise facts seen often in training, but it cannot cite them, cannot be updated without retraining, and gives no signal when it is out of date. For anything that changes, retrieval wins.
No. BM25 over a few hundred documents in memory is fast, dependency-free, and debuggable. Add embeddings when you can show that queries and documents use different vocabulary and lexical search misses.
When your eval set shows failures that are about missing facts rather than wrong formatting, or when the prompt has grown to the point where every request pays for context that is usually irrelevant. Those are retrieval signals.
deepseek-v4-flash for everything, with a validator and one repair attempt. Escalate to deepseek-v4-pro only on a specific failure signal, and log which requests escalated so you can see what it is actually buying you.