참고
이 튜토리얼에서는 LangChain의 Python 라이브러리를 사용합니다. JavaScript 라이브러리를 사용하는 튜토리얼은 LangChain JavaScript/ 타입스크립트 (Typescript) 통합 시작하기를 참조하세요.
MongoDB Vector Search를 LangChain과 통합하여 LLM 애플리케이션을 빌드 하고 RAG(검색 강화 생성)를 구현 수 있습니다. 이 튜토리얼에서는 MongoDB Vector Search와 LangChain을 함께 사용하여 데이터에서 시맨틱 검색 수행하고 RAG 구현 빌드 방법을 설명합니다. 구체적으로 다음 조치를 수행합니다.
환경을 설정합니다.
사용자 지정 데이터를 MongoDB 에 저장합니다.
데이터에 MongoDB Vector Search 인덱스 생성합니다.
다음 벡터 검색 쿼리를 실행합니다.
시맨틱 검색.
점수가 있는 시맨틱 검색.
메타데이터 사전 필터링을 통한 시맨틱 검색.
MongoDB Vector Search를 사용하여 데이터에 대한 질문에 답변 RAG 를 구현합니다.
배경
LangChain은 '체인'을 사용하여 LLM 애플리케이션 생성을 간소화하는 오픈 소스 프레임워크입니다. 체인은 RAG를 포함한 다양한 AI 사용 사례에 대해 결합할 수 있는 LangChain 관련 구성 요소입니다.
By integrating MongoDB Vector Search with LangChain, you can use MongoDB as a vector database and use MongoDB Vector Search to implement RAG by retrieving semantically similar documents from your data. To learn more about RAG, see Retrieval-Augmented Generation (RAG) with MongoDB.
전제 조건
이 튜토리얼을 완료하려면 다음 조건을 충족해야 합니다.
다음 MongoDB cluster 유형 중 하나입니다.
MongoDB 버전 6.0.11을 실행하는 Atlas 클러스터, 7.0.2 이상. 당신의 IP 주소가 Atlas 프로젝트의 액세스 목록에 포함되어 있는지 확인하세요.
Python과 Docker를 사용하여 만든 로컬 Atlas 배포서버입니다.
atlas-local-lib-py(pip install atlas-local-lib-py)를 설치하여 로컬 배포서버를 프로그래밍으로 만들고 관리할 수 있습니다. 자세한 내용은 atlas-local-lib-py 리포지토리를 참조하십시오.A MongoDB Community cluster with Search and Vector Search installed.
A Voyage AI API key. To create an API key, see Manage Voyage AI Model API Keys.
OpenAI API 키입니다. API 요청에 사용할 수 있는 크레딧이 있는 OpenAI 계정이 있어야 합니다. OpenAI 계정 등록에 대해 자세히 학습하려면 OpenAI API 웹사이트를 참조하세요.
Colab과같은 대화형 Python 노트북을 실행 수 있는 환경입니다.
환경 설정
이 튜토리얼의 환경을 설정합니다. 확장자가 .ipynb 인 파일 저장하여 대화형 Python 노트북을 만듭니다. 이 노트북을 사용하면 Python 코드 스니펫을 개별적으로 실행 수 있으며, 이 튜토리얼에서는 이를 사용하여 코드를 실행 .
노트북 환경을 설정하다 하려면 다음을 수행합니다.
종속성을 설치하고 가져옵니다.
다음 명령을 실행합니다:
pip install --quiet --upgrade langchain langchain-community langchain-core langchain-mongodb langchain-voyageai langchain-openai langchain-text-splitters pymongo pypdf
그런 다음, 다음 코드를 실행하여 필요한 패키지를 가져옵니다.
import os, pymongo, pprint from langchain_community.document_loaders import PyPDFLoader from langchain_core.output_parsers import StrOutputParser from langchain_core.runnables import RunnablePassthrough from langchain_mongodb import MongoDBAtlasVectorSearch from langchain_voyageai import VoyageAIEmbeddings from langchain_openai import ChatOpenAI from langchain.prompts import PromptTemplate from langchain_text_splitters import RecursiveCharacterTextSplitter from pymongo import MongoClient from pymongo.operations import SearchIndexModel
환경 변수를 정의합니다.
다음 코드를 실행하고 자리 표시자를 다음 값으로 대체합니다.
Voyage AI 및 OpenAI API 키.
MongoDB 클러스터의 연결 문자열.
os.environ["VOYAGE_API_KEY"] = "<voyage-api-key>" os.environ["OPENAI_API_KEY"] = "<openai-api-key>" MONGODB_URI = "<connection-string>"
참고
<connection-string>을 Atlas 클러스터 또는 로컬 Atlas 배포서버의 연결 문자열로 교체합니다.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
중요한: 연결 문자열 에 데이터베이스 사용자의 자격 증명 포함되어 있는지 확인하세요. 연결 문자열 찾는 방법에 대해 자세히 학습하려면 클라이언트 라이브러리를 통해 클러스터에 연결하기를 참조하세요.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb://localhost:<port-number>/?directConnection=true
자세한 학습 은 연결 문자열을 참조하세요.
MongoDB 벡터 저장소로 사용
그런 다음 사용자 지정 데이터를 MongoDB 에 로드하고 MongoDB cluster 를 벡터 저장 라고도 하는 벡터 데이터베이스 로 인스턴스화합니다. 다음 코드 스니펫을 복사하여 노트북에 붙여넣습니다.
샘플 데이터를 불러옵니다.
For this tutorial, you use a publicly accessible PDF document about a recent MongoDB earnings report as the data source for your vector store.
샘플 데이터를 로드하려면 다음 코드 스니펫을 실행합니다. 다음을 수행합니다.
지정된 URL에서 PDF를 검색하고 원시 텍스트 데이터를 로드합니다.
텍스트 분할기 를 사용하여 데이터를 작은 문서로 분할 .
각 문서의 문자 수와 두 개의 연속 문서 간에 겹치는 문자 수를 결정하는 청크 매개변수를 지정합니다.
# Load the PDF loader = PyPDFLoader("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) # Print the first document docs[0]
Document(metadata={'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': 0, 'page_label': '1'}, page_content='MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results\nMarch 5, 2025\nFourth Quarter Fiscal 2025 Total Revenue of $548.4 million, up 20% Year-over-Year')
벡터 저장소를 인스턴스화합니다.
샘플 문서에서 vector_store라는 벡터 저장소 인스턴스를 생성하려면 다음 코드를 실행하세요. 이 코드 스니펫은 다음을 지정합니다.
MongoDB cluster 에 대한 연결 문자열 .
langchain_db.test문서를 저장 MongoDB 네임스페이스 로 사용합니다.Voyage AI 의
voyage-3-large임베딩 모델입니다. 텍스트를embedding필드 에 대한 벡터 임베딩으로 변환합니다.vector_index를 벡터 저장소를 쿼리하는 데 사용할 인덱스로 사용합니다.
# Instantiate the vector store using your MongoDB connection string vector_store = MongoDBAtlasVectorSearch.from_connection_string( connection_string = MONGODB_URI, namespace = "langchain_db.test", embedding = VoyageAIEmbeddings(model="voyage-3-large"), index_name = "vector_index" ) # Add documents to the vector store vector_store.add_documents(documents=docs)
샘플 코드를 실행 후 Atlas 사용하는 경우 langchain_db.test Atlas UI 의 네임스페이스 로이동하여 벡터 임베딩을 확인할 수 있습니다.
MongoDB Vector Search 인덱스 만들기
벡터 저장 에서 벡터 검색 쿼리를 활성화 하려면 LangChain 헬퍼 메서드 또는 PyMongo 운전자 메서드를 사용하여 langchain_db.test 컬렉션 에 MongoDB Vector Search 인덱스 만듭니다.
선호하는 방법을 사용해 노트북에서 다음 코드를 실행합니다. 이 인덱스 정의는 다음 필드의 인덱싱을 지정합니다.
embeddingfield as the vector type. Theembeddingfield contains the embeddings created using Voyage AI'svoyage-3-largeembedding model. The index definition specifies1024vector dimensions and measures similarity usingcosine.page_labelfield as the filter type for pre-filtering data by the page number in the PDF.
# Use helper method to create the vector search index vector_store.create_vector_search_index( dimensions = 1024, # The number of vector dimensions to index filters = [ "page_label" ] )
# Connect to your cluster client = MongoClient(MONGODB_URI) collection = client["langchain_db"]["test"] # Create your vector search index model, then create the index search_index_model = SearchIndexModel( definition={ "fields": [ { "type": "vector", "path": "embedding", "numDimensions": 1024, "similarity": "cosine" }, { "type": "filter", "path": "page_label" } ] }, name="vector_index", type="vectorSearch" ) collection.create_search_index(model=search_index_model)
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.
Vector Search 쿼리 실행
MongoDB 인덱스 빌드하면 데이터에 대해 벡터 검색 쿼리를 실행 . 다음 예제는 벡터화된 데이터에 대해 실행 수 있는 다양한 쿼리를 보여줍니다.
다음 쿼리는 similarity_search 메서드를 사용하여 문자열 MongoDB acquisition 에 대한 기본 시맨틱 검색을 수행합니다. 관련성별로 순위가 지정된 문서 목록을 반환합니다.
query = "MongoDB acquisition" results = vector_store.similarity_search(query) pprint.pprint(results)
[Document(id='67f0259b8bb2babc06924409', metadata={ ... }, page_content='SOURCE MongoDB, Inc.'), Document(id='67f0259b8bb2babc0692432f', metadata={ ... }, page_content='MongoDB platform. In fiscal year 2026 we expect to see stable consumption growth in Atlas, our main growth driver," said Dev Ittycheria, President\nand Chief Executive Officer of MongoDB .'), Document(id='67f0259b8bb2babc06924355', metadata={ ... }, 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='67f0259b8bb2babc069243a6', metadata={ ... }, page_content="MongoDB's unified, intelligent data platform was built to power the next generation of applications, and MongoDB is the most widely available, globally")]
다음 쿼리는 similarity_search_with_score 메서드를 사용하여 문자열 MongoDB acquisition에 대한 시맨틱 검색을 수행하고 k 매개변수를 지정하여 반환할 문서의 수를 3으로 제한합니다.
참고
The k parameter in this example refers to the similarity_search_with_score method option, not the knnBeta operator option of the same name.
It returns the three most relevant documents and a relevance score between 0 and 1.
query = "MongoDB acquisition" results = vector_store.similarity_search_with_score( query = query, k = 3 ) pprint.pprint(results)
[(Document(id='67f0259b8bb2babc06924409', metadata={ ... }, page_content='SOURCE MongoDB, Inc.'), 0.8193451166152954), (Document(id='67f0259b8bb2babc0692432f', metadata={ ... }, page_content='MongoDB platform. In fiscal year 2026 we expect to see stable consumption growth in Atlas, our main growth driver," said Dev Ittycheria, President\nand Chief Executive Officer of MongoDB .'), 0.7815237045288086), (Document(id='67f0259b8bb2babc06924355', metadata={ ... }, 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.'), 0.7788857221603394)]
You can pre-filter your data by using an MQL match expression that compares the indexed field with another value in your collection. You must index any metadata fields that you want to filter by as the filter type. To learn more, see How to Index Fields for Vector Search.
참고
이 튜토리얼의 page_label 인덱스 생성할 때 필드 필터하다 로 지정했습니다.
다음 쿼리는 similarity_search_with_score 메서드를 사용하여 문자열 MongoDB acquisition에 대한 의미 체계 검색을 수행합니다. 또한 다음을 지정합니다.
반환할 문서 수를
3)로 제한하는k매개 변수입니다.A pre-filter on the
page_labelfield that uses the$eqoperator to match documents appearing on page 2 only.
It returns the three most relevant documents from page 2 and a relevance score between 0 and 1.
query = "MongoDB acquisition" results = vector_store.similarity_search_with_score( query = query, k = 3, pre_filter = { "page_label": { "$eq": 2 } } ) pprint.pprint(results)
[(Document(id='67f0259b8bb2babc06924355', metadata={ ... '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.'), 0.7788857221603394), (Document(id='67f0259b8bb2babc06924351', metadata={ ... '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'), 0.7606035470962524), (Document(id='67f0259b8bb2babc06924354', metadata={ ... 'page_label': '2'}, page_content='data.\nMongoDB completed the redemption of 2026 Convertible Notes, eliminating all debt from the balance sheet. Additionally, in'), 0.7583936452865601)]
팁
시맨틱 검색 메서드의 전체 목록은 API 참조를 참조하세요.
데이터에 대한 질문에 답변
이 섹션에서는 MongoDB Vector Search 및 LangChain을 사용하여 애플리케이션에서 RAG 를 구현 방법을 설명합니다. 이제 MongoDB Vector Search를 사용하여 의미적으로 유사한 문서를 조회 했으므로, 다음 코드 예제를 실행 LLM이 해당 문서를 기반으로 질문에 답변 하도록 프롬프트를 표시합니다.
이 예제는 다음을 수행합니다:
LLM이 이러한 문서를 쿼리의 컨텍스트로 사용하도록 지시하는 LangChain 프롬프트 템플릿 을 정의합니다. LangChain은 이러한 문서를
{context}입력 변수에 전달하고 쿼리{question}변수에 전달합니다.다음을 지정하는 체인 을 생성합니다.
MongoDB Vector Search를 리트리버로 사용하여 컨텍스트로 사용할 문서를 검색 .
사용자가 정의한 프롬프트 템플릿입니다.
OpenAI의
gpt-4o채팅 모델은 컨텍스트 인식 응답을 생성합니다.
샘플 쿼리로 체인을 호출합니다.
LLM 의 응답과 컨텍스트로 사용되는 문서를 반환합니다. 생성된 응답은 다를 수 있습니다.
# Instantiate MongoDB Vector Search as a retriever retriever = vector_store.as_retriever( search_type = "similarity", search_kwargs = { "k": 10 } ) # Define a prompt template template = """ Use the following pieces of context to answer the question at the end. {context} Question: {question} """ prompt = PromptTemplate.from_template(template) model = ChatOpenAI(model="gpt-4o") # Construct a chain to answer questions on your data chain = ( { "context": retriever, "question": RunnablePassthrough()} | prompt | model | StrOutputParser() ) # Prompt the chain question = "What was MongoDB's latest acquisition?" answer = chain.invoke(question) print("Question: " + question) print("Answer: " + answer) # Return source documents documents = retriever.invoke(question) print("\nSource documents:") pprint.pprint(documents)
Question: What was MongoDB's latest acquisition? Answer: MongoDB's latest acquisition was Voyage AI, a pioneer in state-of-the-art embedding and reranking models. Source documents: [Document(id='67f0259b8bb2babc06924409', metadata={'_id': '67f0259b8bb2babc06924409', ... 'page_label': '9'}, page_content='SOURCE MongoDB, Inc.'), Document(id='67f0259b8bb2babc06924351', metadata={'_id': '67f0259b8bb2babc06924351', ... '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='67f0259b8bb2babc0692432f', metadata={'_id': '67f0259b8bb2babc0692432f', ... 'page_label': '1'}, page_content='MongoDB platform. In fiscal year 2026 we expect to see stable consumption growth in Atlas, our main growth driver," said Dev Ittycheria, President\nand Chief Executive Officer of MongoDB .'), Document(id='67f0259b8bb2babc06924355', metadata={'_id': '67f0259b8bb2babc06924355', ... '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='67f0259b8bb2babc069243a6', metadata={'_id': '67f0259b8bb2babc069243a6', ... 'page_label': '4'}, page_content="MongoDB's unified, intelligent data platform was built to power the next generation of applications, and MongoDB is the most widely available, globally"), Document(id='67f0259b8bb2babc06924329', metadata={'_id': '67f0259b8bb2babc06924329', ... 'page_label': '1'}, page_content='MongoDB, Inc. Announces Fourth Quarter and Full Year Fiscal 2025 Financial Results\nMarch 5, 2025\nFourth Quarter Fiscal 2025 Total Revenue of $548.4 million, up 20% Year-over-Year'), Document(id='67f0259b8bb2babc069243a7', metadata={'_id': '67f0259b8bb2babc069243a7', ... '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'), Document(id='67f0259b8bb2babc069243a5', metadata={'_id': '67f0259b8bb2babc069243a5', ... 'page_label': '4'}, page_content="Headquartered in New York, MongoDB's mission is to empower innovators to create, transform, and disrupt industries with software and data."), Document(id='67f0259b8bb2babc06924354', metadata={'_id': '67f0259b8bb2babc06924354', ... 'page_label': '2'}, page_content='data.\nMongoDB completed the redemption of 2026 Convertible Notes, eliminating all debt from the balance sheet. Additionally, in'), Document(id='67f0259b8bb2babc069243a9', metadata={'_id': '67f0259b8bb2babc069243a9', ... 'page_label': '4'}, page_content='50,000 customers across almost every industry—including 70% of the Fortune 100—rely on MongoDB for their most important applications. To learn\nmore, visit mongodb.com .\nInvestor Relations')]
이 예제는 다음을 수행합니다:
MongoDB Vector Search를 리트리버 로 인스턴스화하여 다음과 같은 선택적 매개변수를 포함하여 유사한 문서를 쿼리.
k가장 관련성이 높은 문서10개만 검색합니다.score_threshold관련성 점수가0.75이상인 문서만 사용합니다.참고
This parameter refers to a relevance score that Langchain uses to normalize your results, and not the relevance score used in MongoDB Search queries. To use MongoDB Search scores in your RAG implementation, define a custom retriever that uses the
similarity_search_with_scoremethod and filters by the MongoDB Search score.pre_filter2 페이지에만 나타나는 문서에 대해서만page_label필드를 필터링합니다.
LLM이 이러한 문서를 쿼리의 컨텍스트로 사용하도록 지시하는 LangChain 프롬프트 템플릿 을 정의합니다. LangChain은 이러한 문서를
{context}입력 변수에 전달하고 쿼리{question}변수에 전달합니다.다음을 지정하는 체인 을 생성합니다.
MongoDB Vector Search를 리트리버로 사용하여 컨텍스트로 사용할 문서를 검색 .
사용자가 정의한 프롬프트 템플릿입니다.
OpenAI의
gpt-4o채팅 모델은 컨텍스트 인식 응답을 생성합니다.
샘플 쿼리로 체인을 호출합니다.
LLM 의 응답과 컨텍스트로 사용되는 문서를 반환합니다. 생성된 응답은 다를 수 있습니다.
# Instantiate MongoDB Vector Search as a retriever retriever = vector_store.as_retriever( search_type = "similarity", search_kwargs = { "k": 10, "score_threshold": 0.75, "pre_filter": { "page_label": { "$eq": 2 } } } ) # Define a prompt template template = """ Use the following pieces of context to answer the question at the end. {context} Question: {question} """ prompt = PromptTemplate.from_template(template) model = ChatOpenAI(model="gpt-4o") # Construct a chain to answer questions on your data chain = ( { "context": retriever, "question": RunnablePassthrough()} | prompt | model | StrOutputParser() ) # Prompt the chain question = "What was MongoDB's latest acquisition?" answer = rag_chain.invoke(question) print("Question: " + question) print("Answer: " + answer) # Return source documents documents = retriever.invoke(question) print("\nSource documents:") pprint.pprint(documents)
Question: What was MongoDB's latest acquisition? Answer: MongoDB's latest acquisition was Voyage AI, a pioneer in state-of-the-art embedding and reranking models. Source documents: [Document(id='67f0259b8bb2babc06924351', metadata={'_id': '67f0259b8bb2babc06924351', ... '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='67f0259b8bb2babc06924355', metadata={'_id': '67f0259b8bb2babc06924355', ... '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='67f0259b8bb2babc06924354', metadata={'_id': '67f0259b8bb2babc06924354', ... 'page_label': '2'}, page_content='data.\nMongoDB completed the redemption of 2026 Convertible Notes, eliminating all debt from the balance sheet. Additionally, in'), Document(id='67f0259b8bb2babc06924358', metadata={'_id': '67f0259b8bb2babc06924358', ... 'page_label': '2'}, page_content='Lombard Odier, a Swiss private bank, partnered with MongoDB to migrate and modernize its legacy banking technology'), Document(id='67f0259b8bb2babc06924352', metadata={'_id': '67f0259b8bb2babc06924352', ... 'page_label': '2'}, page_content="AI applications. Integrating Voyage AI's technology with MongoDB will enable organizations to easily build trustworthy,"), Document(id='67f0259b8bb2babc0692435a', metadata={'_id': '67f0259b8bb2babc0692435a', ... 'page_label': '2'}, page_content='applications from a legacy relational database to MongoDB 20 times faster than previous migrations.\nFirst Quarter and Full Year Fiscal 2026 Guidance'), Document(id='67f0259b8bb2babc06924356', metadata={'_id': '67f0259b8bb2babc06924356', ... 'page_label': '2'}, page_content='For the third consecutive year, MongoDB was named a Leader in the 2024 Gartner® Magic Quadrant™ for Cloud'), Document(id='67f0259b8bb2babc0692434d', metadata={'_id': '67f0259b8bb2babc0692434d', ... 'page_label': '2'}, page_content='compared to $121.5 million of cash from operations in the year-ago period. MongoDB used $29.6 million of cash in capital'), Document(id='67f0259b8bb2babc0692434c', metadata={'_id': '67f0259b8bb2babc0692434c', ... 'page_label': '2'}, page_content='Cash Flow: During the year ended January 31, 2025, MongoDB generated $150.2 million of cash from operations,'), Document(id='67f0259b8bb2babc06924364', metadata={'_id': '67f0259b8bb2babc06924364', ... 'page_label': '2'}, page_content='MongoDB will host a conference call today, March 5, 2025, at 5:00 p.m. (Eastern Time) to discuss its financial results and business outlook. A live')]
보면서 배우기
이 동영상 튜토리얼을 따라 LangChain과 MongoDB를 사용한 시맨틱 검색 및 RAG에 대해 더 학습해보세요.
소요 시간: 8분