0


使用大语言模型集成工具 LangChain 创建自己的论文汇总和查询工具

Langchain可以帮助开发人员构建由大型语言模型(llm)支持的应用程序。它提供一个框架将LLM与其他数据源(如互联网或个人文件)连接起来。这允许开发人员将多个命令链接在一起,以创建更复杂的应用程序。包括最近比较火爆的AutoGPT等都是使用了Langchain框架进行开发的。所以本文将介绍如何使用LangChain来创建我们自己的论文汇总工具。

LangChain的基本使用方法

我们先了解LangChain的基本使用情况,所以这里使用HuggingFace为例,介绍LangChain最基本的用法。

1、整合transformer

 from langchain import PromptTemplate, HuggingFaceHub, LLMChain
 from langchain.embeddings import HuggingFaceEmbeddings
 from langchain.indexes import VectorstoreIndexCreator
 from langchain.callbacks.base import CallbackManager
 from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
 from langchain.chains.qa_with_sources import load_qa_with_sources_chain
 from langchain.document_loaders import DirectoryLoader
 from langchain.text_splitter import RecursiveCharacterTextSplitter
 from langchain.vectorstores import FAISS
 from huggface_hub import hf_hub_download
 import textwrap
 import glob

这里需要HuggingFace的API key,如果你没有也不要紧,因为后面我们会使用OPEN AI的API,这里只是介绍基本功能

 HUGGING_FACE_API_KEY = "hf_...."

然后就可以为我们的问答模型创建一个提示的模板。这是传递给问答模型的默认模板,其中包含一个包含问题的变量。例如:

 template = """ You are going to be my assistant.
 Please try to give me the most beneficial answers to my
 question with reasoning for why they are correct.
 
  Question: {input} Answer: """
 prompt = PromptTemplate(template=template, input_variables=["input"])

从Huggingface加载模型。我们以facebook/mbart-large-50为例

 model = HuggingFaceHub(repo_id="facebook/mbart-large-50",
                        model_kwargs={"temperature": 0, "max_length":200},
                        huggingfacehub_api_token=HUGGING_FACE_API_KEY)
 chain = LLMChain(prompt=prompt, llm=model)

temperature表示输出的随机性程度。max_length则为我们令牌的最大长度

现在就可以载入模型:

 hf_embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2')

2、创建langchain索引

Langhchain支持多种数据加载器和多种数据格式,需要通过它的数据加载器将我们的数据集加载并且放入索引中:

 my_loader = DirectoryLoader('my_data', glob='**/*.txt')
 docs = my_loader.load()
 text_split = RecursiveCharacterTextSplitter(chunk_size = 700, chunk_overlap = 0)
 text = text_split.split_documents(docs)

Langchain支持很多类型的矢量存储,每个向量中的值表示相应文档中每个术语的重要性或频率。这种表示允许通过测量向量之间的余弦相似度来轻松计算文档相似度。

向量存储通常用于信息检索系统和自然语言处理任务,如文档分类、搜索引擎和推荐系统。它们还可以用于主题建模和集群等任务。

这个示例将使用FAISS (Facebook AI相似度搜索),这是一个用于高效相似度搜索和密集向量聚类的开源库。它用于构建大规模的向量数据库,可以通过查询来检索与给定查询向量最相似的向量。

在FAISS矢量数据库中,每个矢量都表示为高维空间中的一个点。可以使用不同的索引方法对向量进行快速最近邻搜索,例如IVF、HNSW和PQ。FAISS还支持用于计算相似度的各种距离度量,例如L2、内积和余弦相似度。

 vectorstore = FAISS.from_documents(text, hf_embeddings)

3、提问

然后我们就可以创建最有趣的部分,问答(QA) LLM链。因为我们希望能够检查答案的来源,所以可以使用“load_qa_with_sources_chain”:

 my_chain = load_qa_with_sources_chain(model, chain_type="refine")
 query = "Any question that you want to ask the model"
 documents = vectorstore.similarity_search(query)
 result = with_sources_chain({"input_documents": documents, "question": query})

这样在result变量中就能获得我们问题的答案了。

以上就是LangChain的基本使用方法,下面我们来将他与OpenAI金正整合,创建一个我们自己的项目。

论文汇总和查询

langchain里面包含了很多实用的工具,比如pdf文件的读取,openai API的对接,所以我们可以直接拿来使用:

 from langchain.chains.summarize import load_summarize_chain
 from langchain.document_loaders import PyPDFLoader
 from langchain import OpenAI, PromptTemplate
 import glob

然后就可以通过OpenAI对象来与openai的API进行对接:

 llm = OpenAI(temperature=0.2)

PyPDFLoader对象已经为我们封装好了PDF的操作,所以可以直接使用,这里我们遍历目录,读取目录中的所有文件进行操作:

 def summarize_pdfs_from_folder(pdfs_folder):
     summaries = []
     for pdf_file in glob.glob(pdfs_folder + "/*.pdf"):
         loader = PyPDFLoader(pdf_file)
         docs = loader.load_and_split()
         chain = load_summarize_chain(llm, chain_type="map_reduce")
         summary = chain.run(docs)
         print("Summary for: ", pdf_file)
         print(summary)
         print("\n")
         summaries.append(summary)
     
     return summaries

将摘要保存为文本文件:

 with open("summaries.txt", "w") as f:
     for summary in summaries:
         f.write(summary + "\n"*3)

然后使用VectorStoreIndexCreator来对摘要进行索引:

 from langchain.indexes import VectorstoreIndexCreator
 from langchain.document_loaders import PyPDFDirectoryLoader
 loader = PyPDFDirectoryLoader("./pdfs/")
 
 docs = loader.load()
 index = VectorstoreIndexCreator().from_loaders([loader])

索引创建完成后就可以查询了:

 query = "What is the core idea behind the CoOP (context optimization) paper?"
 index.query(query)
 
 # Output
 # " The core idea behind the CoOP paper is to model 
 # a prompt's context words with learnable vectors 
 # while keeping the entire pre-trained parameters fixed, 
 # in order to adapt CLIP-like vision-language models for 
 # downstream image recognition tasks."

或者:

 query = "What is the central idea that can allow for scaling transformers to 1 million tokens?"
 
 index.query(query)
 
 # Output
 # ' The central idea is to use the Recurrent Memory Transformer (RMT) architecture to extend the context length of BERT, allowing it to store and process both local and global information across up to 2 million tokens.'

看样子还不错。

总结

使用LangChain来总结和查询研究论文非常的简单,LangChain很容易使用,也很容易学习。我们可以通过它来完成我们自己的自定义任务,这个论文汇总的代码在这里:

https://github.com/EnkrateiaLucca/summarizing_and_querying_multiple_pdfs_with_langchain.git

如果你测试可以直接下载来使用。

“使用大语言模型集成工具 LangChain 创建自己的论文汇总和查询工具”的评论:

还没有评论