ベクターデータベースを使用したRAGの保存と検索

LangChainを使ったLLMアプリケーション開発

Jonathan Bennion

AI Engineer & LangChain Contributor

RAG開発のステップ

一般的なRAGワークフロー: ドキュメントローダー、ドキュメント分割器、および保存と検索のプロセス。

  • この動画の焦点: ストレージ と 検索
LangChainを使ったLLMアプリケーション開発

ベクターデータベースとは何か、なぜ必要なのか?

典型的なRAGワークフロー。

LangChainを使ったLLMアプリケーション開発

どのベクトルデータベースを使うべきですか?

利用可能なさまざまなベクトルデータベースの全体像。オープンソースとクローズドソースで分けられ、さらに専用のベクトルデータベースか、単にその操作をサポートするだけかでも分けられています。

考慮すべき点:

  • オープンソース vs. クローズドソース(ライセンス)
  • クラウド vs. オンプレミス
  • 軽量対パワフル
1 画像提供: Yingjun Wu
LangChainを使ったLLMアプリケーション開発

ドキュメントをご紹介します...

docs
[
    Document(
        page_content="In all marketing copy, TechStack should always be written with the T and S
        capitalized. Incorrect: techstack, Techstack, etc.",
        metadata={"guideline": "brand-capitalization"}
    ),
    Document(
        page_content="Our users should be referred to as techies in both internal and external
        communications.",
        metadata={"guideline": "referring-to-users"}
    )
]
LangChainを使ったLLMアプリケーション開発

Chromaベクトルデータベースの構築

from langchain_openai import OpenAIEmbeddings
from langchain_chroma import Chroma

embedding_function = OpenAIEmbeddings(api_key=openai_api_key, model='text-embedding-3-small')


vectorstore = Chroma.from_documents( docs, embedding=embedding_function, persist_directory="path/to/directory" )
retriever = vectorstore.as_retriever( search_type="similarity", search_kwargs={"k": 2} )
LangChainを使ったLLMアプリケーション開発

プロンプトテンプレートの作成

from langchain_core.prompts import ChatPromptTemplate

message = """
Review and fix the following TechStack marketing copy with the following guidelines in consideration:

Guidelines:
{guidelines}

Copy:
{copy}

Fixed Copy:
"""

prompt_template = ChatPromptTemplate.from_messages([("human", message)])
LangChainを使ったLLMアプリケーション開発

すべてをつなげましょう!

from langchain_core.runnables import RunnablePassthrough

rag_chain = ({"guidelines": retriever, "copy": RunnablePassthrough()}
             | prompt_template
             | llm)

response = rag_chain.invoke("Here at techstack, our users are the best in the world!")
print(response.content)
Here at TechStack, our techies are the best in the world!
LangChainを使ったLLMアプリケーション開発

練習しましょう!

LangChainを使ったLLMアプリケーション開発

Preparing Video For Download...