一、面向文档的对话机器人——代码
from operator import itemgetter
from langchain_core.prompts import ChatPromptTemplate, PromptTemplate, format_document
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough, RunnableLambda
from langchain_community.chat_models import ChatOllama
from langchain_community.embeddings import OllamaEmbeddings
from langchain_community.document_loaders import ArxivLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.vectorstores.faiss import FAISS
# 加载 arXiv 上的论文《ReAct: Synergizing Reasoning and Acting in Language Models》
loader = ArxivLoader(query="2210.03629", load_max_docs=1)
docs = loader.load()
# 把文本分割成 200 字一组的切片
text_splitter = RecursiveCharacterTextSplitter(chunk_size=200, chunk_overlap=20)
chunks = text_splitter.split_documents(docs)
# 构建 FAISS 向量存储和对应的 retriever
vs = FAISS.from_documents(chunks[:10], OllamaEmbeddings(model="llama2-chinese:13b"))
# vs.similarity_search("What is ReAct")
retriever = vs.as_retriever()
# 构建 Document 转文本段落的工具函数
DEFAULT_DOCUMENT_PROMPT = PromptTemplate.from_template(template="{page_content}")
def _combine_documents(
docs, document_prompt=DEFAULT_DOCUMENT_PROMPT, document_separator="\n\n"
):
doc_strings = [format_document(doc, document_prompt) for doc in docs]
return document_separator.join(doc_strings)
# 准备 Model I/O 三元组
template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
model = ChatOllama(model="llama2-chinese:13b")
# 构建 RAG 链
chain = (
{
"context": retriever | _combine_documents,
"question": RunnablePassthrough()
}
| prompt
| model
| StrOutputParser()
)
chain.invoke("什么是 ReAct?")
二、文档
2.1 文档加载
langchain提供了很多种类的文档加载器
2.2 文档预处理
langchain提供了很多种类的文本处理和转换工具,用之前也查查,最基本的就是文档分割,见文档分割一文
2.3 文本向量化存储
vectorstore = FAISS.from_texts(
["harrison worked at kensho"], embedding=OllamaEmbeddings(model="llama2-chinese:13b")
)
# 定义了一个检索器 retriever,可以从文本中检索上下文
retriever = vectorstore.as_retriever()
print(retriever.InputType)
print(retriever.OutputType)
<class 'str'>
typing.List[langchain_core.documents.base.Document]
FAISS.from_texts
更适合处理简单的文本列表
FAISS.from_documents
则适用于处理包含更多结构化信息的文档
由大模型负责embedding,而后存在向量数据库faiss中,注意langchain也支持多种向量数据库的使用
三、retriever检索
向量存储的retriever = vs.as_retriever()方法,得到绑定该向量存储的检索器
3.1 retriever输入输出类型
输入:<class 'str'>
输出:typing.List[langchain_core.documents.base.Document]
这里retriever接收字符串"where did harrison work?":
retrieval_chain = (
{"context": retriever, "question": RunnablePassthrough()}
| prompt
| model
| StrOutputParser()
)
retrieval_chain.invoke("where did harrison work?")
这里chain传入一个字典,故需要通过itemgetter("question")获取字符串传给retriever:
chain = (
{
"context": itemgetter("question") | retriever,
"question": itemgetter("question"),
"language": itemgetter("language"),
}
| prompt
| model
| StrOutputParser()
)
print(chain.invoke({"question": "where did harrison work", "language": "italian"}))