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

Atlas Vector Search를 사용하여 로컬 RAG 구현 구축

이 페이지의 내용

  • 배경
  • 전제 조건
  • 로컬 Atlas 배포 만들기
  • 환경 설정
  • 로컬 모델로 임베딩 생성
  • Atlas Vector Search 인덱스 만들기
  • 로컬 LLM으로 질문에 답변하기

이 튜토리얼에서는 API 키 또는 크레딧 없이 로컬에서 검색 보강 생성(RAG)을 구현하는 방법을 보여 줍니다. RAG 에 대해 자세히 알아보려면 Atlas Vector Search를 사용한 RAG(검색 보강 생성)를 참조하세요.

구체적으로 다음 조치를 수행합니다.

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

  2. 환경을 설정합니다.

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

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

  5. 로컬 LLM 을 배포하여 데이터에 대한 질문에 답변하세요.

이 튜토리얼을 완료하려면 Atlas CLI 를 사용하여 로컬 Atlas 배포서버를 생성하거나 클라우드에 클러스터를 배포하세요 . Atlas CLI는 MongoDB Atlas의 명령줄 인터페이스이며, Atlas CLI를 사용하여 터미널에서 Atlas와 상호 작용하여 로컬 Atlas 배포 생성을 포함한 다양한 작업을 수행할 수 있습니다. 자세한 내용은 Atlas CLI에서 로컬 및 클라우드 배포 관리를 참조하세요.

참고

로컬 Atlas 배포는 테스트용으로만 제공됩니다. 프로덕션 환경 의 경우 클러스터를 배포합니다.

이 튜토리얼에서는 다음과 같은 오픈 소스 모델도 사용합니다.

LLM을 로컬에 다운로드하고 배포하는 방법에는 여러 가지가 있습니다. 이 튜토리얼에서는 7 GPT4를 사용하여 Mistral B 모델을 다운로드합니다.로컬 LLM 개발을 위한 오픈 소스 에코시스템입니다.

이 튜토리얼에서는 LangChain 도 사용합니다. 인 인기 오픈 소스 LLM 프레임워크를 사용하여 이러한 모델에 연결하고 Atlas Vector Search와 통합할 수 있습니다. 다른 모델이나 다른 프레임워크를 선호하는 경우 모델 이름과 LangChain 관련 구성 요소를 원하는 설정에 해당하는 것으로 대체하여 이 튜토리얼을 조정할 수 있습니다.

RAG 애플리케이션에서 LangChain을 활용하는 방법에 대해 자세히 알아보려면 LangChain 통합 시작하기를 참조하세요. Atlas Vector Search와 함께 사용할 수 있는 다른 프레임워크에 대해 자세히 알아보려면 벡터 검색과 AI 기술 통합을 참조하세요.

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

  • Atlas CLI 가 설치되어 실행 중입니다. v1.14.3 이상.

  • 로컬에서 실행할 수 있는 대화형 Python 노트북입니다.VS Code 에서 대화형 Python 노트북을 실행할 수 있습니다. . 환경에서 Python v 를 실행하는지3 10 확인합니다. 이상.

    참고

    Colab 과 같은 호스팅 서비스를 사용하는 경우 이 튜토리얼을 실행하기에 충분한 RAM이 있는지 확인합니다. 그렇지 않으면 성능 문제가 발생할 수 있습니다.

이 섹션에서는 벡터 데이터베이스로 사용할 로컬 Atlas 배포서버를 생성합니다. MongoDB 버전 6 를 실행하는 Atlas 클러스터가 있는 경우.0.11, 7.0.2 이상이며 샘플 데이터 가 로드되어 있는 경우 이 단계를 건너뛸 수 있습니다.

로컬 배포를 만들려면 다음을 수행합니다.

1

터미널에서 atlas auth login 를 실행하여 Atlas 로그인 자격 증명으로 인증합니다. 자세한 내용 은 Atlas CLI에서 연결을 참조하세요.

참고

기존 Atlas 계정이 없는 경우 atlas setup 를 실행하거나 새 계정을 만드세요.

2

atlas deployments setup 를 실행하고 메시지에 따라 로컬 배포를 만듭니다.

자세한 지침 은 로컬 Atlas 배포 생성을 참조하세요.

3
  1. 터미널에서 다음 명령을 실행하여 샘플 데이터를 다운로드합니다.

    curl https://atlas-education.s3.amazonaws.com/sampledata.archive -o sampledata.archive
  2. 다음 명령을 실행하여 데이터를 배포에 로드하고 <port-number> 을 배포를 호스팅하는 포트로 바꿉니다.

    mongorestore --archive=sampledata.archive --port=<port-number>

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

1

다음 명령을 실행합니다:

