AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

MongoDB 및 LangChain을 사용하여 로컬 RAG 구현 구축

cloud 에 MongoDB Atlas 배포하는 것 외에도, Atlas CLI 사용하여 로컬 머신에 독립형 MongoDB 인스턴스를 배포 수 있습니다. LangChain MongoDB 통합은 Atlas 클러스터와 로컬 배포를 모두 지원합니다. 연결 문자열 매개변수를 지정할 때 클러스터 연결 연결 문자열 대신 로컬 배포서버 연결 연결 문자열 지정할 수 있습니다.

이 튜토리얼에서는 로컬 Atlas 배포서버, 로컬 모델 및 LangChain MongoDB 통합을 사용하여 RAG(검색 강화 생성) 구현 방법을 보여 줍니다. 구체적으로 다음 조치를 수행합니다.

  1. 로컬 Atlas 배포서버를 생성합니다.

  2. 로컬 임베딩 모델을 사용하여 벡터 임베딩을 생성합니다.

  3. 로컬 Atlas 배포를 벡터 저장소로 사용합니다.

  4. 로컬 LLM을 사용하여 데이터에 대한 질문에 답변 .

To learn how to implement RAG locally without using LangChain, see Build a Local RAG Implementation with MongoDB Vector Search.

이 튜토리얼을 완료하려면 다음 조건을 충족해야 합니다.

  • Python v3.10 이상.

  • Docker가 로컬에서 실행 중입니다.

  • 로컬에서 실행할 수 있는 대화형 Python 노트북입니다. VS Code에서 대화형 Python 노트북을 실행할 수 있습니다.

이 섹션에서는 이 자습서를 위한 환경을 설정합니다. atlas-local-lib-py 라이브러리는 Docker를 통해 로컬 MongoDB 배포서버를 자동으로 만들고 관리하여 수동 설정 또는 CLI 명령이 필요 없습니다.

1

터미널에서 다음 명령을 실행하여 local-rag-langchain-mongodb 이라는 새 디렉토리를 만듭니다.

mkdir local-rag-langchain-mongodb
cd local-rag-langchain-mongodb
2

다음 명령은 langchain-local-rag.ipynb라는 디렉토리에 노트북을 생성합니다.

touch langchain-local-rag.ipynb
3

노트북에서 다음 명령을 실행하여 uv:를 설치합니다.

%pip install --quiet uv

노트북에서 다음 명령을 실행하여 필요한 종속성을 설치하세:

import sys
!uv pip install --system --python "{sys.executable}" atlas-local-lib-py pymongo langchain langchain-classic langchain-mongodb langchain-pymupdf4llm langchain-text-splitters gpt4all langchain-huggingface==1.2.2 sentence-transformers==5.7.0 transformers==4.57.6
4

노트북에서 다음 코드를 실행하여 새 로컬 배포서버를 만들거나 일치하는 구성으로 기존 배포서버를 재사용합니다. 이로써 연결 문자열도 프로그래밍적으로 조회합니다.

from atlas_local import LocalDeployment
# Create or reuse a local Atlas deployment
deployment = LocalDeployment.get_or_create(name="local-atlas-deployment")
deployment.start()
MONGODB_URI = deployment.connection_string()
print("Local deployment ready:", MONGODB_URI)

로컬 Atlas 배포서버 벡터 저장 라고도 하는 벡터 데이터베이스 로 사용할 수 있습니다. 다음 코드 스니펫을 복사하여 노트북에 붙여넣습니다.

1

다음 코드는 MongoDB Vector Search용 LangChain 통합을 사용하여 네임스페이스 사용하여 로컬 Atlas 배포서버 벡터 저장 라고도 하는 벡터 데이터베이스 로 langchain_db.local_rag 인스턴스화합니다.

이 예시 Hugging Face의 voyageai/voyage-4-nano 모델을 지정합니다.

from langchain_mongodb import MongoDBAtlasVectorSearch
from langchain_huggingface import HuggingFaceEmbeddings
# Load the embedding model (https://huggingface.co/voyageai/voyage-4-nano)
embedding_model = HuggingFaceEmbeddings(
model_name="voyageai/voyage-4-nano",
model_kwargs={"trust_remote_code": True, "truncate_dim": 2048},
encode_kwargs={"prompt_name": "document"},
query_encode_kwargs={"prompt_name": "query"},
)
# Instantiate vector store
vector_store = MongoDBAtlasVectorSearch.from_connection_string(
connection_string = MONGODB_URI,
namespace = "langchain_db.local_rag",
embedding=embedding_model,
index_name="vector_index"
)
2

이 자습서의 이전 실행이 있는 경우 노트북에서 다음 코드를 실행하여 깨끗한 langchain_db.local_rag 컬렉션에서 시작합니다.

from pymongo import MongoClient
# Start from a clean collection, in case of previous runs of this tutorial
MongoClient(MONGODB_URI)["langchain_db"]["local_rag"].drop()

Paste and run the following code in your notebook to ingest a sample PDF that contains a recent MongoDB earnings report into the vector store.

이 코드는 텍스트 분할기를 사용하여 PDF 데이터를 더 작은 상위 문서로 청크화합니다. 각 문서에 대해 청크 크기(문자 수)와 청크 겹침(연속된 청크 사이에 겹치는 문자 수)을 지정합니다.

from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_pymupdf4llm import PyMuPDF4LLMLoader
# Load the PDF
loader = PyMuPDF4LLMLoader("https://investors.mongodb.com/node/13176/pdf")
data = loader.load()
# Split PDF into documents
text_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=20)
docs = text_splitter.split_documents(data)
# Add data to the vector store
vector_store.add_documents(docs)

