Skip to content

Split View: RAG vs Fine-tuning vs Prompt Engineering: 언제 무엇을 선택하는가

|

RAG vs Fine-tuning vs Prompt Engineering: 언제 무엇을 선택하는가

AI 제품팀이 항상 하는 질문

"우리 서비스에 AI를 붙이려는데 어떤 방법을 써야 하나요?"

이 질문을 몇 백 번은 들은 것 같다. 스타트업 CTO, 대기업 개발팀장, 사이드 프로젝트 하는 개발자까지 — 모두 같은 고민을 한다. 그리고 대부분은 "일단 fine-tuning 해보자"거나 "RAG 구축하자"는 방향으로 성급하게 달려간다.

결론부터 말하면: 대부분의 경우 Prompt Engineering으로 시작하고, 필요할 때 RAG 추가하면 된다. Fine-tuning은 생각보다 훨씬 드물게 필요하다.

이 글에서는 세 가지 접근법의 특성을 솔직하게 비교하고, 실제 판단 기준을 제시한다.

세 가지 접근법이란?

먼저 개념을 정리하자.

Prompt Engineering은 LLM에게 전달하는 입력 자체를 최적화하는 방법이다. System prompt 작성, few-shot 예시 추가, Chain-of-Thought 유도 등이 여기에 해당한다. 모델 자체는 건드리지 않는다.

**RAG (Retrieval-Augmented Generation)**는 외부 지식 베이스에서 관련 문서를 검색해서 LLM에게 컨텍스트로 전달하는 방법이다. 모델이 모르는 정보를 "실시간으로 찾아서" 제공하는 방식이다.

Fine-tuning은 사전 학습된 LLM을 특정 도메인 데이터로 추가 학습시키는 방법이다. 모델의 가중치 자체를 변경한다.

3가지 접근법 특성 비교

특성Prompt EngineeringRAGFine-tuning
초기 비용최저중간높음
구축 속도즉시 (몇 시간)빠름 (며칠)느림 (수 주)
지식 업데이트즉시즉시재학습 필요
전문 지식 습득약함중간강함
필요 데이터없음문서 모음labeled 데이터셋
환각(hallucination) 위험높음낮음중간
운영 복잡도낮음중간높음
스타일/형식 제어중간중간강함

이 표에서 가장 중요한 컬럼은 **"지식 업데이트"**와 **"환각 위험"**이다. RAG가 fine-tuning보다 환각 위험이 낮은 이유는, 모델이 "생성"하는 게 아니라 retrieved 문서에서 "인용"하도록 유도할 수 있기 때문이다.

의사결정 프레임워크

Q1: 최신 정보 또는 사내 비공개 문서가 필요한가?
    YESRAG 고려
    NO  → 다음 질문으로

Q2: 특정 스타일, 형식, 도메인 전용 언어가 필요한가?
    YESFine-tuning 고려
    NOPrompt Engineering으로 시작

Q3: RAG를 시도했는데 retrieval 품질이 계속 나쁜가?
         (도메인 특화 용어를 모델이 이해 못 하는 경우 등)
    YESRAG + Fine-tuning 조합
    NORAG만으로 충분

Q4: Prompt Engineering인데 일관성이 부족한가?
    YESFew-shot 예시 추가 또는 Fine-tuning 검토
    NO  → 현재 접근으로 계속

실전 적용 팁

Q1에서 "사내 문서"라고 하면 FAQ, 제품 매뉴얼, Confluence, Notion, Slack 아카이브 등 모든 내부 문서를 포함한다. 이런 정보는 LLM이 학습 데이터에 갖고 있지 않으니 반드시 RAG가 필요하다.

Q2의 "도메인 전용 언어"는 의료 기록의 약어 체계, 법률 문서의 특정 형식, 특정 회사의 코딩 컨벤션 등을 말한다. 일반적인 기술 글쓰기나 요약은 fine-tuning 없이도 충분히 잘 된다.

실전 사례 3가지

1. 고객 지원 챗봇 → RAG

