Langchain 과제 : 벡터 저장소를 활용한 유사도 검색

(늦은 사례 글 올립니다.)


10기 랭체인 캠프의 랭체인 과제 2의 실습 1번 “벡터 저장소를 활용한 유사도 검색”입니다.

문제의 주요 내용은 다음과 같습니다.

> 비구조화된 데이터를 저장하고 검색하는 가장 일반적인 방법 중 하나는 데이터를 임베딩하여 생성된 벡터를 저장하고, 검색 시점에 쿼리를 임베딩하여 '가장 유사한' 임베딩 벡터를 검색하는 것입니다. 이 실습에서는 벡터 저장소를 사용하여 임베딩된 데이터를 저장하고 벡터 검색을 수행하는 방법을 배웁니다.
> 
1. 첫 번째 단계에서는 문서(state_of_the_union.txt)를 로드하고 적절한 크기로 나눠줍니다. 이후, 이를 임베딩하여 벡터 저장소에 로드하는 과정을 합니다. 두 번째 단계에서는 주어진 쿼리에 대해 유사도 검색을 수행하고, '가장 유사한' 결과를 검색하여 출력합니다.
2. 예를 들어, "What did the president say about Ketanji Brown Jackson"이라는 쿼리에 대해 **유사도 검색(similarity_search)**을 수행하고, 두번째로 **최대 한계 관련성 검색(MMR)**으로 2개의 검색된 문서의 내용을 출력하는 과정을 실습합니다




기본 구조 & 단계

  • step 0 : Source Data “state_of_the_union.txt”

  • step 1 : Load Source Data —> “TextLoader”

  • step 2 : Transform(Textsplitting) —> “CharacterTextSplitter”

  • step 3 : Text embedding —> “OpenAIEmbeddings”

    » default 모델(old) : text-embedding-ada-002($0.10/1M tokens)
    » 권장 모델(new) : text-embedding-3-small($0.02/1M tokens)

  • step 4 : Vector stores DB —> “Chroma”

  • step 5 : Retrieve ‘most similar’

    A. query embedding
    ("What did the president say about Ketanji Brown Jackson")

    B. 2가지 방식으로 retrieve


※ Retrieve 방식 : similarity_search, max_marginal_relevance_search

  1. similarity_search : 유사도(관련성) 고려(cosine distance)


  1. max_marginal_relevance_search(MMR) : 유사도(관련성)와 다양성 고려


코드

from langchain_community.document_loaders import TextLoader
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import CharacterTextSplitter
from langchain_community.vectorstores import Chroma

# reference doc
# C:\New_LLM_Camp\myenv\Lib\site-packages\langchain_community\vectorstores\chroma.py


# Load the document, split it into chunks, embed each chunk and load it into the vector store.
raw_documents = TextLoader("state_of_the_union.txt", encoding="utf-8").load()

# output the basic information of Load document(state_of_the_union.txt"
print('character count of reference text :', len(raw_documents[0].page_content))
print('source file text : ', raw_documents[0])
print('source file name(metadata) : ', raw_documents[0].metadata['source'])

text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
documents = text_splitter.split_documents(raw_documents)


# check the state of the text_splitting(chunk_size, chunk_overlap)
print(len(documents)) 
 for idx, document in enumerate(documents):
     if idx <= 1: # output the first 2 chunks
         print('=========================chunk number :', idx)
         print(len(document.page_content))
         print((document.page_content))

db = Chroma.from_documents(documents, OpenAIEmbeddings())

print(len(db.get()['documents']))

query = "What did the president say about Ketanji Brown Jackson"

# [1] Similarity search 
docs_ss = db.similarity_search(query)

# [similarity_search] by chroma.py
# 
# """Run similarity search with Chroma.
# 
# Args:
#     query (str): Query text to search for.
#     k (int): Number of results to return. Defaults to 4.
#     filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.
# 
# Returns:
#     List[Document]: List of documents most similar to the query text.
# """

print('------------------------------------------------------------------')
print('---------- similarity_search -------------------------------------')
print('------------------------------------------------------------------')

# 검색된 4개 문서 출력
for idx, doc in enumerate(docs_ss):
    print('[', idx + 1, ']', '\n', doc.page_content, '\n')

# [2] Max marginal relevance search(MMR)
docs_mmr = db.max_marginal_relevance_search(query, k = 4, fetch_k=10, lambda_mult = 0.5) 

# """Return docs selected using the maximal marginal relevance.
# Maximal marginal relevance optimizes for similarity to query AND diversity
# among selected documents.

# Args:
#     query: Text to look up documents similar to.
#     k: Number of Documents to return. Defaults to 4.
#     fetch_k: Number of Documents to fetch to pass to MMR algorithm.
#     lambda_mult: Number between 0 and 1 that determines the degree
#                 of diversity among the results with 0 corresponding
#                 to maximum diversity and 1 to minimum diversity.
#                 Defaults to 0.5.
#     filter (Optional[Dict[str, str]]): Filter by metadata. Defaults to None.

# Returns:
#     List of Documents selected by maximal marginal relevance.
# """