pip install --quiet langchain langchain_community langchain_huggingface langchain-mongodb pymongo sentence-transformers gpt4all
2

로컬 Atlas 배포서버를 사용하는 경우 노트북에서 다음 코드를 실행하여 <port-number> 을 로컬 배포서버용 포트로 바꿉니다.

ATLAS_CONNECTION_STRING = ("mongodb://localhost:<port-number>/?directConnection=true")

Atlas cluster를 사용하는 경우 노트북에서 다음 코드를 실행하여 <connection-string> 을(를) Atlas cluster의 SRV 연결 문자열로 바꿉니다.

ATLAS_CONNECTION_STRING = ("<connection-string>")

참고

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

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

이 섹션에서는 로컬에서 임베딩 모델을 로드하고 listingsAndReviews 라는 단일 컬렉션이 포함된 sample_airbnb 데이터베이스의 데이터를 사용하여 벡터 임베딩을 생성합니다. 다음 코드 스니펫은 다음 조치를 수행합니다.

  • 로컬 Atlas 배포서버 또는 Atlas cluster 및 sample_airbnb.listingsAndReviews 컬렉션에 대한 연결을 설정합니다.

  • LangChain의 HuggingFaceEmbeddings 라이브러리에서 bge-large-en-v1.5 임베딩 모델을 로드합니다.

  • summary 필드가 있고 embeddings 필드가 없는 문서만 포함하는 필터를 만듭니다.

  • 필터를 충족하는 컬렉션의 각 문서에 대해 다음을 수행합니다.

    • bge-large-en-v1.5 임베딩 모델을 사용하여 문서의 summary 필드에서 임베딩을 생성합니다.

    • 임베딩이 포함된 embeddings 라는 새 필드를 만들어 문서를 업데이트합니다.

노트북에서 다음 코드를 실행합니다.

from langchain_huggingface import HuggingFaceEmbeddings
from pymongo import MongoClient
# Connect to your local Atlas deployment or Atlas Cluster
client = MongoClient(ATLAS_CONNECTION_STRING)
# Select the sample_airbnb.listingsAndReviews collection
collection = client["sample_airbnb"]["listingsAndReviews"]
# Specify local embedding model (https://huggingface.co/sentence-transformers/baai/bge-large-en-v1.5)
model = HuggingFaceEmbeddings(model_name="baai/bge-large-en-v1.5")
# Filters for only documents with a summary field and without an embeddings field
filter = { '$and': [ { 'summary': { '$exists': True, '$ne': None } }, { 'embeddings': { '$exists': False } } ] }
count = 0
totalCount = collection.count_documents(filter)
# Creates embeddings and updates the documents in the collection
for document in collection.find(filter):
text = document['summary']
embedding = model.embed_query(text)
collection.update_one({ '_id': document['_id'] }, { "$set": { 'embeddings': embedding } }, upsert = True)
count+=1
print("Documents updated: {}/{} ".format(count, totalCount))

이 코드는 실행하는 데 시간이 걸립니다. 완료되면 배포의 연결 문자열을 사용하여 mongosh 또는 애플리케이션에서 로컬 배포에 연결할 수 있습니다. 그런 다음 벡터 임베딩을 보려면 sample_airbnb.listingsAndReviews 컬렉션에서 읽기 작업 을 실행합니다.

이 코드는 실행하는 데 시간이 걸립니다. 완료되면 클러스터의 sample_airbnb.listingsAndReviews 컬렉션으로 이동하고 문서의 필드를 확장하여 Atlas UI에서 벡터 임베딩을 볼 수 있습니다.

sample_airbnb.listingsAndReviews 컬렉션에서 벡터 검색을 활성화하려면 Atlas Vector Search 인덱스를 생성하세요.

로컬 Atlas 배포를 사용하는 경우 다음 단계를 완료하세요.

1

vector-index.json 이라는 파일을 만들고 다음 인덱스 정의를 파일에 붙여넣습니다.

이 인덱스 정의는 sample_airbnb.listingsAndReviews 컬렉션에 대한 vectorSearch 유형의 인덱스에서 embeddings 필드를 인덱싱하도록 지정합니다. 이 필드에는 bge-large-en-v1.5 임베딩 모델을 사용하여 생성된 임베딩이 포함됩니다. 인덱스 정의는 1024 벡터 차원을 지정하고 cosine 을 사용하여 유사성을 측정합니다.

{
"database": "sample_airbnb",
"collectionName": "listingsAndReviews",
"type": "vectorSearch",
"name": "vector_index",
"fields": [
{
"type": "vector",
"path": "embeddings",
"numDimensions": 1024,
"similarity": "cosine"
}
]
}
2
  1. 파일을 저장한 후 터미널에서 다음 명령을 실행하여 <path-to-file> 을(를) 생성한 vector-index.json 파일의 경로로 바꿉니다.

    atlas deployments search indexes create --file <path-to-file>