B2B SaaS 회사의 고객 지원 자동화를 구축한다고 하자. 제품 FAQ, 릴리즈 노트, 사용자 가이드가 수백 개 있다.

이 경우 RAG가 정답이다. 이유:

  • 문서가 자주 업데이트된다 (신기능 추가 시)
  • 특정 제품에 대한 정확한 정보가 필요하다 (환각 허용 불가)
  • 모델이 스타일을 새로 배울 필요가 없다

Fine-tuning을 선택하면 문서가 업데이트될 때마다 재학습해야 하고, 비용과 시간이 폭발한다.

2. 의료 기록 요약 → Fine-tuning

병원의 EMR(Electronic Medical Record) 시스템에서 진료 기록을 자동으로 요약하는 시스템을 만든다고 하자.

여기서는 Fine-tuning이 필요하다. 이유:

  • Hx of HTN, DM2, CKD3 같은 의학 약어를 정확히 해석해야 한다
  • SOAP 노트 형식(Subjective-Objective-Assessment-Plan)을 정확히 따라야 한다
  • 일반 LLM은 의학 용어의 미묘한 차이를 놓칠 수 있다

단, RAG와 병행하는 경우도 많다. 의학 가이드라인 문서를 검색 베이스로 두고, fine-tuned 모델이 생성하는 패턴이다.

3. 코드 리뷰 도우미 → Prompt Engineering + Few-shot

팀의 코드 리뷰를 보조하는 AI를 만든다고 하자.

Prompt Engineering(특히 few-shot)이 충분하다. 이유:

  • LLM은 이미 코드를 잘 이해한다
  • 리뷰 스타일 예시를 3-5개 넣어주면 팀 스타일을 금방 따라한다
  • 굳이 비싼 fine-tuning이나 복잡한 RAG 인프라가 필요 없다
SYSTEM_PROMPT = """You are a senior engineer doing code review.
Review style: direct, constructive, specific line references.

Example reviews:
---
[EXAMPLE 1]
Code: for i in range(len(items)): process(items[i])
Review: Use enumerate() instead. This is cleaner:
  for i, item in enumerate(items): process(item)
---
[EXAMPLE 2]
Code: try: result = api_call() except: pass
Review: Never use bare except. Catch specific exceptions and log them:
  try: result = api_call()
  except RequestException as e: logger.error(f"API call failed: {e}"); raise
---
Now review the following code:"""

비용 계산 실례

하루 10,000건 쿼리를 처리하는 서비스를 가정하자. GPT-4o 기준으로 대략 계산하면:

Prompt Engineering만 사용

  • 쿼리당 평균 1,000 토큰 (입력 800 + 출력 200)
  • 월 300만 건 × 0.005달러/1K 토큰 ≈ 월 약 150달러
  • 인프라 추가 비용: 거의 없음

RAG 추가

  • 쿼리당 토큰 증가: 검색된 컨텍스트 ~2,000 토큰 추가
  • 토큰 비용: 월 약 450달러 (약 3배)
  • 벡터DB 운영비(Pinecone 등): 월 약 70달러
  • 총 월 운영비: 약 520달러

Fine-tuning

  • 학습 비용(GPT-4o fine-tuning): 데이터 100만 토큰 기준 약 25달러 (1회성)
  • 인퍼런스 비용: fine-tuned 모델은 기본 모델보다 비쌈 (+20~50%)
  • 총 월 운영비: 약 180~225달러 + 재학습 비용

결론: RAG는 토큰 비용이 올라가지만, 사내 문서가 필요하다면 선택의 여지가 없다. Fine-tuning은 인퍼런스 비용만 보면 나쁘지 않지만, 재학습 주기와 레이블링 인력 비용을 합산하면 실제로는 훨씬 비싸다.

세 가지를 동시에 쓰는 경우

엔터프라이즈 수준의 AI 제품에서는 세 가지를 함께 쓰는 패턴이 효과적이다.

[System Prompt]Prompt Engineering
"당신은 ABC 회사의 전문 상담원입니다.
 항상 한국어로, 공손하게 답변하세요."

