대규모 언어 모델(LLM)은 강력하지만 두 가지 주요 제약이 있습니다:
- 유한한 컨텍스트 — 전체 말뭉치를 한 번에 수용할 수 없습니다.
- 정적 지식 — 훈련 데이터가 특정 시점에 고정되어 있습니다.
Retrieval은 쿼리 시점에 관련된 외부 지식을 가져옴으로써 이러한 문제를 해결합니다. 이것이 검색-증강 생성(Retrieval-Augmented Generation, RAG)의 기초입니다: 컨텍스트별 정보로 LLM의 답변을 향상시키는 것입니다.
Building a knowledge base
지식 베이스(knowledge base)는 검색 중에 사용되는 문서 또는 구조화된 데이터의 저장소입니다.
맞춤형 지식 베이스가 필요한 경우, LangChain의 document loaders와 vector stores를 사용하여 자신의 데이터로부터 구축할 수 있습니다.
참고
이미 지식 베이스(예: SQL 데이터베이스, CRM, 또는 내부 문서 시스템)를 가지고 있다면, 다시 구축할 필요가 없습니다. 다음과 같이 할 수 있습니다:
- Agentic RAG에서 에이전트를 위한 도구(tool)로 연결합니다.
- 쿼리하고 검색된 콘텐츠를 LLM에 컨텍스트로 제공합니다 (2-Step RAG).
검색 가능한 지식 베이스와 최소 RAG 워크플로우를 구축하려면 다음 튜토리얼을 참조하세요:
Tutorial: Semantic search
LangChain의 document loaders, embeddings, vector stores를 사용하여 자신의 데이터로부터 검색 가능한 지식 베이스를 만드는 방법을 학습합니다.
이 튜토리얼에서는 PDF에 대한 검색 엔진을 구축하여 쿼리와 관련된 구절을 검색할 수 있습니다. 또한 이 엔진 위에 최소 RAG 워크플로우를 구현하여 외부 지식이 LLM 추론에 어떻게 통합될 수 있는지 확인할 수 있습니다.
From retrieval to RAG
Retrieval은 LLM이 런타임에 관련 컨텍스트에 액세스할 수 있게 합니다. 그러나 대부분의 실제 애플리케이션은 한 단계 더 나아갑니다: 검색과 생성을 통합하여 근거 있고 컨텍스트를 인식하는 답변을 생성합니다.
이것이 검색-증강 생성(Retrieval-Augmented Generation, RAG)의 핵심 아이디어입니다. 검색 파이프라인은 검색과 생성을 결합하는 더 광범위한 시스템의 기반이 됩니다.
Retrieval Pipeline
일반적인 검색 워크플로우는 다음과 같습니다:

각 구성 요소는 모듈식입니다: 앱의 로직을 다시 작성하지 않고도 로더, 스플리터, 임베딩 또는 벡터 스토어를 교체할 수 있습니다.
Building Blocks
Document loaders
외부 소스(Google Drive, Slack, Notion 등)에서 데이터를 수집하여 표준화된 Document 객체를 반환합니다.
Text splitters
대형 문서를 개별적으로 검색 가능하고 모델의 컨텍스트 윈도우에 맞는 더 작은 청크로 분할합니다.
Embedding models
임베딩 모델은 텍스트를 숫자 벡터로 변환하여 유사한 의미를 가진 텍스트가 벡터 공간에서 가까이 위치하도록 합니다.
Vector stores
임베딩을 저장하고 검색하기 위한 특수 데이터베이스입니다.
Retrievers
retriever는 구조화되지 않은 쿼리가 주어졌을 때 문서를 반환하는 인터페이스입니다.
RAG Architectures
RAG는 시스템의 요구 사항에 따라 여러 방식으로 구현될 수 있습니다. 아래 섹션에서 각 유형을 설명합니다.
| Architecture | Description | Control | Flexibility | Latency | Example Use Case |
|---|---|---|---|---|---|
| 2-Step RAG | 검색이 항상 생성 전에 발생합니다. 간단하고 예측 가능합니다 | ✅ High | ❌ Low | ⚡ Fast | FAQ, 문서 봇 |
| Agentic RAG | LLM 기반 에이전트가 추론 중 언제 그리고 어떻게 검색할지 결정합니다 | ❌ Low | ✅ High | ⏳ Variable | 여러 도구에 액세스할 수 있는 연구 어시스턴트 |
| Hybrid | 검증 단계를 통해 두 접근 방식의 특성을 결합합니다 | ⚖️ Medium | ⚖️ Medium | ⏳ Variable | 품질 검증이 있는 도메인별 Q&A |
Latency: 2-Step RAG에서 지연 시간은 일반적으로 더 예측 가능합니다. 최대 LLM 호출 횟수가 알려져 있고 제한되어 있기 때문입니다. 이 예측 가능성은 LLM 추론 시간이 지배적인 요인이라고 가정합니다. 그러나 실제 지연 시간은 API 응답 시간, 네트워크 지연 또는 데이터베이스 쿼리와 같은 검색 단계의 성능에도 영향을 받을 수 있으며, 이는 사용 중인 도구와 인프라에 따라 달라질 수 있습니다.
2-step RAG
2-Step RAG에서는 검색 단계가 항상 생성 단계 전에 실행됩니다. 이 아키텍처는 간단하고 예측 가능하여 관련 문서 검색이 답변 생성의 명확한 전제 조건인 많은 애플리케이션에 적합합니다.