참고

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

Atlas 클러스터를 사용하는 경우 다음 단계를 완료하세요.

1
  1. 아직 표시되지 않은 경우 다음 목록에서 원하는 프로젝트가 포함된 조직을 선택합니다. 탐색 표시줄의 Organizations 메뉴.

  2. 아직 표시되지 않은 경우 탐색 표시줄의 Projects 메뉴에서 원하는 프로젝트를 선택합니다.

  3. Clusters 페이지가 아직 표시되지 않은 경우 사이드바에서 Database를 클릭합니다.

    클러스터 페이지가 표시됩니다.

2

사이드바, Data Explorer 또는 클러스터 세부 정보 페이지에서 Atlas Search 페이지로 이동할 수 있습니다.

  1. 사이드바에서 Services 제목 아래의 Atlas Search 을 클릭합니다.

  2. Select data source 드롭다운에서 클러스터를 선택하고 Go to Atlas Search 를 클릭합니다.

    Atlas Search 페이지가 표시됩니다.

  1. cluster의 Browse Collections 버튼을 클릭합니다.

  2. 데이터베이스를 확장하고 컬렉션을 선택합니다.

  3. 컬렉션의 Search Indexes 탭을 클릭합니다.

    Atlas Search 페이지가 표시됩니다.

  1. 클러스터의 이름을 클릭합니다.

  2. Atlas Search 탭을 클릭합니다.

    Atlas Search 페이지가 표시됩니다.

3
  1. Create Search Index를 클릭합니다.

  2. Atlas Vector Search 아래에서 JSON Editor 을 선택한 다음 Next 를 클릭합니다.

  3. Database and Collection 섹션에서 sample_airbnb 데이터베이스를 찾고 listingsAndReviews 컬렉션을 선택합니다.

  4. Index Name 필드에 vector_index를 입력합니다.

  5. 기본 정의를 다음 인덱스 정의로 바꾼 다음 Next를 클릭합니다.

    이 인덱스 정의는 sample_airbnb.listingsAndReviews 컬렉션에 대한 vectorSearch 유형의 인덱스에서 embeddings 필드를 인덱싱하도록 지정합니다. 이 필드에는 bge-large-en-v1.5 임베딩 모델을 사용하여 생성된 임베딩이 포함됩니다. 인덱스 정의는 1024 벡터 차원을 지정하고 cosine 을 사용하여 유사성을 측정합니다.

    {
    "fields":[
    {
    "type": "vector",
    "path": "embeddings",
    "numDimensions": 1024,
    "similarity": "cosine"
    }
    ]
    }
4

인덱스가 작성 중임을 보여주는 모달 창이 표시됩니다.

5

인덱스 작성에는 약 1분 정도가 소요됩니다. 작성하는 동안 Status 열은 Initial Sync를 읽습니다. 빌드가 완료되면 Status 열에 Active가 표시됩니다.

이 섹션에서는 Atlas Vector Search, LangChain 및 GPT4All을 사용하여 로컬에서 실행할 수 있는 샘플 RAG 구현을 보여 줍니다. 대화형 Python 노트북에서 다음 코드 스니펫을 실행합니다.

1

다음 코드는 Atlas Vector Search에 LangChain 통합을 사용하여 로컬 Atlas 배포 또는 Atlas cluster를 벡터 저장소라고도 하는 벡터 데이터베이스로 인스턴스화합니다.

from langchain_mongodb import MongoDBAtlasVectorSearch
# Instantiate vector store
vector_store = MongoDBAtlasVectorSearch(
collection=collection,
embedding=model,
index_name="vector_index",
embedding_key="embeddings",
text_key="summary")

다음 코드를 실행하여 샘플 시맨틱 검색 쿼리를 실행할 수도 있습니다.

import pprint
query = "beach house"
results = vector_store.similarity_search(query)
pprint.pprint(results)
[Document(page_content='Beach house with contemporary interior', metadata={'_id': '22123688', 'listing_url': 'https://www.airbnb.com/rooms/22123688', 'name': 'Bungan Beach House', ... }),
Document(page_content="Well done !!! you won't find a better location in Manly. The “Beach House” Apartments overlook Cabbage Tree Bay Aquatic Reserve between Manly and Shelly Beach, in one of Manly's premier locations Swim, dive, snorkel, surf, paddle board, coastal walkways, ocean pool, restaurants, all literally at your doorstep, or simply chill and unwind. Manly is amazing, I look forward to welcoming you", metadata={'_id': '18917022', 'listing_url': 'https://www.airbnb.com/rooms/18917022', 'name': 'Beach House Manly Apartment 4', ... }]}),
Document(page_content='Beautiful spacious two story beach house that has an amazing private gated grass area fronting Makaha beach. Perfect for family BBQ,s while watching the sun set into the ocean. Room for 10 people. Four night minimum stay required', metadata={'_id': '7099038', 'listing_url': 'https://www.airbnb.com/rooms/7099038', 'name': 'Ocean front Beach House in Makaha', ... }]}),
Document(page_content='Beautifully finished, newly renovated house with pool. The ultimate in indoor/outdoor living. Excellent finishes and a short stroll to the beach.', metadata={'_id': '19768051', 'listing_url': 'https://www.airbnb.com/rooms/19768051', 'name': 'Ultra Modern Pool House Maroubra', ... }]})]

