0Pricing
AI Engineering Academy · 课时

RAG 与微调:何时选择哪一种

从知识新鲜度、成本、延迟和实现复杂度等方面比较 RAG 与微调,为不同的真实场景决定合适的方法。

RAG 与微调:何时选择哪一种 是 CoddyKit 上的免费 AI Engineering Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 AI Engineering Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 AI Engineering Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Two Strategies, Different Goals

When you need an LLM to work well on your specific domain, you have two main strategies: Retrieval-Augmented Generation (RAG) dynamically injects relevant knowledge at inference time, while fine-tuning updates the model's weights to bake in knowledge, style, or format preferences. Choosing between them correctly can mean the difference between a reliable system and months of expensive GPU compute wasted on the wrong approach.

What Fine-Tuning Actually Changes

Fine-tuning updates the model's weights by training on example input-output pairs. It excels at changing behavior: teaching a model to always respond in a specific JSON format, adopt a brand voice, follow domain-specific reasoning patterns, or perform a task type it was not optimized for. Fine-tuning does not reliably update factual knowledge — models can overfit on training examples without generalizing the underlying facts to new queries.

# Fine-tuning training example format (JSONL)
# {"messages": [
#   {"role": "system", "content": "You extract order info as JSON."},
#   {"role": "user",   "content": "Order #1234 for 3 widgets at $9.99 each"},
#   {"role": "assistant", "content": '{"order_id": "1234", "qty": 3, "unit_price": 9.99}'}
# ]}

# Good fine-tuning use case: consistent output FORMAT
# Bad fine-tuning use case: teaching the model your 2025 product catalog facts

What RAG Actually Changes

RAG does not modify model weights. Instead, it changes the information available to the model at inference time by placing relevant documents in the context window. RAG excels at knowledge: answering questions about private documents, keeping answers current with frequently updated data, and grounding responses in verifiable sources. What RAG does not easily change is the model's inherent style, format preferences, or reasoning approach.

Knowledge Freshness: RAG Wins

For any use case where information changes over time, RAG is clearly superior. Re-indexing a vector store when documents update takes minutes and requires no GPU resources. Fine-tuning a model on new data requires retraining (expensive and slow), and even then the model may not reliably recall the new facts. Product catalogs, legal regulations, medical guidelines, and company policies are all better served by RAG than fine-tuning.

Style and Format Consistency: Fine-Tuning Wins

If you need the model to always respond in a very specific style, tone, or structured format that prompt engineering alone cannot reliably enforce, fine-tuning is the right tool. Examples: a customer service bot that must always use your brand's specific vocabulary, a code generator that must produce code matching your company's internal style guide, or a classification model that must output a rigid taxonomy reliably across thousands of edge cases.

Cost Comparison

Fine-tuning has high upfront cost (compute for training, dataset preparation time, evaluation) but reduces per-query cost if fine-tuning enables you to use a smaller model. RAG has low upfront cost (vector database indexing is cheap) but adds per-query overhead: an embedding API call plus slightly longer prompts with injected context. For most applications under 10M daily queries, RAG's per-query overhead is negligible compared to fine-tuning's development cost.

# RAG per-query cost estimate
EMBED_COST_PER_1K_TOKENS = 0.00002  # text-embedding-3-small
LLM_INPUT_COST_PER_1K = 0.0025     # gpt-4o input

query_embed_cost = (10 / 1000) * EMBED_COST_PER_1K_TOKENS    # ~10 token query
context_cost = (1500 / 1000) * LLM_INPUT_COST_PER_1K         # 5 chunks * 300 tokens

print(f'RAG overhead per query: ${query_embed_cost + context_cost:.5f}')
# About $0.004 extra per query — negligible at moderate scale

Latency Comparison

Fine-tuned models can be faster at inference because shorter prompts are needed — the knowledge is in the weights, not the context. RAG adds two round-trips: an embedding API call and a vector search query. Total overhead is typically 50-200ms. For latency-sensitive applications like real-time voice assistants, this overhead matters. For most chat and Q&A applications, the additional latency is imperceptible to users.

Transparency and Auditability

RAG provides a clear audit trail: for every answer, you know exactly which documents were retrieved and can show them to the user. Fine-tuned models answer from opaque weights — there is no record of which training example produced a given output. In regulated industries like finance, healthcare, and law, where answers must be explainable and verifiable, RAG's transparency is a significant advantage over fine-tuning.

When to Combine Both

RAG and fine-tuning are not mutually exclusive. A common production pattern is: fine-tune a model for consistent output format and domain vocabulary, then add RAG on top to supply current factual knowledge. The fine-tuned model handles the style and structure reliably, while RAG handles the knowledge. This combination outperforms either approach alone for high-stakes enterprise applications.

Decision Flowchart

Follow this decision path: Is the problem about style or format consistency? → Consider fine-tuning. Is the information private or frequently updated? → Use RAG. Do you need source citations? → Use RAG. Is the dataset too small for fine-tuning (under 500 examples)? → Use RAG with few-shot prompting. Do you need the model to handle a task it currently refuses to do? → Fine-tune with RLHF or DPO. When uncertain, start with RAG — it is faster to build, easier to update, and more transparent.

Real-World Scenario Examples

Use these scenarios to build intuition: Internal HR chatbot (policies change quarterly, must cite sources) → RAG. Code completion for a proprietary framework (consistent code style, framework patterns) → Fine-tuning. Legal document Q&A (private documents, precise citation needed) → RAG. Customer support bot (specific tone, product FAQ changes weekly) → Fine-tuning for tone + RAG for knowledge. Medical literature summarizer (current research, attribution critical) → RAG.

Quick Check

Test your understanding of AI Engineering concepts from this lesson.

Lesson Recap

In this lesson you learned: fine-tuning changes model behavior and style but not reliably factual knowledge, RAG dynamically supplies knowledge at inference time with full transparency and source citation, and the decision framework for choosing — use RAG for frequently updated private knowledge requiring attribution, use fine-tuning for consistent style and format, and combine both for high-stakes enterprise applications. Next up we start building a complete RAG pipeline from scratch.

常见问题解答

「RAG 与微调:何时选择哪一种」课时是免费的吗?

是的 — 「RAG 与微调:何时选择哪一种」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 AI Engineering Academy 课程的其余内容,请升级到 CoddyKit PRO。 AI Engineering Academy 课程共包含 4 节课。

「RAG 与微调:何时选择哪一种」这节课中我会学到什么?

从知识新鲜度、成本、延迟和实现复杂度等方面比较 RAG 与微调,为不同的真实场景决定合适的方法。 你通过在浏览器中直接运行的动手代码来练习 AI Engineering Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 AI Engineering Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 AI Engineering Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「RAG 与微调:何时选择哪一种」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 AI Engineering Academy 课中编写并运行代码吗?

能。每节 AI Engineering Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. RAG 解决的问题
  2. RAG 架构:索引与检索
  3. 编写增强提示
  4. RAG 与微调:何时选择哪一种
← 返回 AI Engineering Academy