문서 메뉴
문서 홈
/
MongoDB 아틀라스
/ /

LangChain 통합 시작하기

이 페이지의 내용

  • 배경
  • 전제 조건
  • 환경 설정
  • Atlas를 Vector Store로 사용
  • Atlas Vector Search 인덱스 만들기
  • Vector Search 쿼리 실행
  • 데이터에 대한 질문에 답변
  • 다음 단계

참고

이 튜토리얼에서는 LangChain의 Python 라이브러리 를 사용합니다. . JavaScript 라이브러리를 사용하는 튜토리얼은 LangChain JS/TS 통합 시작하기를 참조하세요.

Atlas Vector Search를 LangChain 과 통합할 수 있습니다.LLM 애플리케이션을 빌드하고 검색 강화 생성(RAG)을 구현합니다. 이 튜토리얼에서는 LangChain과 함께 Atlas Vector Search 를 사용하여 데이터에 대해 시맨틱 Atlas Search를 수행하고 RAG 구현을 구축하는 방법을 보여 줍니다. 구체적으로 다음 조치를 수행합니다.

  1. 환경을 설정합니다.

  2. Atlas에 사용자 지정 데이터를 저장합니다.

  3. 데이터에 Atlas Vector Search 검색 인덱스를 만듭니다.

  4. 다음 벡터 검색 쿼리를 실행합니다.

    • 시맨틱 검색.

    • 점수가 있는 시맨틱 검색.

    • 메타데이터 사전 필터링을 통한 시맨틱 검색.

  5. Atlas Vector Search를 사용하여 RAG 를 구현하여 데이터에 대한 질문에 답변하세요.

LangChain은 '체인'을 사용하여 LLM 애플리케이션 생성을 간소화하는 오픈 소스 프레임워크입니다. 체인은 RAG 를 포함한 다양한 AI 사용 사례에 결합할 수 있는 LangChain 관련 구성 요소입니다.

Atlas Vector Search를 LangChain과 통합하면 Atlas를 벡터 데이터베이스로 사용하고 Atlas Vector Search를 사용하여 데이터에서 의미적으로 유사한 문서를 검색하여 RAG 를 구현할 수 있습니다. RAG 에 대해 자세히 알아보려면 Atlas Vector Search를 사용한 검색-증강 생성(RAG)을 참조하세요.

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

  • MongoDB 버전 6 을(를) 실행하는 Atlas 클러스터입니다.0.11, 7.0.2 이상( RC 포함). 사용자의 IP 주소 가 Atlas 프로젝트의 액세스 목록에 포함되어 있는지 확인하세요.

  • OpenAI API 키입니다. API 요청에 사용할 수 있는 크레딧이 있는 유료 OpenAI 계정이 있어야 합니다.

  • Colab과같은 대화형 Python 노트북을 실행할 수 있는 환경입니다.

먼저 이 튜토리얼을 진행하려면 환경을 설정해야 합니다. 확장자가 .ipynb 인 파일을 저장하여 대화형 Python 노트북을 만든 후 노트북에서 다음 코드 스니펫을 실행합니다.

1

다음 명령을 실행합니다:

%pip install --upgrade --quiet langchain langchain-community langchain-core langchain-mongodb langchain-openai pymongo pypdf

그런 다음, 다음 코드를 실행하여 필요한 패키지를 가져옵니다.

import getpass, 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_openai import ChatOpenAI, OpenAIEmbeddings
from langchain.prompts import PromptTemplate
from langchain.text_splitter import RecursiveCharacterTextSplitter
from pymongo import MongoClient
from pymongo.operations import SearchIndexModel
2

다음 코드를 실행하고 메시지가 표시되면 다음을 제공합니다.

os.environ["OPENAI_API_KEY"] = getpass.getpass("OpenAI API Key:")
ATLAS_CONNECTION_STRING = getpass.getpass("MongoDB Atlas SRV Connection String:")

참고

연결 문자열은 다음 형식을 사용해야 합니다.

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

그런 다음 사용자 지정 데이터를 Atlas에 로드하고 Atlas를 벡터 저장소 라고도 하는 벡터 데이터베이스로 인스턴스화합니다. . 다음 코드 스니펫을 복사하여 노트북에 붙여넣습니다.

