LangChainのContextual Compressionのいくつかの機能がどのように実現されているかを確認してみた

最近、LangChainの以下の公式blog記事で「Contextual Compression」という機能が紹介されていました。

https://blog.langchain.dev/improving-document-retrieval-with-contextual-compression/

ちょうどこういう機能があったらいいなぁと思っていたところだったので、この機能について調べてみました。今回はそのまとめ記事になります。

今回の記事を書くにあたり、動作チェックをした際のnotebookはここにあげておきました。コードを見たい方はこちらをご覧ください。

https://github.com/shu65/langchain_examples/blob/main/LangChain_Contextual_Compression.ipynb

また、LangChainがどういうものかご存じない方は以前LangChainの紹介記事を書きましたので、こちらをご覧ください。

Contextual Compressionとは?

LLMを使ったQAシステムでは関連するドキュメントを見つけてきて、質問と関連ドキュメントをLLMに入れて質問に答えるという形のものがあります。この際、以下のような問題点があります。

  1. 質問と関連してないドキュメントが含まれるケースがある
  2. 関連ドキュメントの文字数が多いとLLMに入力できる文字数を圧迫する

この問題を解決する方法の手段の一つとしてこの「Contextual Compression」があります。

このContextual Compressionでは関連ドキュメントを見つけたあと、質問により関連している情報だけを抽出します。この抽出された情報と質問をLLMに入れてより的確な質問に答えられるようにするというものです。

LangChainではContextual Compressionの機能としていくつか用意されています。その中でもぱっと見て動作が分かりずらいLLMを使ったものに関して今回はどういうpromptになっているのかを調べたので順番に紹介していきます。

LLMChainExtractor

まず一つ目が「LLMChainExtractor」です。これは関連するドキュメントを見つけたあとLLMによって質問に関連する部分だけを抽出するものになっています。

LLMChainExtractorを使う前の以下のコードは以下の通りです。

from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.document_loaders import TextLoader
from langchain.vectorstores import FAISS

documents = TextLoader('./state_of_the_union.txt').load()
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)
retriever = FAISS.from_documents(texts, OpenAIEmbeddings()).as_retriever()

docs = retriever.get_relevant_documents("What did the president say about Ketanji Brown Jackson")

このコードの出力は以下のようになります。

Document 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.
----------------------------------------------------------------------------------------------------
Document 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.
----------------------------------------------------------------------------------------------------
Document 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.
----------------------------------------------------------------------------------------------------
Document 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.

それでは次にLLMChainExtractorを使った場合の結果を見てみます。コードとしては以下の通りです。

from langchain.llms import OpenAI
from langchain.retrievers import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import LLMChainExtractor

llm = OpenAI(temperature=0)
compressor = LLMChainExtractor.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(base_compressor=compressor, base_retriever=retriever)

compressed_docs = compression_retriever.get_relevant_documents("What did the president say about Ketanji Jackson Brown")

compressed_docsの中身を見てみると以下の通りです。

Document 1:

"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."
----------------------------------------------------------------------------------------------------
Document 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."

先ほど変わってドキュメント数が減っているのと、Document 1のほうを見ると出力されている内容もたしかに関連したところだけ残っている感じがしています。この時、どのようなpromtpでLLMを実行されていたかというと、以下のようなテンプレートを使ってpromptを作ってLLMに入力していました。

"""Given the following question and context, extract any part of the context *AS IS* that is relevant to answer the question. If none of the context is relevant return {no_output_str}. 

Remember, *DO NOT* edit the extracted parts of the context.

> Question: {{question}}
> Context:
>>>
{{context}}
>>>
Extracted relevant parts:"""

{{question}}と{{context}}がそれぞれ入力した質問と関連ドキュメントとして見つけたドキュメントの内容を入れる部分です。

templateを見ると、関連ドキュメントの中から質問に回答と関連すると思われるところを抜き出してくるというものになっています。また、関連していなければ{no_output_str}、実際にはNO_OUTPUTという文字列を返すようになっています。

これにより、見つけてきたドキュメントが関係ないものであればはじくということができるようになっています。

LLMChainFilter

次に「LLMChainFilter」です。これは先ほどの「LLMChainExtractor」と同じようにLLMを使うものになっていますが、見つけたドキュメントが質問に関連するものかどうかだけを判断し、関連しないものであればはじくということだけをするものになっています。つまり、「LLMChainExtractor」であった質問に関連する部分を抽出するという処理がなくなったバージョンという感じかと思います。

LLMChainFilterを利用するコードは以下のようになっています。

from langchain.retrievers.document_compressors import LLMChainFilter

_filter = LLMChainFilter.from_llm(llm)
compression_retriever = ContextualCompressionRetriever(base_compressor=_filter, base_retriever=retriever)

compressed_docs = compression_retriever.get_relevant_documents("What did the president say about Ketanji Jackson Brown")

このコードの出力結果は以下のようになります。

Document 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.

オリジナルのコードでは4つ関連ドキュメントがでていましたが、今回は一つだけになっています。

これを実現するためにLLMChainFilterはLLMには以下のようなテンプレートのpromptをLLMに入力しています。

"""Given the following question and context, return YES if the context is relevant to the question and NO if it isn't.

> Question: {question}
> Context:
>>>
{context}
>>>
> Relevant (YES / NO):"""

{question}と{context}がそれぞれ入力した質問と関連ドキュメントとして見つけたドキュメントの内容を入れる部分です。

テンプレートを見ればわかる通り、質問と関連するドキュメントかどうかを聞き、YESかNOを返すようにLLMにお願いするpromptになっていることがわかります。

それ以外のContextual Compressionの機能

今回はLLMを利用しているContextual Compressionのみに注目して紹介しましたが、これ以外にも以下のようなものがあります。

  1. EmbeddingsFilter: Embeddingによって質問と関連するドキュメントかどうかを判断してフィルタリングするもの。LLMを利用しないので、高速に動作する
  2. DocumentCompressorPipeline: 複数の前処理との組み合わせることができるContextual Compressionの仕組み

実際にこれらを使った例は公式のこちらのnotebookにありますので気になる方はご覧ください。

https://python.langchain.com/en/latest/modules/indexes/retrievers/examples/contextual-compression.html

終わりに

今回はContextual Compressionについて調べたのでまとめを書きました。LangChainを使った例としてQAシステムはよく見るのですが、自分でやってみると関連ドキュメントを見つけてくるドキュメントが微妙ということがよくあるので、このような仕組みがあったらいいな、と思っていました。このため、今回は個人的には非常に勉強になりました。

今後もまたLLMをどう扱えばいいのか?の勉強でいろいろ調べたらまとめようと思います。

この記事が皆様のお役に立てれば幸いです。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトは reCAPTCHA と Google によって保護されていますプライバシーポリシー利用規約 申し込み。

The reCAPTCHA verification period has expired. Please reload the page.