使用大語言模型集成工具 LangChain 創(chuàng)建自己的論文匯總和查詢工具
Langchain可以幫助開發(fā)人員構(gòu)建由大型語言模型(llm)支持的應(yīng)用程序。它提供一個(gè)框架將LLM與其他數(shù)據(jù)源(如互聯(lián)網(wǎng)或個(gè)人文件)連接起來。這允許開發(fā)人員將多個(gè)命令鏈接在一起,以創(chuàng)建更復(fù)雜的應(yīng)用程序。包括最近比較火爆的AutoGPT等都是使用了Langchain框架進(jìn)行開發(fā)的。所以本文將介紹如何使用LangChain來創(chuàng)建我們自己的論文匯總工具。
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,如果你沒有也不要緊,因?yàn)楹竺嫖覀儠?huì)使用OPEN AI的API,這里只是介紹基本功能
HUGGING_FACE_API_KEY = "hf_...."
然后就可以為我們的問答模型創(chuàng)建一個(gè)提示的模板。這是傳遞給問答模型的默認(rèn)模板,其中包含一個(gè)包含問題的變量。例如:
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表示輸出的隨機(jī)性程度。max_length則為我們令牌的最大長度
現(xiàn)在就可以載入模型:
hf_embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2')
2、創(chuàng)建langchain索引
Langhchain支持多種數(shù)據(jù)加載器和多種數(shù)據(jù)格式,需要通過它的數(shù)據(jù)加載器將我們的數(shù)據(jù)集加載并且放入索引中:
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支持很多類型的矢量存儲(chǔ),每個(gè)向量中的值表示相應(yīng)文檔中每個(gè)術(shù)語的重要性或頻率。這種表示允許通過測量向量之間的余弦相似度來輕松計(jì)算文檔相似度。
向量存儲(chǔ)通常用于信息檢索系統(tǒng)和自然語言處理任務(wù),如文檔分類、搜索引擎和推薦系統(tǒng)。它們還可以用于主題建模和集群等任務(wù)。
這個(gè)示例將使用FAISS (Facebook AI相似度搜索),這是一個(gè)用于高效相似度搜索和密集向量聚類的開源庫。它用于構(gòu)建大規(guī)模的向量數(shù)據(jù)庫,可以通過查詢來檢索與給定查詢向量最相似的向量。
在FAISS矢量數(shù)據(jù)庫中,每個(gè)矢量都表示為高維空間中的一個(gè)點(diǎn)??梢允褂貌煌乃饕椒▽?duì)向量進(jìn)行快速最近鄰搜索,例如IVF、HNSW和PQ。FAISS還支持用于計(jì)算相似度的各種距離度量,例如L2、內(nèi)積和余弦相似度。
vectorstore = FAISS.from_documents(text, hf_embeddings)
3、提問
然后我們就可以創(chuàng)建最有趣的部分,問答(QA) LLM鏈。因?yàn)槲覀兿M軌驒z查答案的來源,所以可以使用“l(fā)oad_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金正整合,創(chuàng)建一個(gè)我們自己的項(xiàng)目。
論文匯總和查詢
langchain里面包含了很多實(shí)用的工具,比如pdf文件的讀取,openai API的對(duì)接,所以我們可以直接拿來使用:
from langchain.chains.summarize import load_summarize_chain
from langchain.document_loaders import PyPDFLoader
from langchain import OpenAI, PromptTemplate
import glob
然后就可以通過OpenAI對(duì)象來與openai的API進(jìn)行對(duì)接:
llm = OpenAI(temperature=0.2)
PyPDFLoader對(duì)象已經(jīng)為我們封裝好了PDF的操作,所以可以直接使用,這里我們遍歷目錄,讀取目錄中的所有文件進(jìn)行操作:
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來對(duì)摘要進(jìn)行索引:
from langchain.indexes import VectorstoreIndexCreator
from langchain.document_loaders import PyPDFDirectoryLoader
loader = PyPDFDirectoryLoader("./pdfs/")
docs = loader.load()
index = VectorstoreIndexCreator().from_loaders([loader])
索引創(chuàng)建完成后就可以查詢了:
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.'
看樣子還不錯(cuò)。
總結(jié)
使用LangChain來總結(jié)和查詢研究論文非常的簡單,LangChain很容易使用,也很容易學(xué)習(xí)。我們可以通過它來完成我們自己的自定義任務(wù),這個(gè)論文匯總的代碼在這里:
https://github.com/EnkrateiaLucca/summarizing_and_querying_multiple_pdfs_with_langchain.git
如果你測試可以直接下載來使用。