Tutorial: Retrieval-Augmented Generation (RAG)
검색-증강 생성을 사용하여 데이터에 기반한 질문에 답변할 수 있는 Q&A 챗봇을 구축하는 방법을 확인하세요.
이 튜토리얼은 두 가지 접근 방식을 안내합니다:
- 유연한 도구로 검색을 실행하는 RAG 에이전트 — 범용 사용에 적합합니다.
- 쿼리당 하나의 LLM 호출만 필요한 2-step RAG 체인 — 더 간단한 작업에 빠르고 효율적입니다.
Agentic RAG
에이전틱 검색-증강 생성(Agentic Retrieval-Augmented Generation, RAG)은 검색-증강 생성의 강점과 에이전트 기반 추론을 결합합니다. 답변하기 전에 문서를 검색하는 대신, (LLM으로 구동되는) 에이전트가 단계별로 추론하고 상호 작용 중 언제 그리고 어떻게 정보를 검색할지 결정합니다.
에이전트가 RAG 동작을 활성화하기 위해 필요한 것은 문서 로더, 웹 API 또는 데이터베이스 쿼리와 같은 외부 지식을 가져올 수 있는 하나 이상의 도구에 대한 액세스입니다.

import requests
from langchain.tools import tool
from langchain.chat_models import init_chat_model
from langchain.agents import create_agent
@tool
def fetch_url(url: str) -> str:
"""Fetch text content from a URL"""
response = requests.get(url, timeout=10.0)
response.raise_for_status()
return response.text
system_prompt = """\
Use fetch_url when you need to fetch information from a web-page; quote relevant snippets.
"""
agent = create_agent(
model="claude-sonnet-4-5-20250929",
tools=[fetch_url], # A tool for retrieval
system_prompt=system_prompt,
)
Extended example: Agentic RAG for LangGraph's llms.txt
이 예제는 사용자가 LangGraph 문서를 쿼리하는 것을 돕기 위한 에이전틱 RAG 시스템을 구현합니다. 에이전트는 먼저 사용 가능한 문서 URL을 나열하는 llms.txt를 로드한 다음, 사용자의 질문에 따라 관련 콘텐츠를 검색하고 처리하기 위해 fetch_documentation 도구를 동적으로 사용할 수 있습니다.
import requests
from langchain.agents import create_agent
from langchain.messages import HumanMessage
from langchain.tools import tool
from markdownify import markdownify
ALLOWED_DOMAINS = ["https://langchain-ai.github.io/"]
LLMS_TXT = 'https://langchain-ai.github.io/langgraph/llms.txt'
@tool
def fetch_documentation(url: str) -> str:
"""Fetch and convert documentation from a URL"""
if not any(url.startswith(domain) for domain in ALLOWED_DOMAINS):
return (
"Error: URL not allowed. "
f"Must start with one of: {', '.join(ALLOWED_DOMAINS)}"
)
response = requests.get(url, timeout=10.0)
response.raise_for_status()
return markdownify(response.text)
# We will fetch the content of llms.txt, so this can
# be done ahead of time without requiring an LLM request.
llms_txt_content = requests.get(LLMS_TXT).text
# System prompt for the agent
system_prompt = f"""
You are an expert Python developer and technical assistant.
Your primary role is to help users with questions about LangGraph and related tools.
Instructions:
1. If a user asks a question you're unsure about — or one that likely involves API usage,
behavior, or configuration — you MUST use the `fetch_documentation` tool to consult the relevant docs.
2. When citing documentation, summarize clearly and include relevant context from the content.
3. Do not use any URLs outside of the allowed domain.
4. If a documentation fetch fails, tell the user and proceed with your best expert understanding.
You can access official documentation from the following approved sources:
{llms_txt_content}
You MUST consult the documentation to get up to date documentation
before answering a user's question about LangGraph.
Your answers should be clear, concise, and technically accurate.
"""
tools = [fetch_documentation]
model = init_chat_model("claude-sonnet-4-0", max_tokens=32_000)
agent = create_agent(
model=model,
tools=tools,
system_prompt=system_prompt,
name="Agentic RAG",
)
response = agent.invoke({
'messages': [
HumanMessage(
content=(
"Write a short example of a langgraph agent using the "
"prebuilt create react agent. the agent should be able "
"to look up stock pricing information."
))
]
})
print(response['messages'][-1].content)
Tutorial: Retrieval-Augmented Generation (RAG)
검색-증강 생성을 사용하여 데이터에 기반한 질문에 답변할 수 있는 Q&A 챗봇을 구축하는 방법을 확인하세요.
이 튜토리얼은 두 가지 접근 방식을 안내합니다:
- 유연한 도구로 검색을 실행하는 RAG 에이전트 — 범용 사용에 적합합니다.
- 쿼리당 하나의 LLM 호출만 필요한 2-step RAG 체인 — 더 간단한 작업에 빠르고 효율적입니다.
Hybrid RAG
Hybrid RAG는 2-Step과 Agentic RAG의 특성을 결합합니다. 쿼리 전처리, 검색 검증, 생성 후 검사와 같은 중간 단계를 도입합니다. 이러한 시스템은 고정된 파이프라인보다 더 많은 유연성을 제공하면서 실행에 대한 일부 제어를 유지합니다.
일반적인 구성 요소는 다음과 같습니다:
쿼리 향상(Query enhancement): 검색 품질을 향상시키기 위해 입력 질문을 수정합니다. 이는 불명확한 쿼리 재작성, 여러 변형 생성 또는 추가 컨텍스트로 쿼리 확장을 포함할 수 있습니다.
검색 검증(Retrieval validation): 검색된 문서가 관련성이 있고 충분한지 평가합니다. 그렇지 않은 경우, 시스템은 쿼리를 개선하거나 다른 소스를 시도할 수 있습니다.
생성 후 검사(Post-generation checks): 출력이 검색된 컨텍스트와 일치하는지, 환각(hallucination)이 없는지 확인합니다.
아키텍처는 여러 단계를 반복적으로 수행할 수 있게 한다.

다음과 같은 경우에 적합한 아키텍처입니다:
- Ambiguous / underspecified queries가 들어오는 애플리케이션
- Validation / Quality control 단계가 필요한 시스템
- 여러 sources를 다루거나 iterative refinement가 필요한 워크플로우
출처: https://docs.langchain.com/oss/python/langchain/retrieval
Langchain v1.0
- LangChain 개요
- LangChain v1
- LangChain v1 마이그레이션 가이드
- LangChain 설치
- QuickStart
- Philosophy
- Agents
- Models
- Messages
- Tools
- Short-term memory
- Streaming
- Middleware
- Structured output
- Guardrails
- Runtime
- Context Engineering
- Model Context Protocol (MCP)
- Human-in-the-loop
- Multi-agent
Retrieval- Long-term memory
- Studio
- Test
- Deploy
- Agent Chat UI
- Observability