1

다음 코드를 실행하여 Atlas cluster에 대한 연결을 설정하세요. 다음을 지정합니다:

  • langchain_db.test 를 데이터를 로드할 collection의 이름으로 사용합니다.

  • vector_index 를 데이터 쿼리에 사용할 Atlas Vector Search 검색 인덱스의 이름으로 사용합니다.

# Connect to your Atlas cluster
client = MongoClient(ATLAS_CONNECTION_STRING)
# Define collection and index name
db_name = "langchain_db"
collection_name = "test"
atlas_collection = client[db_name][collection_name]
vector_search_index = "vector_index"
2

이 튜토리얼에서는 공개적으로 액세스할 수 있는 MongoDB Atlas 모범 사례 라는 제목의 PDF 문서를 사용합니다. 벡터 저장소의 데이터 소스로 사용합니다. 이 문서에서는 Atlas 배포서버를 관리하기 위한 다양한 권장 사항과 핵심 개념을 설명합니다.

샘플 데이터를 로드하려면 다음 코드 스니펫을 실행합니다. 다음을 수행합니다.

  • 지정된 URL에서 PDF를 검색하고 원시 텍스트 데이터를 로드합니다.

  • 텍스트 분할기 를 사용합니다. 데이터를 작은 문서로 분할합니다.

  • 각 문서의 문자 수와 두 개의 연속 문서 간에 겹치는 문자 수를 결정하는 청크 매개변수를 지정합니다.