[Retrieved Context]RAG
"관련 문서: [FAQ #127] 환불 정책은 30일 이내..."

[User Query]
"주문한 제품을 반품하고 싶어요."

[Fine-tuned Model]Fine-tuning
도메인 특화 언어 이해 + 회사 톤앤매너 내재화

이 조합이 최고의 결과를 내는 이유:

  • System prompt: 역할과 제약 정의
  • RAG: 최신 정확한 정보 제공
  • Fine-tuning: 도메인 용어 이해 및 일관된 스타일

다만 이 조합은 구축과 운영이 복잡하다. MVP 단계에서는 과도한 엔지니어링이다.

Python으로 만드는 간단한 의사결정 헬퍼

def choose_approach(
    has_private_docs: bool,
    needs_latest_info: bool,
    has_training_data: bool,
    budget: str  # 'low', 'medium', 'high'
) -> str:
    """
    Returns recommended approach based on project characteristics.

    Args:
        has_private_docs: Do you have internal/proprietary documents?
        needs_latest_info: Does the system need up-to-date information?
        has_training_data: Do you have labeled training examples?
        budget: Development + ops budget level

    Returns:
        Recommended approach string
    """
    if has_private_docs or needs_latest_info:
        if has_training_data and budget == 'high':
            return "RAG + Fine-tuning (hybrid approach)"
        return "RAG"

    if has_training_data and budget in ['medium', 'high']:
        return "Fine-tuning (consider starting with Prompt Engineering first)"

    return "Prompt Engineering (start here, iterate fast)"


# 실제 사용 예시
print(choose_approach(
    has_private_docs=True,
    needs_latest_info=True,
    has_training_data=False,
    budget='medium'
))
# 출력: "RAG"

print(choose_approach(
    has_private_docs=False,
    needs_latest_info=False,
    has_training_data=True,
    budget='high'
))
# 출력: "Fine-tuning (consider starting with Prompt Engineering first)"

자주 하는 실수

실수 1: Fine-tuning을 첫 번째 선택지로 고려 Fine-tuning은 마지막 수단이다. GPT-4o에 좋은 system prompt를 주는 것만으로도 대부분의 fine-tuning 효과를 얻을 수 있다.

실수 2: RAG를 만능 해결책으로 생각 RAG는 retrieval 품질에 완전히 의존한다. "관련 문서를 잘 못 찾아오면" 아무리 좋은 LLM도 소용없다. 청킹 전략과 임베딩 품질이 핵심이다.

실수 3: 평가 없이 배포 세 가지 접근 중 어떤 것을 선택하든, 정량적 평가 없이 "느낌"으로 배포하면 안 된다. RAGAS 같은 툴로 측정하고 개선해야 한다.

결론: 단계적 접근

  1. Prompt Engineering으로 시작 → 하루 만에 첫 번째 버전 완성
  2. 사내 문서가 필요하면 RAG 추가 → 며칠 안에 구축 가능
  3. 도메인 특화가 정말 필요할 때만 Fine-tuning 검토 → 몇 주 투자 가치가 있는지 판단

"완벽한 시스템을 처음부터 만들려다가 아무것도 못 배포하는" 함정에 빠지지 말자. Prompt Engineering부터 시작하고, 실제 유저 피드백을 보면서 단계적으로 복잡도를 높이는 게 현실적으로 가장 빠른 길이다.

RAG vs Fine-tuning vs Prompt Engineering: The Complete Decision Framework

The Question Every AI Product Team Asks

"We want to add AI to our product — which approach should we use?"

I've heard this question hundreds of times. From startup CTOs, enterprise dev leads, solo developers building side projects — everyone hits this same decision point. And most of them jump too fast to either "let's fine-tune a model" or "we need to build a full RAG pipeline."

Here's the honest answer: Start with Prompt Engineering. Add RAG when you need private/up-to-date knowledge. Fine-tune only as a last resort. Fine-tuning is needed far less often than people think.

This post gives you the real framework for making this decision — with actual cost numbers and production war stories.

What Are These Three Approaches?

Let's be precise about the definitions.

