AIㆍML

단계별로 알아보는 완전 로컬 검색 증강 생성(RAG)

Nitin Borwankar | InfoWorld 2024.04.12
로컬 임베딩 모델과 로컬 LLM을 사용해 검색 증강 생성 시스템의 완전한 로컬 버전을 구축해 본다. 이전 기사와 마찬가지로 랭체인(LangChain)을 사용해 애플리케이션의 다양한 구성요소를 연결한다. FAISS(페이스북 AI 유사성 검색) 대신 SQLite-vss를 사용해 벡터 데이터를 저장한다. SQLite-vss는 친숙한 SQLite에 유사성 검색을 가능하게 해주는 확장이 추가된 것이다.
 
ⓒ Getty Images Bank

텍스트에 대한 유사성 검색은 임베딩을 사용해서 의미(또는 의미체계)에 대한 최적 매칭을 수행한다. 임베딩은 벡터 공간에서 단어나 구를 숫자로 표현한 것이다. 벡터 공간에서 두 임베딩 사이의 거리가 가까울수록 두 단어 또는 구의 의미도 더 비슷하다. 따라서 자체 문서를 LLM에 제공하려면 먼저 문서를 LLM이 입력으로 받을 수 있는 유일한 원시 재료인 임베딩으로 변환해야 한다.
 
임베딩을 로컬 벡터 저장소에 저장한 다음 이 벡터 스토어를 LLM과 통합한다. LLM은 라마 2(Llama 2)를 사용하는데, 올라마(Ollama)라는 앱을 사용해서 로컬로 실행한다. 올라마는 맥OS와 리눅스, 윈도우(프리뷰)용으로 나와 있다. 올라마 설치에 대해서는 이 인포월드 기사에서 읽어볼 수 있다.
 
간단한 완전 로컬 RAG 시스템을 구축하기 위해 필요한 구성요소 목록은 다음과 같다.
 
  1. 문서 코퍼스. 여기서는 바이든 대통령의 2023년 2월 7일 연두 교서 텍스트가 포함된 하나의 문서만 사용한다. 텍스트는 아래 링크에서 다운로드할 수 있다.
  2. 문서 로더. 문서에서 텍스트를 추출해 임베딩을 생성하기 위한 청크로 전처리하는 코드.
  3. 임베딩 모델. 전처리된 문서 청크를 입력으로 받아서 임베딩(문서 청크를 표현하는 일련의 벡터)을 출력하는 모델.
  4. 검색을 위한 인덱스가 있는 로컬 벡터 데이터 저장소
  5. 지시에 따르고 자체 시스템에서 실행되도록 조정된 LLM. 시스템은 데스크톱, 노트북 또는 클라우드의 VM도 된다. 예제에서는 필자의 맥에 설치된 올라마에서 실행되는 라마 2 모델을 사용한다.
  6. 질문을 위한 채팅 템플릿. 이 템플릿은 LLM이 사람이 이해하는 형식으로 응답할 수 있도록 하기 위한 틀을 만든다.
 
이제 코드를 보자. 주석에 부가적인 설명이 포함돼 있다.

바이든 대통령의 2023년 2월 7일 연두 교서 텍스트 파일 연두 교서 다운로드
 

완전 로컬 RAG 예제 – 검색 코드

# LocalRAG.py
# LangChain is a framework and toolkit for interacting with LLMs programmatically
from langchain.embeddings.sentence_transformer import SentenceTransformerEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores import SQLiteVSS
from langchain.document_loaders import TextLoader
# Load the document using a LangChain text loader
loader = TextLoader("./sotu2023.txt")
documents = loader.load()
# Split the document into chunks
text_splitter = CharacterTextSplitter (chunk_size=1000, chunk_overlap=0)
docs = text_splitter.split_documents(documents)
texts = [doc.page_content for doc in docs]
# Use the sentence transformer package with the all-MiniLM-L6-v2 embedding model
embedding_function = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
# Load the text embeddings in SQLiteVSS in a table named state_union
db = SQLiteVSS.from_texts(
    texts = texts,
    embedding = embedding_function,
    table = "state_union",
    db_file = "/tmp/vss.db"
)
# First, we will do a simple retrieval using similarity search
# Query
question = "What did the president say about Nancy Pelosi?"
data = db.similarity_search(question)
# print results
print(data[0].page_content)
 

완전 로컬 RAG 예제 – 검색 출력