이 코드는 실행 데 몇 분 정도 걸릴 수 있습니다. 작업이 완료된 후 Atlas 사용하는 경우 langchain_db.local_rag Atlas UI 의 네임스페이스 로 이동하여 벡터 임베딩을 확인할 수 있습니다.

You can also view your vector embeddings by connecting to your local deployment from mongosh or your application using your deployment's connection string. Then you can run read operations on the langchain_db.local_rag collection.

3

벡터 저장 에서 벡터 검색 쿼리를 활성화 하려면 langchain_db.local_rag 컬렉션 에 MongoDB Vector Search 인덱스 만듭니다. LangChain 헬퍼 메서드를 사용하여 인덱스 만들 수 있습니다.

# Use helper method to create the vector search index
vector_store.create_vector_search_index(
dimensions = 2048 # The dimensions of the vector embeddings to be indexed
)

The index should take about one minute to build. While it builds, the index is in an initial sync state. When it finishes building, you can start querying the data in your collection.

이 섹션에서는 MongoDB 벡터 검색 및 GPT4All을 사용하여 로컬에서 실행할 수 있는 샘플 RAG 구현을 보여줍니다.

LangChain을 사용하여 로컬에서 LLM을 실행 다른 방법을 학습 로컬에서 모델 실행을 참조하세요.

1
  1. 다음 버튼을 클릭하여 GPT4All에서 Mistral 7B 모델을 다운로드하세요. 다른 모델을 살펴보려면 GPT4All 웹사이트를 참조하세요.

    다운로드
  2. 이 모델을 local-rag-langchain-mongodb 프로젝트 디렉토리로 이동합니다.

  3. 다음 코드를 노트북에 붙여넣어 LLM을 구성하세요. 실행하기 전에 <path-to-model>을(를) LLM을 로컬에 저장한 경로로 바꾸세요.

    from langchain_core.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
    from langchain_classic.llms import GPT4All
    # Configure the LLM
    local_path = "<path-to-model>"
    # Callbacks support token-wise streaming
    callbacks = [StreamingStdOutCallbackHandler()]
    # Verbose is required to pass to the callback manager
    llm = GPT4All(model=local_path, callbacks=callbacks, verbose=True)
2

다음 코드를 실행하여 RAG 구현을 완료합니다.

from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
import pprint
# Instantiate MongoDB Vector Search as a retriever
retriever = vector_store.as_retriever()
# Define prompt template
template = """
Use the following pieces of context to answer the question at the end.
{context}
Question: {question}
"""
custom_rag_prompt = PromptTemplate.from_template(template)
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
# Create chain
rag_chain = (
{"context": retriever | format_docs, "question": RunnablePassthrough()}
| custom_rag_prompt
| llm
| StrOutputParser()
)
# Prompt the chain
question = "What was MongoDB's latest acquisition?"
answer = rag_chain.invoke(question)
# Return source documents
documents = retriever.invoke(question)
print("\nSource documents:")
pprint.pprint(documents)
Answer: MongoDB's latest acquisition was Voyage AI, a pioneer in state-of-the-art embedding and reranking models that power next-generation
Source documents:
[Document(id='680a98187685ddb66d29ed88', metadata={'_id': '680a98187685ddb66d29ed88', 'producer': 'West Corporation using ABCpdf', 'creator': 'PyPDF', 'creationdate': '2025-03-05T21:06:26+00:00', 'title': 'MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results', 'source': 'https://investors.mongodb.com/node/13176/pdf', 'total_pages': 9, 'page': 1, 'page_label': '2'}, page_content='Measures."\nFourth Quarter Fiscal 2025 and Recent Business Highlights\nMongoDB acquired Voyage AI, a pioneer in state-of-the-art embedding and reranking models that power next-generation'),
Document(id='680a98187685ddb66d29ed8c', metadata={'_id': '680a98187685ddb66d29ed8c', 'producer': 'West Corporation using ABCpdf', 'creator': 'PyPDF', 'creationdate': '2025-03-05T21:06:26+00:00', 'title': 'MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results', 'source': 'https://investors.mongodb.com/node/13176/pdf', 'total_pages': 9, 'page': 1, 'page_label': '2'}, page_content='conjunction with the acquisition of Voyage, MongoDB is announcing a stock buyback program of $200 million, to offset the\ndilutive impact of the acquisition consideration.'),
Document(id='680a98187685ddb66d29ee3f', metadata={'_id': '680a98187685ddb66d29ee3f', 'producer': 'West Corporation using ABCpdf', 'creator': 'PyPDF', 'creationdate': '2025-03-05T21:06:26+00:00', 'title': 'MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results', 'source': 'https://investors.mongodb.com/node/13176/pdf', 'total_pages': 9, 'page': 8, 'page_label': '9'}, page_content='View original content to download multimedia:https://www.prnewswire.com/news-releases/mongodb-inc-announces-fourth-quarter-and-full-\nyear-fiscal-2025-financial-results-302393702.html'),
Document(id='680a98187685ddb66d29edde', metadata={'_id': '680a98187685ddb66d29edde', 'producer': 'West Corporation using ABCpdf', 'creator': 'PyPDF', 'creationdate': '2025-03-05T21:06:26+00:00', 'title': 'MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results', 'source': 'https://investors.mongodb.com/node/13176/pdf', 'total_pages': 9, 'page': 3, 'page_label': '4'}, page_content='distributed database on the market. With integrated capabilities for operational data, search, real-time analytics, and AI-powered retrieval, MongoDB')]