使用向量数据库进行 RAG 存储与检索

使用 LangChain 开发 LLM 应用

Jonathan Bennion

AI Engineer & LangChain Contributor

RAG 开发步骤

一般的 RAG 工作流:文档加载器、文档切分,以及存储与检索流程。

  • 本视频重点:存储 与 检索
使用 LangChain 开发 LLM 应用

什么是向量数据库?为何需要它?

典型的 RAG 工作流。

使用 LangChain 开发 LLM 应用

我该用哪种向量数据库?

 

不同向量数据库的全景:按开源/闭源与专用/支持型划分。

 

需要考虑:

  • 开源 vs. 闭源(许可)
  • 云端 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 应用

Passons à la pratique !

使用 LangChain 开发 LLM 应用

Preparing Video For Download...