Mr. Speaker. Madam Vice President. Our First Lady and Second Gentleman.
Members of Congress and the Cabinet. Leaders of our military.
Mr. Chief Justice, Associate Justices, and retired Justices of the Supreme Court.
And you, my fellow Americans.
I start tonight by congratulating the members of the 118th Congress and the new Speaker of the House, Kevin McCarthy.
Mr. Speaker, I look forward to working together.
I also want to congratulate the new leader of the House Democrats and the first Black House Minority Leader in history, Hakeem Jeffries.
Congratulations to the longest serving Senate Leader in history, Mitch McConnell.
And congratulations to Chuck Schumer for another term as Senate Majority Leader, this time with an even bigger majority.
And I want to give special recognition to someone who I think will be considered the greatest Speaker in the history of this country, Nancy Pelosi.
결과에는 쿼리와 관련된 텍스트 청크가 문자 그대로 포함된다. 벡터 데이터베이스의 유사성 검색에 의해 반환된 것이지만 쿼리에 대한 답은 아니다. 쿼리에 대한 답은 출력의 마지막 줄이고, 나머지는 이 답을 위한 컨텍스트다.
 
벡터 데이터베이스에서 원시 유사성 검색을 하는 경우에는 문서의 청크만 결과로 받게 된다. 질문의 성격과 범위에 따라 두 개 이상의 청크가 표시되는 경우가 많은데, 예제 질문은 범위가 좁은 편이고 텍스트에 낸시 펠로시에 대한 언급은 한 번만 있으므로 여기서는 하나의 청크만 반환됐다.
 
이제 LLM을 사용해서 유사성 검색에서 받은 텍스트 청크를 흡수해 쿼리에 대한 간결한 답을 생성해 보자.
 
다음 코드를 실행하려면 먼저 올라마를 설치하고 llama2:7b 모델을 다운로드해야 한다. 참고로 맥OS와 리눅스에서 올라마는 사용자 홈 디렉터리의 .ollama 하위 디렉터리에 모델을 저장한다.
 

완전 로컬 RAG – 쿼리 코드

# LLM
from langchain.llms import Ollama
from langchain.callbacks.manager import CallbackManager
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
llm = Ollama(
    model = "llama2:7b",
    verbose = True,
    callback_manager = CallbackManager([StreamingStdOutCallbackHandler()]),
)
# QA chain
from langchain.chains import RetrievalQA
from langchain import hub
# LangChain Hub is a repository of LangChain prompts shared by the community
QA_CHAIN_PROMPT = hub.pull("rlm/rag-prompt-llama")
qa_chain = RetrievalQA.from_chain_type(
    llm,
    # we create a retriever to interact with the db using an augmented context
    retriever = db.as_retriever(), 
    chain_type_kwargs
= {"prompt": QA_CHAIN_PROMPT},
)
result = qa_chain({"query": question})
 

완전 로컬 RAG 예제 – 쿼리 출력

In the retrieved context, President Biden refers to Nancy Pelosi as 
"someone who I think will be considered the greatest Speaker in the history of this country." 
This suggests that the President has a high opinion of Pelosi's leadership skills and accomplishments as Speaker of the House.

 
두 코드의 출력의 다른 것을 볼 수 있다. 첫 번째는 쿼리와 관련된 문서에서 문자 그대로 가져온 텍스트 청크이고, 두 번째는 쿼리에 대한 요약된 답변이다. 첫 번째의 경우 LLM을 사용하지 않고 벡터 저장소를 사용해서 문서에서 텍스트 청크만 검색했다. 두 번째에서는 LLM을 사용해서 쿼리에 대한 간결한 답을 생성했다. 
 
실제 애플리케이션에서 RAG를 사용하려면 PDF, DOCX, RTF, XLSX, PPTX와 같은 여러 문서 형식을 가져와야 한다. 랭체인라마인덱스(LlamaIndex: LLM 애플리케이션을 구축하는 데 많이 사용되는 또 다른 프레임워크) 모두 다양한 문서 형식에 특화된 로더가 있다.
 
FAISS와 SQLite-vss 외의 다른 벡터 저장소도 있다. 대규모 언어 모델 및 다른 생성형 AI 영역과 마찬가지로 벡터 데이터베이스 분야도 빠르게 발전하고 있다. 앞으로 후속 기사에서 이러한 모든 영역에서의 다른 옵션도 살펴볼 예정이다.
editor@itworld.co.kr 
Sponsored

회사명 : 한국IDG | 제호: ITWorld | 주소 : 서울시 중구 세종대로 23, 4층 우)04512
| 등록번호 : 서울 아00743 등록발행일자 : 2009년 01월 19일

발행인 : 박형미 | 편집인 : 박재곤 | 청소년보호책임자 : 한정규
| 사업자 등록번호 : 214-87-22467 Tel : 02-558-6950

Copyright © 2024 International Data Group. All rights reserved.