🦜️🔗LangChain : モジュール : 検索 – Retrievers (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 09/06/2023
* 本ページは、LangChain の以下のドキュメントを翻訳した上で適宜、補足説明したものです:
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。
- 人工知能研究開発支援
- 人工知能研修サービス(経営者層向けオンサイト研修)
- テクニカルコンサルティングサービス
- 実証実験(プロトタイプ構築)
- アプリケーションへの実装
- 人工知能研修サービス
- PoC(概念実証)を失敗させないための支援
- お住まいの地域に関係なく Web ブラウザからご参加頂けます。事前登録 が必要ですのでご注意ください。
◆ お問合せ : 本件に関するお問い合わせ先は下記までお願いいたします。
- 株式会社クラスキャット セールス・マーケティング本部 セールス・インフォメーション
- sales-info@classcat.com ; Web: www.classcat.com ; ClassCatJP
🦜️🔗 LangChain : モジュール : 検索 – Retrievers
INFO : 組み込み retriever のサードパーティ・ツールとの統合のドキュメントは 統合 にアクセスしてください。
retriever は非構造化クエリーが与えられたときにドキュメントを返すインターフェイスです。それはベクトルストアよりも汎用的です。retriever はドキュメントをストアできる必要はなく、それらを返す (or 検索取得) ことができるだけです。ベクトルストアは retriever のバックボーンとして使用できますが、他の種類の retrievers もあります。
Get started
LangChain の BaseRetriever クラスの公開 API は以下のようなものです :
from abc import ABC, abstractmethod
from typing import Any, List
from langchain.schema import Document
from langchain.callbacks.manager import Callbacks
class BaseRetriever(ABC):
...
def get_relevant_documents(
self, query: str, *, callbacks: Callbacks = None, **kwargs: Any
) -> List[Document]:
"""Retrieve documents relevant to a query.
Args:
query: string to find relevant documents for
callbacks: Callback manager or list of callbacks
Returns:
List of relevant documents
"""
...
async def aget_relevant_documents(
self, query: str, *, callbacks: Callbacks = None, **kwargs: Any
) -> List[Document]:
"""Asynchronously get documents relevant to a query.
Args:
query: string to find relevant documents for
callbacks: Callback manager or list of callbacks
Returns:
List of relevant documents
"""
...
It’s that simple! クエリーに関連するドキュメントを取得するために get_relevant_documents または非同期の aget_relevant_documents メソッドを呼び出すことができます、ここで「関連性 (relevance)」は呼び出している特定の retriever オブジェクトにより定義されます。
もちろん、私たちが考える有用な retrievers を構築する支援もします。フォーカスする主要なタイプの retrievers はベクトルストア retriever です。このガイドの残りはそれにフォーカスします。
ベクトルストア retriever を理解するためには、ベクトルストアが何かを理解することが重要です。So let’s look at that.
デフォルトでは、LangChain は埋め込みのインデックス作成と検索を行なうためにベクトルストアとして Chroma を使用します。このチュートリアルをウォークスルーするには、最初に chromadb をインストールする必要があります。
pip install chromadb
この例はドキュメントに対する質問応答を紹介します。始めるためのサンプルとしてこれを選択したのは、多くの様々な要素 (テキストスプリッター, 埋め込み, ベクトルストア) を上手く組み合わせて、そしてそれらをチェインで使用する方法も示しているからです。
ドキュメントに対する質問応答は以下の 4 ステップから構成されます :
- インデックス作成
- インデックスから retriever を作成する
- 質問応答チェインの作成
- 質問します!
ステップの各々は複数のサブステップと潜在的な configuration を含みます。このノートブックでは主として (1) に焦点を当てます。それを行なうための one-liner を示すことから始めますが、それから実際に何が起きているのかを分解します。
まず、それが何であっても使用する幾つかの共通クラスをインポートしましょう。
from langchain.chains import RetrievalQA
from langchain.llms import OpenAI
次に、一般的なセットアップで、使用したいドキュメントローダーを指定しましょう。
state_of_the_union.txt ファイルを ここ でダウンロードできます。
from langchain.document_loaders import TextLoader
loader = TextLoader('../state_of_the_union.txt', encoding='utf8')
ワンライン・インデックス作成
できるだけ素早く始めるため、VectorstoreIndexCreator を使用できます。
from langchain.indexes import VectorstoreIndexCreator
index = VectorstoreIndexCreator().from_loaders([loader])
Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient.
インデックスが作成されたので、それを使用してデータの質問をすることができます!内部的にはこれは実際には幾つかのステップを実行していることに注意してください、これは後でこのガイドでカバーします。
query = "What did the president say about Ketanji Brown Jackson"
index.query(query)
" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans."
query = "What did the president say about Ketanji Brown Jackson"
index.query_with_sources(query)
{'question': 'What did the president say about Ketanji Brown Jackson', 'answer': " The president said that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson, one of the nation's top legal minds, to continue Justice Breyer's legacy of excellence, and that she has received a broad range of support from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.\n", 'sources': '../state_of_the_union.txt'}
VectorstoreIndexCreator から返されるものは VectorStoreIndexWrapper で、これは素晴らしいクエリーと query_with_sources の機能を提供しています。ベクトルストアに単に直接アクセスしたい場合は、それを行なうこともできます。
index.vectorstore
<langchain.vectorstores.chroma.Chroma at 0x119aa5940>
そして VectorStoreRetriever にアクセスしたい場合は、それを以下で行なうことができます :
index.vectorstore.as_retriever()
VectorStoreRetriever(vectorstore=, search_kwargs={})
それはまたドキュメントに関連付けられたメタデータによりベクトルストアをフィルタリングするとき便利です、特にベクトルストアが複数のソースを持っているときです。これは以下のような query メソッドを使用して行われます :
index.query("Summarize the general content of this document.", retriever_kwargs={"search_kwargs": {"filter": {"source": "../state_of_the_union.txt"}}})
" The document is a speech given by President Trump to the nation on the occasion of his 245th birthday. The speech highlights the importance of American values and the challenges facing the country, including the ongoing conflict in Ukraine, the ongoing trade war with China, and the ongoing conflict in Syria. The speech also discusses the importance of investing in emerging technologies and American manufacturing, and calls on Congress to pass the Bipartisan Innovation Act and other important legislation."
ウォークスルー
Okay, それでは実際に何が起きているのでしょう?おのインデックスはどのように作成されるのでしょう?
この VectorstoreIndexCreator には多くのマジックが隠されています。これは何をしているのでしょう?
ドキュメントがロードされた後、3 つの主要なステップが進んでいます :
- ドキュメントをチャンクに分割する
- 各ドキュメントの埋め込みを作成する
- ドキュメントと埋め込みをベクトルストアにストアする。
Let’s walk through this in code
documents = loader.load()
次に、ドキュメントをチャンクに分割します。
from langchain.text_splitter import CharacterTextSplitter
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)
そしてどの埋め込みを使用したいか選択します。
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
次にインデックスとして使用するベクトルストアを作成します。
from langchain.vectorstores import Chroma
db = Chroma.from_documents(texts, embeddings)
Running Chroma using direct local API. Using DuckDB in-memory for database. Data will be transient.
そしてそれはインデックスを作成しています。それから、このインデックスを retriever インターフェイスで公開します。
retriever = db.as_retriever()
それから前述のように、チェインを作成してそれを質問応答で使用します!
qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="stuff", retriever=retriever)
query = "What did the president say about Ketanji Brown Jackson"
qa.run(query)
" The President said that Judge Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He said she is a consensus builder and has received a broad range of support from organizations such as the Fraternal Order of Police and former judges appointed by Democrats and Republicans."
VectorstoreIndexCreator はすべてのこのロジック周りの単なるラッパーです。それは使用するテキストスプリッター、使用する埋め込み、そして使用するベクトルストアにおいて構成可能です。例えば、それを以下のように構成できます :
index_creator = VectorstoreIndexCreator(
vectorstore_cls=Chroma,
embedding=OpenAIEmbeddings(),
text_splitter=CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
)
これが VectorstoreIndexCreator の内部で何が起きているかハイライトしていることを願いますインデックスを作成する単純な方法を持つことが重要であると考える一方で、内部的に何が起きているかを理解することも重要であると私たちは考えています。
以上