Prompt Engineering optimizes the input you give to an LLM. This includes writing effective system prompts, adding few-shot examples, and structuring Chain-of-Thought reasoning. The model's weights are never modified.

RAG (Retrieval-Augmented Generation) retrieves relevant documents from an external knowledge base and feeds them as context to the LLM. It gives the model access to knowledge it wasn't trained on — in real time.

Fine-tuning continues training a pre-trained LLM on domain-specific data. The model weights are directly modified, baking new knowledge and behavior into the model itself.

Comparison Table

PropertyPrompt EngineeringRAGFine-tuning
Upfront costMinimalMediumHigh
Time to first versionHoursDaysWeeks
Knowledge updatesInstantInstantRequires retraining
Domain expertiseWeakMediumStrong
Data requirementsNoneDocument corpusLabeled dataset
Hallucination riskHighLowMedium
Operational complexityLowMediumHigh
Style/format controlMediumMediumStrong

The two most important columns are Knowledge updates and Hallucination risk. RAG has lower hallucination risk than fine-tuning because you can instruct the model to cite retrieved documents rather than generate from memory.

Decision Framework

Q1: Do you need current information or private/internal documents?
    YESConsider RAG
    NONext question

Q2: Do you need a specific output style, format, or domain-specific language?
    YESConsider Fine-tuning
    NOStart with Prompt Engineering