다음도 참조하세요.

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

    다운로드
  2. 다음 코드를 노트북에 붙여넣어 LLM 을 구성합니다. 실행하기 전에 <path-to-model>LLM 을 로컬에 저장한 경로로 바꿉니다.

    from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
    from langchain_community.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)
3

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

  • Atlas Vector Search를 리트리버 로 인스턴스화합니다. 유사한 문서를 쿼리합니다.

  • 다음과 같은 LangChain 관련 구성 요소를 생성합니다.

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

    • 체인 이는 Atlas Vector Search를 리트리버, 사용자가 작성한 프롬프트 템플릿, 컨텍스트 인식 응답을 생성하도록 구성한 로컬 LLM 을 지정합니다.

  • 샘플 쿼리를 사용하여 LLM 에 프롬프트를 표시하고 응답을 반환합니다. 생성된 응답은 다를 수 있습니다.

from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
# Instantiate Atlas 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 = "Can you recommend me a few AirBnBs that are beach houses? Include a link to the listings."
answer = rag_chain.invoke(question)
# Return source documents
documents = retriever.invoke(question)
print("\nSource documents:")
pprint.pprint(documents)
Answer: Yes, I can recommend a few AirBnBs that are beach houses. Here are some links to their respective listings:
1. Oceanfront home on private, gated property - https://www.airbnb.com/rooms/15073739
2. Ground Floor, Oceanfront condo with complete remodeling - https://www.airbnb.com/rooms/14687148
3. 4 bedroom house in a great location with ocean views and free salt water pool - https://www.airbnb.ca/s?host_id=740644
Source documents:
[Document(page_content='Please look for Airbnb numb (Phone number hidden by Airbnb) to book with us. We do not take bookings through this one. It is live for others to read reviews. Oceanfront home on private, gated property. This unique property offers year-round swimming, private beach access and astounding ocean and mountain views. Traveling with a large group? Another 3 bedroom home is available for rent on this spacious property. Visit https://www.airbnb.com/rooms/15073739 or contact us for more information.', metadata={'_id': '14827972', 'listing_url': 'https://www.airbnb.com/rooms/14827972', 'name': 'Oceanfront Beach House Makai', ... }]}),
Document(page_content='This GROUND FLOOR, OCEANFRONT condo is just feet from ocean access. Completely remodeled kitchen, bathroom and living room, with queen size bed in the bedroom, and queen size convertible sofa bed in the living room. Relax with the 55" SMART blue ray DVD, cable, and free WiFi. With ceiling fans in each room and trade winds, this condo rarely need the air conditioning unit in the living room. Airbnb charges a reservation fee to all guests at the time of booking. Please see "Other Things to Note"', metadata={'_id': '18173803', 'listing_url': 'https://www.airbnb.com/rooms/18173803', 'name': 'Papakea A108', ... }]}),
Document(page_content='2 minutes to bus stop, beach - Cafes, Sun, Surf & Sand. 4 Secure rooms in older style, 4 bedroom house. Can squeeze in up to 15 guests (9 beds, 2 sofa beds in lounge & a single sofa mattress) BUT is best suited to 10-12 people Wireless Internet, under cover parking, unlimited street parking.', metadata={'_id': '2161945', 'listing_url': 'https://www.airbnb.com/rooms/2161945', 'name': 'Sand Sun Surf w Parking. City 9km', ... }]}),
Document(page_content='High Quality for a third of the price! Great Location & Ocean Views! FREE Salt Water Roof-Deck Pool, Activities & Rental Car Desk! Hassle-Free Self Check-In via Lockbox. Located In Famous Waikiki: Easily walk to Beaches, Shops/all Restaurants! Hawaiian Convention Center is only 2 Blocks Away! On-Site Garage $. See my similar listings if your dates are not available. https://www.airbnb.ca/s?host_id=740644', metadata={'_id': '13146333', 'listing_url': 'https://www.airbnb.com/rooms/13146333', 'name': '~TROPICAL DREAM VACATION~ Ocean View', ... }]})]

돌아가기

하이브리드 검색

다음

AI 통합