微信扫码
添加专属顾问
与大量 PDF 文档的交互如今变得前所未有地便捷与智能。想象一下,您可以轻松与您的笔记、书籍和各种文档进行无缝对话,不再需要繁琐的手动查找和处理。
这篇文章将带您逐步构建一个基于 Multi-RAG 和 Streamlit 的 Web 应用程序,该应用程序通过 AI 驱动的聊天机器人来读取、解析和处理 PDF 数据,提供前所未有的用户体验。让我们一起深入探讨开发这一创新应用的完整过程,了解如何通过先进技术实现高效的文档管理与交互。
在开始构建之前,让我们先介绍一下我们将使用的关键工具和库:
Streamlit:Streamlit 是一个功能强大的框架,它显著简化了为机器学习和数据科学项目创建和分享美观、自定义 Web 应用程序的过程。通过 Streamlit,开发者可以快速将数据分析、模型结果和交互式可视化打包成易于使用的 Web 应用,无需深厚的前端开发经验。
PyPDF2:一个专为阅读和操作 PDF 文件而设计的综合库。它可以提取文本、合并多个 PDF,甚至解密受保护的 PDF。
Langchain:一套多功能工具,旨在增强自然语言处理 (NLP) 并创建复杂的对话式 AI 应用程序。Langchain为文本处理、嵌入和交互提供了各种工具。
FAISS:由 Facebook AI Research 开发的库,旨在实现高效的相似性搜索和密集向量的聚类。它经过高度优化,并支持快速索引和搜索,这对于处理大型数据集至关重要。
import streamlit as st # Importing Streamlit for the web interfacefrom PyPDF2 import PdfReader # Importing PyPDF2 for reading PDF filesfrom langchain.text_splitter import RecursiveCharacterTextSplitter # Importing Langchain's text splitterfrom langchain_core.prompts import ChatPromptTemplate # Importing ChatPromptTemplate from Langchainfrom langchain_community.embeddings.spacy_embeddings import SpacyEmbeddings # Importing SpacyEmbeddingsfrom langchain_community.vectorstores import FAISS # Importing FAISS for vector storefrom langchain.tools.retriever import create_retriever_tool # Importing retriever tool from Langchainfrom dotenv import load_dotenv # Importing dotenv to manage environment variablesfrom langchain_anthropic import ChatAnthropic # Importing ChatAnthropic from Langchainfrom langchain_openai import ChatOpenAI, OpenAIEmbeddings # Importing ChatOpenAI and OpenAIEmbeddings from Langchainfrom langchain.agents import AgentExecutor, create_tool_calling_agent # Importing agent-related modules from Langchainimport osos.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE" # Setting environment variable to avoid potential conflicts
我们应用程序的第一个主要功能涉及读取 PDF 文件。这是使用 PDF 阅读器实现的,该阅读器从上传的 PDF 文件中提取文本并将其编译为单个连续字符串。
当用户上传一个或多个 PDF 时,应用程序会处理每个文档以提取文本。此过程涉及读取 PDF 的每一页并将文本连接起来以形成一个大字符串。
PDF上传:用户可以通过 Streamlit 界面上传多个 PDF 文件。
文本提取:对于每个上传的 PDF,应用程序使用 PdfReader 遍历每个页面并提取文本。然后,此文本被连接成一个连续的字符串。
def pdf_read(pdf_doc):text = ""for pdf in pdf_doc:pdf_reader = PdfReader(pdf) # Initializing the PDF reader for the given documentfor page in pdf_reader.pages: # Iterating through each page in the PDFtext += page.extract_text() # Extracting and appending the text from the current pagereturn text # Returning the concatenated text from all pages
为了有效地分析和处理文本,我们将其拆分为较小的块。这是使用 Langchain 的文本拆分器完成的,它通过将大文本划分为更小、更易于管理的段来帮助管理大文本。
文本分块:大文本字符串被划分为较小的块,每个块 1000 个字符,重叠 200 个字符,以确保在块之间保留上下文。
def get_chunks(text):text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200) # Initializing the text splitter with specified chunk size and overlapchunks = text_splitter.split_text(text) # Splitting the text into chunksreturn chunks # Returning the list of text chunks
一旦文本被分割成块,下一步就是通过将这些块转换为向量表示来使其可搜索。这就是FAISS库发挥作用的地方。
通过将文本块转换为向量,我们使系统能够在文本中执行快速有效的搜索。向量保存在本地,以便快速检索。
嵌入生成:每个文本块都使用 Spacy 嵌入转换为向量表示。这种数值表示对于相似性搜索和检索至关重要。
矢量存储:生成的向量使用 FAISS 库存储,这有助于快速索引和搜索。这使得文本数据库非常高效且可扩展。
embeddings = SpacyEmbeddings(model_name="en_core_web_sm") # Initializing Spacy embeddings with the specified modeldef vector_store(text_chunks):vector_store = FAISS.from_texts(text_chunks, embedding=embeddings) # Creating a FAISS vector store from text chunksvector_store.save_local("faiss_db") # Saving the vector store locally
该应用程序的核心是对话式 AI,它利用 OpenAI 强大的模型与处理过的 PDF 内容进行交互。
为了使聊天机器人能够根据 PDF 内容回答问题,我们使用 OpenAI 的 GPT 模型对其进行配置。此设置包括几个步骤:
模型初始化:我们初始化GPT模型,指定所需的模型变体(gpt-3.5-turbo)并设置温度参数以控制响应的随机性。较低的温度可确保更确定的答案。
提示模板:提示模板用于指导 AI 理解上下文并生成适当的响应。此模板包括系统说明、聊天历史记录的占位符、用户输入和座席暂存器。
代理创建:我们使用初始化的模型和提示模板创建代理。该代理将处理对话,调用必要的工具从 PDF 内容中获取相关信息。
工具集成:我们集成了帮助 AI 从存储在矢量数据库中的 PDF 文本中检索相关信息的工具。
代理执行:代理通过调用工具并处理用户的查询来执行对话。如果答案在提供的上下文中不可用,AI 会以“答案在上下文中不可用”进行响应,确保用户不会收到错误的信息。
def get_conversational_chain(tools, ques):# Initialize the language model with specified parametersllm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0, api_key="")# Define the prompt template for guiding the AI's responsesprompt = 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 inprovided context just say, "answer is not available in the context", don't provide the wrong answer""",),("placeholder", "{chat_history}"),("human", "{input}"),("placeholder", "{agent_scratchpad}"),])# Create the tool list and the agenttool = [tools]agent = create_tool_calling_agent(llm, tool, prompt)# Execute the agent to process the user's query and get a responseagent_executor = AgentExecutor(agent=agent, tools=tool, verbose=True)response = agent_executor.invoke({"input": ques})print(response)st.write("Reply: ", response['output'])
该应用程序允许用户通过简单的文本界面输入他们的问题。然后处理用户输入以从 PDF 数据库中检索相关信息。
def user_input(user_question):# Load the vector databasenew_db = FAISS.load_local("faiss_db", embeddings, allow_dangerous_deserialization=True)# Create a retriever from the vector databaseretriever = new_db.as_retriever()retrieval_chain = create_retriever_tool(retriever, "pdf_extractor", "This tool is to give answers to queries from the PDF")# Get the conversational chain to generate a responseget_conversational_chain(retrieval_chain, user_question)
后端准备就绪后,该应用程序使用 Streamlit 创建一个用户友好的界面。此界面有助于用户交互,包括上传 PDF 和查询聊天机器人。
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()
本教程演示了如何使用 Langchain、Streamlit 和其他强大的库构建复杂的多 PDF RAG 聊天机器人。通过执行这些步骤,您可以创建一个应用程序,该应用程序不仅可以处理和理解大型 PDF 文档,还可以以有意义的方式与用户交互。
为方便起见,以下是应用程序的完整代码:
import streamlit as stfrom PyPDF2 import PdfReaderfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_community.embeddings.spacy_embeddings import SpacyEmbeddingsfrom langchain_community.vectorstores import FAISSfrom langchain.tools.retriever import create_retriever_toolfrom dotenv import load_dotenvfrom langchain_anthropic import ChatAnthropicfrom langchain_openai import ChatOpenAI, OpenAIEmbeddingsfrom langchain.agents import AgentExecutor, create_tool_calling_agentimport osos.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 textdef get_chunks(text):text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)chunks = text_splitter.split_text(text)return chunksdef 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):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 inprovided 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 answers 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 run app.py参考资料:
https://blog.gopenai.com/building-a-rag-chatbot-using-langchain-and-streamlit-engage-with-your-pdfs-9163cec219e1
53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业
2026-07-01
提升 RAG 准确率全攻略 让你的 AI 知识库 真正靠谱起来!
2026-06-30
教程:如何用AutoRAG + Milvus避免RAG 与Agent 中出现串租问题
2026-06-30
知识库不是文件堆——我把RAG准确率从60%调到了92%
2026-06-30
本体论语义建设新思路,另类RAG来解决检索问题
2026-06-30
别把RAG当架构:Ontology(本体)才是Agent的业务世界
2026-06-29
PixelRAG:伯克利团队颠覆传统 RAG,用截图代替文本检索! 28 天狂揽 3000+ Star!
2026-06-29
腾讯WeKnora开源详解(三):检索引擎与生态集成
2026-06-29
腾讯开源WeKnora详解(二):知识库与对话核心能力
2026-04-06
2026-04-27
2026-04-23
2026-04-20
2026-04-09
2026-04-12
2026-04-22
2026-04-10
2026-05-14
2026-04-30
2026-06-23
2026-06-23
2026-06-15
2026-06-10
2026-06-10
2026-05-20
2026-05-18
2026-05-11
欢迎您使用【53AI 官方网站】(以下简称“本网站”或“我们”)。本《会员服务协议》(以下简称“本协议”)是您(以下简称“会员”或“用户”)与【深圳市博思协创网络科技有限公司】之间关于注册、登录及使用本网站会员服务所订立的法律协议。
在您注册或登录前,请务必审慎阅读、充分理解各条款内容,特别是免除或限制责任的条款、知识产权条款、争议解决条款等。此类条款将以加粗形式提示您注意。 当您通过微信公众号授权、手机验证码验证或其他方式成功登录本网站时,即视为您已完全理解并同意接受本协议的全部内容。
一、 定义
本网站:指由【深圳市博思协创网络科技有限公司】运营的,域名为【53ai.com】的网站及相关移动端页面。
会员服务:指本网站向注册会员提供的知识库文章查阅、内容检索及其他相关增值服务。
知识库内容:指本网站发布的包括但不限于文字、图表、数据、研究报告、行业分析等数字化内容资源。
二、 账号注册与登录
登录方式:本网站支持以下登录方式,您可根据实际情况选择:
微信公众号授权登录:您同意将您的微信OpenID信息授权给本网站,用于创建或关联会员账号。
手机验证码登录:您需提供真实有效的手机号码,并通过短信验证码完成身份验证与登录/注册。
账号安全:您的账号仅限您本人使用,禁止赠与、借用、租用、转让或售卖。因您保管不善导致的账号被盗、密码泄露等损失,由您自行承担。
实名认证:根据相关法律法规要求,我们可能要求您在特定功能下完成实名认证。如您拒绝提供,可能无法使用部分或全部服务。
未成年人保护:若您未满18周岁,请在法定监护人的陪同下阅读本协议,并在征得监护人同意后使用本服务。
三、 服务内容与规范
知识库查阅权限:会员登录后,有权按照其会员等级对应的权限范围,在线浏览、检索本网站知识库中的相关文章及内容。
服务变更:我们有权根据业务发展需要,调整、变更或终止部分服务内容,并将以网站公告、公众号消息等方式提前通知。
禁止行为:您在使用服务时不得实施以下行为:
利用技术手段批量爬取、下载、转存知识库内容;
将知识库内容用于商业目的或未经授权地向第三方传播;
干扰本网站正常运行或侵犯其他用户合法权益;
发布违法违规信息或从事违反公序良俗的活动。
四、 知识产权声明
权利归属:本网站知识库中的排版设计、软件代码等内容的知识产权均归【公司全称】或原权利人所有,受《中华人民共和国著作权法》等法律保护。
有限许可:本网站授予会员一项非独占、不可转让、不可转授权的普通许可,仅限于个人学习、研究之目的在线查阅知识库内容。
侵权追责:未经书面许可,任何单位或个人不得以任何形式复制、转载、摘编、镜像、汇编或以其他方式使用上述内容。一经发现,我们保留追究其法律责任的权利。
五、 个人信息保护
我们重视对您个人信息的保护。关于我们如何收集、使用、存储和保护您的个人信息,请单独阅读 《隐私政策》。
您通过微信公众号授权或手机号验证所提供的信息,我们将严格按照《个人信息保护法》的规定处理,仅用于身份识别、服务提供及安全验证等必要用途。
您可以随时通过网站设置或联系客服行使查阅、更正、删除个人信息及撤回授权同意的权利。
六、 免责声明
内容准确性:知识库内容仅供参考,不构成专业建议。我们不对其完整性、准确性、时效性作任何明示或暗示的保证,您应自行判断并承担使用风险。
不可抗力:因自然灾害、政策法规变化、网络故障、第三方平台接口异常(如微信接口维护、运营商短信通道故障)等不可抗力导致的服务中断或延迟,我们不承担违约责任。
第三方链接:本网站可能包含指向第三方网站的链接,该等网站的内容和服务不受我们控制,请您自行甄别风险。
七、 违约责任
如您违反本协议约定,我们有权视情节采取警告、限制功能、暂停服务、注销账号等措施,并保留要求赔偿损失的权利。
如因您的违约行为导致我们遭受行政处罚、第三方索赔或商誉损失,您应承担全部赔偿责任(包括但不限于罚款、赔偿金、律师费、公证费等)。
八、 法律适用与争议解决
本协议的订立、执行和解释均适用中华人民共和国大陆地区法律。
因本协议产生的或与本协议有关的任何争议,双方应友好协商解决;协商不成的,任何一方均可向【公司所在地】有管辖权的人民法院提起诉讼。
九、 其他
本协议构成双方就本服务达成的完整协议,取代此前任何口头或书面约定。
本协议任一条款被认定为无效或不可执行的,不影响其他条款的效力。
我们对本协议享有最终解释权,并在法律允许的范围内保留随时修改的权利。修改后的协议一经公布即生效,继续使用服务即视为同意修订内容。