Q3: You tried RAG but retrieval quality is consistently poor?
         (e.g., model can't understand domain-specific terminology)
    YESRAG + Fine-tuning combination
    NORAG alone is sufficient

Q4: Prompt Engineering output is inconsistent?
    YESAdd more few-shot examples, or consider Fine-tuning
    NOStick with current approach

Practical Notes on Each Branch

"Internal documents" in Q1 means FAQs, product manuals, Confluence pages, Notion wikis, Slack archives — anything the base LLM wasn't trained on. RAG is required for this.

"Domain-specific language" in Q2 means medical abbreviation systems, specific legal document formats, your company's internal coding conventions. Normal technical writing and summarization usually work fine without fine-tuning.

Three Real-World Case Studies

1. Customer Support Chatbot → RAG

You're building AI-powered customer support for a B2B SaaS product. You have hundreds of FAQ documents, release notes, and user guides.

RAG is the right choice here. Reasons:

  • Documents update frequently (every new feature release)
  • You need accurate, product-specific information (hallucinations are unacceptable)
  • The model doesn't need to learn a new writing style

If you chose fine-tuning instead, you'd need to retrain every time the docs update — a cost and time disaster.

2. Medical Record Summarization → Fine-tuning

You're building an automatic summarization system for EMR (Electronic Medical Records) in a hospital.

Fine-tuning is genuinely needed here. Reasons:

  • Must correctly interpret medical abbreviations like Hx of HTN, DM2, CKD3
  • Must follow the SOAP note format precisely (Subjective-Objective-Assessment-Plan)
  • A general LLM will miss subtle differences in medical terminology

That said, this is often paired with RAG too — medical guideline documents as the retrieval base, with a fine-tuned model doing the generation.

3. Code Review Assistant → Prompt Engineering + Few-shot

You want an AI assistant to help with your team's code reviews.

Prompt Engineering with few-shot examples is sufficient. Reasons:

  • LLMs already understand code very well
  • 3-5 review examples in the prompt quickly teach your team's style
  • There's no need for expensive fine-tuning or a complex RAG infrastructure
SYSTEM_PROMPT = """You are a senior engineer doing code review.
Review style: direct, constructive, with specific line references.

Example reviews:
---
[EXAMPLE 1]
Code: for i in range(len(items)): process(items[i])
Review: Use enumerate() instead — cleaner and more Pythonic:
  for i, item in enumerate(items): process(item)
---
[EXAMPLE 2]
Code: try: result = api_call() except: pass
Review: Never use bare except. Catch specific exceptions and log them:
  try: result = api_call()
  except RequestException as e: logger.error(f"API call failed: {e}"); raise
---
Now review the following code:"""

Real Cost Comparison

Let's assume a service handling 10,000 queries per day. Using GPT-4o pricing as a baseline:

Prompt Engineering only

  • Average 1,000 tokens per query (800 input + 200 output)
  • 3M queries/month × 0.005/1Ktokens 0.005/1K tokens ≈ **~150/month**
  • Additional infrastructure: nearly zero

Adding RAG

  • Token increase: ~2,000 additional tokens per query for retrieved context
  • Token cost: ~$450/month (3x increase)
  • Vector DB (e.g., Pinecone): ~$70/month
  • Total monthly cost: ~$520/month

Fine-tuning

  • Training cost (GPT-4o fine-tuning): ~$25 one-time for 1M tokens of data
  • Inference cost: fine-tuned models cost 20-50% more than base models
  • Total monthly cost: ~$180-225/month + retraining costs

The takeaway: RAG significantly increases token costs, but if you need private documents, you have no choice. Fine-tuning looks cheap on inference cost alone, but factor in periodic retraining and labeling labor and it's actually much more expensive.

Combining All Three

For enterprise-grade AI products, all three approaches together can produce excellent results:

[System Prompt]               <- Prompt Engineering
"You are a professional support agent for ACME Corp.
 Always be polite and respond in the user's language."

[Retrieved Context]           <- RAG
"Relevant doc: [FAQ #127] Return policy allows 30 days from..."

[User Query]
"I'd like to return a product I ordered."

[Fine-tuned Model]            <- Fine-tuning
Domain terminology understanding + company tone internalized

Why this combination excels:

  • System prompt: defines role and constraints
  • RAG: provides current, accurate information
  • Fine-tuning: domain vocabulary understanding + consistent style

Be warned though — this combination is complex to build and operate. It's over-engineering for an MVP stage.

Code: Simple Decision Helper

def choose_approach(
    has_private_docs: bool,
    needs_latest_info: bool,
    has_training_data: bool,
    budget: str  # 'low', 'medium', 'high'
) -> str:
    """
    Returns recommended approach based on project characteristics.

    Args:
        has_private_docs: Do you have internal/proprietary documents?
        needs_latest_info: Does the system need up-to-date information?
        has_training_data: Do you have labeled training examples?
        budget: Development + ops budget level

    Returns:
        Recommended approach string
    """
    if has_private_docs or needs_latest_info:
        if has_training_data and budget == 'high':
            return "RAG + Fine-tuning (hybrid approach)"
        return "RAG"

    if has_training_data and budget in ['medium', 'high']:
        return "Fine-tuning (but try Prompt Engineering first)"

    return "Prompt Engineering (start here, iterate fast)"


# Usage examples
print(choose_approach(
    has_private_docs=True,
    needs_latest_info=True,
    has_training_data=False,
    budget='medium'
))
# Output: "RAG"

print(choose_approach(
    has_private_docs=False,
    needs_latest_info=False,
    has_training_data=True,
    budget='high'
))
# Output: "Fine-tuning (but try Prompt Engineering first)"

Common Mistakes

Mistake 1: Treating fine-tuning as the first option Fine-tuning is a last resort. A well-crafted system prompt for GPT-4o will get you most of the fine-tuning benefits without the complexity and cost.

Mistake 2: Thinking RAG is a silver bullet RAG is entirely dependent on retrieval quality. If your search doesn't return relevant documents, the best LLM in the world can't save you. Chunking strategy and embedding quality are critical — more on this in a follow-up post.

Mistake 3: Shipping without evaluation Whatever approach you choose, deploying based on "vibes" without quantitative evaluation is a mistake. Use tools like RAGAS to measure and iterate.

Conclusion: The Incremental Approach

  1. Start with Prompt Engineering → Ship a first version in a day
  2. Add RAG when you need internal documents → Buildable in a few days
  3. Consider Fine-tuning only when domain specialization is truly necessary → Invest weeks only when justified

Don't fall into the trap of trying to build the perfect system from scratch. Start with Prompt Engineering, gather real user feedback, and incrementally increase complexity. That's the fastest path in practice.