AI知识库

53AI知识库

学习大模型的前沿技术与行业应用场景


RAG 聊天机器人:用 Langchain 和 Streamlit开启与 PDF 的智能对话
发布日期:2024-08-14 08:44:08 浏览次数: 1733


与大量 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 Langchain
import 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 document        for page in pdf_reader.pages:  # Iterating through each page in the PDF            text += page.extract_text()  # Extracting and appending the text from the current page    return 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 overlap    chunks = text_splitter.split_text(text)  # Splitting the text into chunks    return 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 chunks    vector_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 parameters    llm = ChatOpenAI(model_name="gpt-3.5-turbo", temperature=0, api_key="")        # Define the prompt template for guiding the AI's responses    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}"),        ]    )        # Create the tool list and the agent    tool = [tools]    agent = create_tool_calling_agent(llm, tool, prompt)        # Execute the agent to process the user's query and get a response    agent_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 database    new_db = FAISS.load_local("faiss_db", embeddings, allow_dangerous_deserialization=True)        # Create a retriever from the vector database    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 the conversational chain to generate a response    get_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_agent
import 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 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 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

参考资料:

  1.  https://blog.gopenai.com/building-a-rag-chatbot-using-langchain-and-streamlit-engage-with-your-pdfs-9163cec219e1


53AI,企业落地应用大模型首选服务商

产品:大模型应用平台+智能体定制开发+落地咨询服务

承诺:先做场景POC验证,看到效果再签署服务协议。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

与创始人交个朋友

回到顶部

 
扫码咨询