赞
踩
与大型 PDF 对话很酷。您可以与笔记、书籍和文档等进行聊天。这篇博文将帮助您构建一个基于 Multi RAG Streamlit 的 Web 应用程序,以通过对话式 AI 聊天机器人读取、处理和与 PDF 数据交互。以下是此应用程序工作原理的分步说明,使用简单的语言便于理解。
《LangChain + Streamlit:在几分钟内创建基于语言模型的大型演示所需的技术堆栈》 权重1,本地类、Streamlit类、LangChain类
《使用本地 Llama 2 模型和向量数据库建立私有检索增强生成 (RAG) 系统 LangChain》权重1,llama类、本地类、langchain类
《如何在自己的电脑上构建大语言模型,使用 LangChain(而不是 OpenAI)回答关于您的文档的问题》 权重2,本地类、langchain类
《在本地 PC 上构建本地聊天机器人100%离线,基于 Langchain、LLama Streamlit 的小于 1 GB 的大型语言模型(支持apple macos m1 m2 window11)》 权重1,本地类、苹果类,llama类、langchain类
《如何使用 GPT4All 和 Langchain 来处理您的文档》 权重1,矢量数据库类、langchain类
《LangChain + Streamlit:在几分钟内创建基于语言模型的大型演示所需的技术堆栈》 权重1,本地类、Streamlit类、LangChain类
《LangChain 系列教程之 使用 LangChain 将对话转化为有向图 构建一个旨在了解有关新潜在客户的关键信息的聊天机器人。》 权重0,矢量数据库类、langchain类
《Langchain Streamlit AI系列之使用 Langchain、OpenAI 函数调用和 Streamlit 构建 AI 金融分析师》 权重0,矢量数据库类、langchain类
《Langchain Streamlit AI系列之 LangChain + Streamlit+ Llama 将对话式 AI 引入你的本地机器(教程含完成源码)》 权重0,矢量数据库类、langchain类
《Langchain Streamlit AI系列之 构建多 PDF RAG 聊天机器人,通过对话式 AI 聊天机器人读取、处理和与 PDF 数据交互(教程含源码)》 权重0,矢量数据库类、langchain类
该应用程序首先导入各种强大的库:
import streamlit as st
from PyPDF2 import PdfReader
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_core.prompts import ChatPromptTemplate
from langchain_community.embeddings.spacy_embeddings import SpacyEmbeddings
from langchain_community.vectorstores import FAISS
from langchain.tools.retriever import create_retriever_tool
from dotenv import load_dotenv
from langchain_anthropic import ChatAnthropic
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain.agents import AgentExecutor, create_tool_calling_agent
import os
os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
我们的应用程序中的第一个主要功能是用于读取 PDF 文件:
文本分割器:使用 Langchain 库,将文本分成每 1000 个字符的块。这种分割有助于更有效地处理和分析文本。
def pdf_read(pdf_doc):
text = ""
for pdf in pdf_doc:
pdf_reader = PdfReader(pdf)
for page in pdf_reader.pages:
text += page.extract_text()
return text
def get_chunks(text):
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
chunks = text_splitter.split_text(text)
return chunks
为了使文本可搜索,应用程序将文本块转换为向量表示:
embeddings = SpacyEmbeddings(model_name="en_core_web_sm")
def vector_store(text_chunks):
vector_store = FAISS.from_texts(text_chunks, embedding=embeddings)
vector_store.save_local("faiss_db")
该应用的核心是对话式人工智能,它使用了 OpenAI 的强大模型:
def get_conversational_chain(tools, ques): llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0, api_key="") prompt = ChatPromptTemplate.from_messages([...]) tool=[tools] agent = create_tool_calling_agent(llm, tool, prompt) agent_executor = AgentExecutor(agent=agent, tools=tool, verbose=True) response=agent_executor.invoke({"input": ques}) print(response) st.write("Reply: ", response['output']) def user_input(user_question): new_db = FAISS.load_local("faiss_db", embeddings,allow_dangerous_deserialization=True) retriever=new_db.as_retriever() retrieval_chain= create_retriever_tool(retriever,"pdf_extractor","This tool is to give answer to queries from the pdf") get_conversational_chain(retrieval_chain,user_question)
后端准备就绪后,该应用程序使用 Streamlit 创建了一个用户友好的界面:
def main(): st.set_page_config("Chat PDF") st.header("RAG based Chat with PDF") user_question = st.text_input("Ask a Question from the PDF Files") if user_question: user_input(user_question) with st.sidebar: pdf_doc = st.file_uploader("Upload your PDF Files and Click on the Submit & Process Button", accept_multiple_files=True) if st.button("Submit & Process"): with st.spinner("Processing..."): raw_text = pdf_read(pdf_doc) text_chunks = get_chunks(raw_text) vector_store(text_chunks) st.success("Done")
import streamlit as st from PyPDF2 import PdfReader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_core.prompts import ChatPromptTemplate from langchain_community.embeddings.spacy_embeddings import SpacyEmbeddings from langchain_community.vectorstores import FAISS from langchain.tools.retriever import create_retriever_tool from dotenv import load_dotenv from langchain_anthropic import ChatAnthropic from langchain_openai import ChatOpenAI, OpenAIEmbeddings from langchain.agents import AgentExecutor, create_tool_calling_agent import os os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE" embeddings = SpacyEmbeddings(model_name="en_core_web_sm") def pdf_read(pdf_doc): text = "" for pdf in pdf_doc: pdf_reader = PdfReader(pdf) for page in pdf_reader.pages: text += page.extract_text() return text def get_chunks(text): text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) chunks = text_splitter.split_text(text) return chunks def vector_store(text_chunks): vector_store = FAISS.from_texts(text_chunks, embedding=embeddings) vector_store.save_local("faiss_db") def get_conversational_chain(tools,ques): #os.environ["ANTHROPIC_API_KEY"]=os.getenv["ANTHROPIC_API_KEY"] #llm = ChatAnthropic(model="claude-3-sonnet-20240229", temperature=0, api_key=os.getenv("ANTHROPIC_API_KEY"),verbose=True) llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0, api_key="") prompt = ChatPromptTemplate.from_messages( [ ( "system", """You are a helpful assistant. Answer the question as detailed as possible from the provided context, make sure to provide all the details, if the answer is not in provided context just say, "answer is not available in the context", don't provide the wrong answer""", ), ("placeholder", "{chat_history}"), ("human", "{input}"), ("placeholder", "{agent_scratchpad}"), ] ) tool=[tools] agent = create_tool_calling_agent(llm, tool, prompt) agent_executor = AgentExecutor(agent=agent, tools=tool, verbose=True) response=agent_executor.invoke({"input": ques}) print(response) st.write("Reply: ", response['output']) def user_input(user_question): new_db = FAISS.load_local("faiss_db", embeddings,allow_dangerous_deserialization=True) retriever=new_db.as_retriever() retrieval_chain= create_retriever_tool(retriever,"pdf_extractor","This tool is to give answer to queries from the pdf") get_conversational_chain(retrieval_chain,user_question) def main(): st.set_page_config("Chat PDF") st.header("RAG based Chat with PDF") user_question = st.text_input("Ask a Question from the PDF Files") if user_question: user_input(user_question) with st.sidebar: st.title("Menu:") pdf_doc = st.file_uploader("Upload your PDF Files and Click on the Submit & Process Button", accept_multiple_files=True) if st.button("Submit & Process"): with st.spinner("Processing..."): raw_text = pdf_read(pdf_doc) text_chunks = get_chunks(raw_text) vector_store(text_chunks) st.success("Done") if __name__ == "__main__": main()
通过将应用程序另存为 app.py 然后使用来运行
streamlit 运行应用程序.py
输出:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。