使用向量資料庫的 RAG 儲存與擷取

使用 LangChain 開發 LLM 應用

Jonathan Bennion

AI Engineer & LangChain Contributor

RAG 開發步驟

一般 RAG 工作流程:文件載入器、文件分割器,以及儲存與擷取流程。

  • 本影片重點:_儲存_ 與 _擷取_
使用 LangChain 開發 LLM 應用

什麼是向量資料庫?為什麼需要它?

典型的 RAG 工作流程。

使用 LangChain 開發 LLM 應用

該用哪一個向量資料庫?

 

各式向量資料庫的版圖,依開源與封閉,以及是專用向量資料庫或僅支援向量操作來區分。

 

需考量:

  • 開源 vs. 封閉(授權)
  • 雲端 vs. 機房自建
  • 輕量 vs. 強大
1 Image Credit: 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 應用

建立提示樣板(prompt template)

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