print('------------------------------------------------------------------')
print('---------- max_marginal_relevance_search -------------------------')
print('---------- # lambda_mult : 0.5(default)  -------------------------')
print('------------------------------------------------------------------')

# 검색된 4개 문서 출력
for idx, doc in enumerate(docs_mmr):
    print('[', idx + 1, ']', '\n', doc.page_content, '\n')    


출력 결과

character count of reference text : 38539


source file text :  page_content='Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans.  \n\nLast year COVID-19 kept us apart. This year we are finally together again. \n\nTonight, we meet as Democrats Republicans and Independents. But most importantly as Amer ~~~~~~~~
~~~~~~~~~~~~
~~~~~~~~~~~~~ May God protect our troops.' metadata={'source': 'state_of_the_union.txt'}
source file name(metadata) :  state_of_the_union.txt


42 # text_splitter 적용된 chunks의 개수(chunk_size=1000, chunk_overlap = 0)

42 # Embedding 후 Chroma DB 저장된 문서 개수

------------------------------------------------------------------
---------- similarity_search -------------------------------------
------------------------------------------------------------------
[ 1 ]
 Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections.

Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.

One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court.

And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.

[ 2 ]
 A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.

And if we are to advance liberty and justice, we need to secure the Border and fix the immigration system.

We can do both. At our border, we’ve installed new technology like cutting-edge scanners to better detect drug smuggling.

We’ve set up joint patrols with Mexico and Guatemala to catch more human traffickers.    

We’re putting in place dedicated immigration judges so families fleeing persecution and violence can have their cases heard faster.

We’re securing commitments and supporting partners in South and Central America to host more refugees and secure their own borders.

[ 3 ]
 And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. 

As I said last year, especially to our younger transgender Americans, I will always have your back as your President, so you can be yourself and reach your God-given potential.  

While it often appears that we never agree, that isn’t true. I signed 80 bipartisan bills into law last year. From preventing government shutdowns to protecting Asian-Americans from still-too-common hate crimes to reforming military justice.

And soon, we’ll strengthen the Violence Against Women Act that I first wrote three decades ago. It is important for us to show the nation that we can come together and do big things.

So tonight I’m offering a Unity Agenda for the Nation. Four big things we can do together.

First, beat the opioid epidemic.

[ 4 ]
 Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers.

And as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up.

That ends on my watch.

Medicare is going to set higher standards for nursing homes and make sure your loved ones get the care they deserve and expect.

We’ll also cut costs and keep the economy going strong by giving workers a fair shot, provide more training and apprenticeships, hire them based on their skills not degrees.     

Let’s pass the Paycheck Fairness Act and paid leave.

Raise the minimum wage to $15 an hour and extend the Child Tax Credit, so no one has to raise a family in poverty.

Let’s increase Pell Grants and increase our historic support of HBCUs, and invest in what Jill—our First Lady who teaches full-time—calls America’s best-kept secret: community colleges.
------------------------------------------------------------------
---------- max_marginal_relevance_search -------------------------
---------- # lambda_mult : 0.5(default)  -------------------------
------------------------------------------------------------------
[ 1 ]
 Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections.

Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.

One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court.

And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.

[ 2 ]
 It is going to transform America and put us on a path to win the economic competition of the 21st Century that we face with the rest of the world—particularly with China.       

As I’ve told Xi Jinping, it is never a good bet to bet against the American people.      

We’ll create good jobs for millions of Americans, modernizing roads, airports, ports, and waterways all across America.

And we’ll do it all to withstand the devastating effects of the climate crisis and promote environmental justice.

We’ll build a national network of 500,000 electric vehicle charging stations, begin to replace poisonous lead pipes—so every child—and every American—has clean water to drink at home and at school, provide affordable high-speed internet for every American—urban, suburban, rural, and tribal communities.

4,000 projects have already been announced.

And tonight, I’m announcing that this year we will start fixing over 65,000 miles of highway and 1,500 bridges in disrepair.

[ 3 ]
 We can’t change how divided we’ve been. But we can change how we move forward—on COVID-19 and other issues we must face together.

I recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera.

They were responding to a 9-1-1 call when a man shot and killed them with a stolen gun.  

Officer Mora was 27 years old.

Officer Rivera was 22.

Both Dominican Americans who’d grown up on the same streets they later chose to patrol as police officers.

I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves.

I’ve worked on these issues a long time.

I know what works: Investing in crime preventionand community police officers who’ll walk the beat, who’ll know the neighborhood, and who can restore trust and safety.

[ 4 ]
 But cancer from prolonged exposure to burn pits ravaged Heath’s lungs and body.

Danielle says Heath was a fighter to the very end.

He didn’t know how to stop fighting, and neither did she.

Through her pain she found purpose to demand we do better.

Tonight, Danielle—we are.

The VA is pioneering new ways of linking toxic exposures to diseases, already helping more veterans get benefits.

And tonight, I’m announcing we’re expanding eligibility to veterans suffering from nine respiratory cancers.

I’m also calling on Congress: pass a law to make sure veterans devastated by toxic exposures in Iraq and Afghanistan finally get the benefits and comprehensive health care they deserve.