# Load the PDF
loader = PyPDFLoader("https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP")
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(page_content='Mong oDB Atlas Best P racticesJanuary 20 19A MongoD B White P aper', metadata={'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 0})
3

다음 코드를 실행하여 샘플 문서에서 vector_store 라는 벡터 저장소를 만듭니다. 이 스니펫은 MongoDBAtlasVectorSearch.from_documents 메서드를 사용하고 다음 매개 변수를 지정합니다:

  • 벡터 데이터베이스에 저장할 샘플 문서입니다.

  • 텍스트를 embedding 필드의 벡터 임베딩으로 변환하는 데 사용되는 모델인 OpenAI의 임베딩 모델입니다.

  • langchain_db.test 문서를 저장할 Atlas collection으로 지정합니다.

  • vector_index 를 벡터 저장소를 쿼리하는 데 사용할 인덱스로 사용합니다.

# Create the vector store
vector_store = MongoDBAtlasVectorSearch.from_documents(
documents = docs,
embedding = OpenAIEmbeddings(disallowed_special=()),
collection = atlas_collection,
index_name = vector_search_index
)

샘플 코드를 실행한langchain_db.test cluster의 collection으로 이동 하여 Atlas UI에서 벡터 임베딩을 볼 수 있습니다.

참고

Atlas Vector Search 검색 인덱스를 만들려면 Atlas 프로젝트에 대한 Project Data Access Admin 이상의 액세스 권한이 있어야 합니다.

벡터 저장소에서 벡터 검색 쿼리를 활성화하려면 langchain_db.test 컬렉션에 Atlas Vector Search 인덱스를 생성하세요.

노트북에서 다음 코드를 실행하여 다음 필드의 인덱싱을 지정하는 vectorSearch 유형의 인덱스를 만듭니다.

  • embedding 필드를 벡터 유형으로 지정합니다. embedding 필드에는 OpenAI의 text-embedding-ada-002 임베딩 모델을 사용하여 생성된 임베딩이 포함되어 있습니다. 인덱스 정의는 1536 벡터 차원을 지정하고 cosine 를 사용하여 유사성을 측정합니다.

  • page 필드를 PDF의 페이지 번호를 기준으로 데이터를 사전 필터링하는 필터 유형으로 지정합니다.

1# Create your index model, then create the search index
2search_index_model = SearchIndexModel(
3 definition={
4 "fields": [
5 {
6 "type": "vector",
7 "path": "embedding",
8 "numDimensions": 1536,
9 "similarity": "cosine"
10 },
11 {
12 "type": "filter",
13 "path": "page"
14 }
15 ]
16 },
17 name="vector_index",
18 type="vectorSearch"
19)
20
21atlas_collection.create_search_index(model=search_index_model)

인덱스를 빌드하는 데 약 1분 정도 걸립니다. 빌드되는 동안 인덱스는 초기 동기화 상태입니다. 빌드가 완료되면 컬렉션의 데이터 쿼리를 시작할 수 있습니다.

Atlas가 인덱스를 빌드하면 데이터에 대해 벡터 검색 쿼리를 실행합니다. 다음 예제는 벡터화된 데이터에 대해 실행할 수 있는 다양한 쿼리를 보여줍니다.

다음 쿼리는 similarity_search 메서드를 사용하여 문자열 MongoDB Atlas security 에 대한 기본 시맨틱 검색을 수행합니다. 관련성별로 순위가 지정된 문서 목록을 반환합니다.

query = "MongoDB Atlas security"
results = vector_store.similarity_search(query)
pprint.pprint(results)
[Document(page_content='To ensure a secure system right out of the b ox,\nauthentication and I P Address whitelisting are\nautomatically enabled.\nReview the security section of the MongoD B Atlas', metadata={'_id': ObjectId('65c2e8f480f26794dedad8d5'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
Document(page_content='MongoD B Atlas team are also monitoring the underlying\ninfrastructure, ensuring that it is always in a healthy state.\nApplication L ogs And Database L ogs', metadata={'_id': ObjectId('65c2e8f480f26794dedad8a0'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 15}),
Document(page_content='MongoD B.\nMongoD B Atlas incorporates best practices to help keep\nmanaged databases healthy and optimized. T hey ensure\noperational continuity by converting comple x manual tasks', metadata={'_id': ObjectId('65c2e8f380f26794dedad883'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 13}),
Document(page_content='Atlas provides encryption of data at rest with encrypted\nstorage volumes.\nOptionally , Atlas users can configure an additional layer of\nencryption on their data at rest using the MongoD B', metadata={'_id': ObjectId('65c2e8f480f26794dedad8e3'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 18})]

다음 쿼리는 similarity_search_with_score 메서드를 사용하여 문자열 MongoDB Atlas security 에 대한 시맨틱 검색을 수행하고 k 매개 변수를 지정하여 반환할 문서 수를 3 로 제한합니다.

참고

이 예제에서 k 매개변수는 동일한 이름의 knnBeta 연산자 옵션이 아닌 similarity_search_with_score 메서드 옵션을 나타냅니다.

가장 관련성이 높은 문서 3개와 0 ~ 1 사이의 관련성 점수 를 반환합니다.

query = "MongoDB Atlas security"
results = vector_store.similarity_search_with_score(
query = query, k = 3
)
pprint.pprint(results)
[(Document(page_content='To ensure a secure system right out of the b ox,\nauthentication and I P Address whitelisting are\nautomatically enabled.\nReview the security section of the MongoD B Atlas', metadata={'_id': ObjectId('65c2e8f480f26794dedad8d5'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
0.935082197189331),
(Document(page_content='MongoD B Atlas team are also monitoring the underlying\ninfrastructure, ensuring that it is always in a healthy state.\nApplication L ogs And Database L ogs', metadata={'_id': ObjectId('65c2e8f480f26794dedad8a0'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 15}),
0.9335962533950806),
(Document(page_content='MongoD B.\nMongoD B Atlas incorporates best practices to help keep\nmanaged databases healthy and optimized. T hey ensure\noperational continuity by converting comple x manual tasks', metadata={'_id': ObjectId('65c2e8f380f26794dedad883'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 13}),
0.9317940473556519)]

인덱싱된 필드를 부울, 숫자 또는 문자열 값과 비교하는 MQL 일치 표현식을 사용하여 데이터를 사전 필터링할 수 있습니다. 필터링하려는 메타데이터 필드를 filter 유형으로 인덱싱해야 합니다. 자세한 내용 은 벡터 검색을 위한 필드 인덱싱 방법을 참조하세요.

참고

이 튜토리얼 의 인덱스를 생성 할 때 page 필드를 필터로 지정했습니다.

다음 쿼리는 similarity_search_with_score 메서드를 사용하여 문자열 MongoDB Atlas security 에 대한 시맨틱 검색을 수행합니다. 또한 다음을 지정합니다.

  • 반환할 문서 수를 3)로 제한하는 k 매개 변수입니다.

  • $eq 연산자를 사용하여 17 페이지에 나타나는 문서만 일치시키는 page 필드에 대한 사전 필터입니다.

17 페이지에서 가장 관련성이 높은 문서 3개와 관련성 점수 0 ~ 1 를 반환합니다.

query = "MongoDB Atlas security"
results = vector_store.similarity_search_with_score(
query = query,
k = 3,
pre_filter = { "page": { "$eq": 17 } }
)
pprint.pprint(results)
[(Document(page_content='To ensure a secure system right out of the b ox,\nauthentication and I P Address whitelisting are\nautomatically enabled.\nReview the security section of the MongoD B Atlas', metadata={'_id': ObjectId('65c2e8f480f26794dedad8d5'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
0.935082197189331),
(Document(page_content='Security\nAs with all software, MongoD B administrators must\nconsider security and risk e xposure for a MongoD B\ndeployment. T here are no magic solutions for risk', metadata={'_id': ObjectId('65c2e8f480f26794dedad8d0'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
0.920635461807251),
(Document(page_content='number of diff erent methods for managing risk and\nreducing risk e xposure.\nMongoD B Atlas f eatures e xtensive capabilities to def end,\ndetect, and control access to MongoD B, off ering among', metadata={'_id': ObjectId('65c2e8f480f26794dedad8d2'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
0.9206267595291138)]

다음도 참조하세요.

이 섹션에서는 Atlas Vector Search 및 LangChain을 사용하여 애플리케이션에서 RAG를 구현하는 방법을 보여 줍니다. 이제 Atlas Vector Search를 사용하여 의미상 유사한 문서를 검색했으니, 다음 코드 예시를 실행하여 LLM이 해당 문서를 기반으로 질문에 답하도록 요청하세요.

이 예제는 다음을 수행합니다:

  • Atlas Vector Search를 리트리버 k 10 로 인스턴스화합니다. 가장 관련성이 높은 문서만 검색하는 선택적 매개 변수를 포함하여 유사한 문서를 쿼리합니다.

  • LangChain 프롬프트 템플릿 을 정의합니다. 을(를) 사용하여 LLM 이 이러한 문서를 쿼리의 컨텍스트로 사용하도록 지시합니다. LangChain은 이러한 문서를 {context} 입력 변수에 전달하고 쿼리를 {question} 변수에 전달합니다.

  • 체인 을 생성합니다. 다음을 지정합니다.

    • LLM에서 컨텍스트로 사용하는 문서를 검색하기 위한 검색기 역할을 하는 Atlas Vector Search입니다.

    • 사용자가 구성한 프롬프트 템플릿입니다.

    • 상황 인식 응답을 생성하는 데 사용되는 LLM인 OpenAI의 채팅 모델입니다.

  • Atlas 보안 권장 사항에 대한 샘플 쿼리를 체인에 표시합니다.

  • LLM 의 응답과 컨텍스트로 사용되는 문서를 반환합니다. 생성된 응답은 다를 수 있습니다.

# Instantiate Atlas 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.
If you don't know the answer, just say that you don't know, don't try to make up an answer.
{context}
Question: {question}
"""
custom_rag_prompt = PromptTemplate.from_template(template)
llm = ChatOpenAI()
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
# Construct a chain to answer questions on your data
rag_chain = (
{ "context": retriever | format_docs, "question": RunnablePassthrough()}
| custom_rag_prompt
| llm
| StrOutputParser()
)
# Prompt the chain
question = "How can I secure my MongoDB Atlas cluster?"
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: How can I secure my MongoDB Atlas cluster?
Answer: To secure your MongoDB Atlas cluster, you can enable
authentication and IP address whitelisting, review the security section
in the MongoDB Atlas dashboard, encrypt data at rest with encrypted storage
volumes, optionally configure an additional layer of encryption on your
data, set up global clusters on Amazon Web Services, Microsoft Azure,
and Google Cloud Platform, and ensure operational continuity by choosing
appropriate instance size, storage size, and storage speed options.
Additionally, consider setting up a larger number of replica nodes for
increased protection against database downtime.
Source documents:
[Document(page_content='To ensure a secure system right out of the b ox,\nauthentication and I P Address whitelisting are\nautomatically enabled.\nReview the security section of the MongoD B Atlas', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe0436'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
Document(page_content='MongoD B Atlas team are also monitoring the underlying\ninfrastructure, ensuring that it is always in a healthy state.\nApplication L ogs And Database L ogs', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe0401'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 15}),
Document(page_content='All the user needs to do in order for MongoD B Atlas to\nautomatically deploy the cluster is to select a handful of\noptions:\n•Instance size\n•Storage size (optional)\n•Storage speed (optional)', metadata={'_id': ObjectId('65fb4f046979cf7cbbfe03ef'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 14}),
Document(page_content='MongoD B.\nMongoD B Atlas incorporates best practices to help keep\nmanaged databases healthy and optimized. T hey ensure\noperational continuity by converting comple x manual tasks', metadata={'_id': ObjectId('65fb4f046979cf7cbbfe03e4'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 13}),
Document(page_content='You can set up global clusters — available on Amazon W eb\nServices, Microsoft Azure, and Google Cloud Platform —\nwith just a f ew clic ks in the MongoD B Atlas U I. MongoD B', metadata={'_id': ObjectId('65fb4f046979cf7cbbfe03bb'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 12}),
Document(page_content='Table of Contents\n1 Introduction\n2 Preparing for a MongoD B Deployment\n9 Scaling a MongoD B Atlas Cluster\n11 Continuous A vailability & Data Consistency\n12 Managing MongoD B\n16 Security', metadata={'_id': ObjectId('65fb4f026979cf7cbbfe02d6'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 1}),
Document(page_content='Atlas provides encryption of data at rest with encrypted\nstorage volumes.\nOptionally , Atlas users can configure an additional layer of\nencryption on their data at rest using the MongoD B', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe0444'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 18}),
Document(page_content='Disaster Recovery\nCreated by the engineers who develop the database,\nMongoD B Atlas is the simplest way to run MongoD B,\nmaking it easy to deploy , monitor , backup, and scale\nMongoD B.', metadata={'_id': ObjectId('65fb4f046979cf7cbbfe03e3'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 13}),
Document(page_content='Security\nAs with all software, MongoD B administrators must\nconsider security and risk e xposure for a MongoD B\ndeployment. T here are no magic solutions for risk', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe0431'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
Document(page_content='A larger number of replica nodes provides increased\nprotection against database downtime in case of multiple\nmachine failures.\nMongoD B Atlas replica sets have a minimum of 3 nodes', metadata={'_id': ObjectId('65fb4f046979cf7cbbfe03ca'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 12})]

이 예제는 다음을 수행합니다:

  • Atlas Vector Search를 리트리버 로 인스턴스화합니다. 다음과 같은 선택적 매개변수를 포함하여 유사한 문서를 쿼리할 수 있습니다.

    • k 가장 관련성이 높은 10 문서만 검색합니다.

    • score_threshold 관련성 점수가 0.75 이상인 문서만 사용합니다.

      참고

      이 매개변수는 Langchain이 결과를 정규화하는 데 사용하는 관련성 점수를 나타내며, Atlas Search 쿼리에 사용되는 관련성 점수 가 아닙니다. RAG 구현에서 Atlas Search 점수를 사용하려면 similarity_search_with_score 메서드를 사용하고 Atlas Search 점수로 필터링하는 사용자 지정 리트리버를 정의하세요.

    • pre_filter 17 페이지에 나타나는 문서에 대해서만 page 필드에서 필터링합니다.

  • LangChain 프롬프트 템플릿 을 정의합니다. 을(를) 사용하여 LLM 이 이러한 문서를 쿼리의 컨텍스트로 사용하도록 지시합니다. LangChain은 이러한 문서를 {context} 입력 변수에 전달하고 쿼리를 {question} 변수에 전달합니다.

  • 체인 을 생성합니다. 다음을 지정합니다.

    • LLM에서 컨텍스트로 사용하는 문서를 검색하기 위한 검색기 역할을 하는 Atlas Vector Search입니다.

    • 사용자가 구성한 프롬프트 템플릿입니다.

    • 상황 인식 응답을 생성하는 데 사용되는 LLM인 OpenAI의 채팅 모델입니다.

  • Atlas 보안 권장 사항에 대한 샘플 쿼리를 체인에 표시합니다.

  • LLM 의 응답과 컨텍스트로 사용되는 문서를 반환합니다. 생성된 응답은 다를 수 있습니다.

# Instantiate Atlas Vector Search as a retriever
retriever = vector_store.as_retriever(
search_type = "similarity_score_threshold",
search_kwargs = {
"k": 10,
"score_threshold": 0.75,
"pre_filter": { "page": { "$eq": 17 } }
}
)
# Define a prompt template
template = """
Use the following pieces of context to answer the question at the end.
If you don't know the answer, just say that you don't know, don't try to make up an answer.
{context}
Question: {question}
"""
custom_rag_prompt = PromptTemplate.from_template(template)
llm = ChatOpenAI()
def format_docs(docs):
return "\n\n".join(doc.page_content for doc in docs)
# Construct a chain to answer questions on your data
rag_chain = (
{ "context": retriever | format_docs, "question": RunnablePassthrough()}
| custom_rag_prompt
| llm
| StrOutputParser()
)
# Prompt the chain
question = "How can I secure my MongoDB Atlas cluster?"
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: How can I secure my MongoDB Atlas cluster?
Answer: To secure your MongoDB Atlas cluster, you can enable
authentication and IP Address whitelisting, define permissions
for users and applications, use VPC Peering for secure connectivity,
implement a Defense in Depth approach for securing deployments, and
consider using LDAP integration for centralized authorization
management. It is important to regularly review the security section
of MongoDB Atlas and continuously monitor and update security measures
to mitigate risk and maintain a secure deployment.
Source documents:
[Document(page_content='To ensure a secure system right out of the b ox,\nauthentication and I P Address whitelisting are\nautomatically enabled.\nReview the security section of the MongoD B Atlas', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe0436'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
Document(page_content='Security\nAs with all software, MongoD B administrators must\nconsider security and risk e xposure for a MongoD B\ndeployment. T here are no magic solutions for risk', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe0431'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
Document(page_content='number of diff erent methods for managing risk and\nreducing risk e xposure.\nMongoD B Atlas f eatures e xtensive capabilities to def end,\ndetect, and control access to MongoD B, off ering among', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe0433'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
Document(page_content='permissions for a user or application, and what data it can\naccess when querying MongoD B. MongoD B Atlas provides\nthe ability to provision users with roles specific to a', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe043b'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
Document(page_content='connectivity without using public I P addresses, and without\nneeding to whitelist every client in your MongoD B Atlas\ngroup.\nAuthorization\nMongoD B Atlas allows administrators to define', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe043a'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
Document(page_content='mitigation, and maintaining a secure MongoD B deployment\nis an ongoing process.\nDefense in Depth\nA Def ense in Depth approac h is recommended for\nsecuring MongoD B deployments, and it addresses a', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe0432'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
Document(page_content='optimization.\nIn addition, MongoD B Atlas provides pac kaged integration\nwith the New Relic platform. K ey metrics from MongoD B\nAtlas are accessible to the AP M for visualization, enabling', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe042e'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
Document(page_content='their I P address (or a C IDR covering their I P address) has\nbeen added to the IP whitelist for your MongoD B Atlas\ngroup.\nVPC P eering\nVirtual P rivate Cloud (VPC) P eering allows users to create', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe0438'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
Document(page_content='dedicated A tlas clusters using credentials that are verified\nby a centralized L DAP server . Authorization management is\nsimplified by allowing control at the L DAP group level.', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe043d'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17}),
Document(page_content='database, making it possible to realize a separation of\nduties between diff erent entities accessing and managing\nthe data.\nAtlas supports L DAP integration, allowing users to login to', metadata={'_id': ObjectId('65fb4f056979cf7cbbfe043c'), 'source': 'https://query.prod.cms.rt.microsoft.com/cms/api/am/binary/RE4HkJP', 'page': 17})]

Atlas Vector Search의 추가 RAG 사용 사례에 대해 알아보려면 LangChain에서 애플리케이션 빌드에 도움이 되도록 제공하는 다음 템플릿을 참조하세요.

MongoDB는 다음과 같은 개발자 리소스도 제공합니다.

다음도 참조하세요.

돌아가기

AI 통합

다음

LangChain JS/TS