And fourth, let’s end cancer as we know it.

This is personal to me and Jill, to Kamala, and to so many of you.

Cancer is the #2 cause of death in America–second only to heart disease.


i) 두 가지 유사도 검색 방식 모두 첫 번째 결과 값은 항상 같이 나옴.

ii) MMR 방식의 파리미터 중 lambda_mult 값은 디폴트로 0.5가 지정되어 있는데, 이 값을 1로 지정하면 “similarity_search”와 동일한 결과가 나옴.


※ Cosine Similarity 함수

# 경로 : langchain_community > utils > math.py

def cosine_similarity(X: Matrix, Y: Matrix) -> np.ndarray:
    """Row-wise cosine similarity between two equal-width matrices."""
    if len(X) == 0 or len(Y) == 0:
        return np.array([])

    X = np.array(X)
    Y = np.array(Y)
    if X.shape[1] != Y.shape[1]:
        raise ValueError(
            f"Number of columns in X and Y must be the same. X has shape {X.shape} "
            f"and Y has shape {Y.shape}."
        )
    try:
        import simsimd as simd

        X = np.array(X, dtype=np.float32)
        Y = np.array(Y, dtype=np.float32)
        Z = 1 - simd.cdist(X, Y, metric="cosine")
        if isinstance(Z, float):
            return np.array([Z])
        return np.array(Z)
    except ImportError:
        logger.debug(
            "Unable to import simsimd, defaulting to NumPy implementation. If you want "
            "to use simsimd please install with `pip install simsimd`."
        )
        X_norm = np.linalg.norm(X, axis=1)
        Y_norm = np.linalg.norm(Y, axis=1)
        # Ignore divide by zero errors run time warnings as those are handled below.
        with np.errstate(divide="ignore", invalid="ignore"):
            similarity = np.dot(X, Y.T) / np.outer(X_norm, Y_norm)
        similarity[np.isnan(similarity) | np.isinf(similarity)] = 0.0
        return similarity


(참고) 유사도 검색(similarity search)에서 유사도 점수 출력하기

» similarity_search 대신 similarity_search_with_score" 사용
(state_of_the_union.txt 일부 내용 추출)

from langchain_community.document_loaders import TextLoader
from langchain_openai import OpenAIEmbeddings
from langchain_text_splitters import CharacterTextSplitter
from langchain_community.vectorstores import Chroma

# reference doc
# C:\New_LLM_Camp\myenv\Lib\site-packages\langchain_community\vectorstores\chroma.py


# Load the document, split it into chunks, embed each chunk and load it into the vector store.
raw_documents = TextLoader("sample.txt", encoding="utf-8").load()

# print(raw_documents)
# print('character count of reference text :', len(raw_documents[0].page_content))
# print('source file text : ', raw_documents[0].page_content)
# print('source file name(metadata) : ', raw_documents[0].metadata['source'])


text_splitter = CharacterTextSplitter(chunk_size=300, chunk_overlap=0)
documents = text_splitter.split_documents(raw_documents)

# print(len(documents))

# for idx, document in enumerate(documents):
#     if idx <= 1:
#         print('=========================chunk number :', idx)
#         print(len(document.page_content))
#         print((document.page_content))

db = Chroma.from_documents(documents, OpenAIEmbeddings())

# print((db.get()['documents']))
# print(dir(db))

query = "What did the president say about Ketanji Brown Jackson"

docs_ss = db.similarity_search_with_score(query)

for idx, (doc, score) in enumerate(docs_ss):
    print(f"Index: {idx}")
    print("Document Content:", doc.page_content)
    print("Metadata:", doc.metadata)
    print("Similarity Score:", score)
    print("----------")  # 각 문서 사이에 구분선 추가

<출력 결과>

Index: 0
Document Content: And I did that 4 days ago, when I nominated Circuit Court of Appeals Judge Ketanji Brown Jackson. One of our nation’s top legal minds, who will continue Justice Breyer’s legacy of excellence.
Metadata: {'source': 'sample.txt'}
Similarity Score: 0.34850430488586426
----------
Index: 1
Document Content: One of the most serious constitutional responsibilities a President has is nominating someone to serve on the United States Supreme Court.
Metadata: {'source': 'sample.txt'}
Similarity Score: 0.48887765407562256
----------
Index: 2
Document Content: Tonight, I’d like to honor someone who has dedicated his life to serve this country: Justice Stephen Breyer—an Army veteran, Constitutional scholar, and retiring Justice of the United States Supreme Court. Justice Breyer, thank you for your service.
Metadata: {'source': 'sample.txt'}
Similarity Score: 0.5131170153617859
----------
Index: 3
Document Content: Tonight. I call on the Senate to: Pass the Freedom to Vote Act. Pass the John Lewis Voting Rights Act. And while you’re at it, pass the Disclose Act so Americans can know who is funding our elections.
Metadata: {'source': 'sample.txt'}
Similarity Score: 0.5388283133506775
6

👉 이 게시글도 읽어보세요!

📚 AI 활용 사례 더 보기