PDF对话RAG应用开发实战

与大型 PDF 对话很酷。你可以与笔记、书籍和文档等聊天。这篇博文将帮助你构建一个基于 Multi RAG Streamlit 的 Web 应用程序,以通过对话式 AI 聊天机器人读取、处理和与 PDF 数据交互。以下是此应用程序工作原理的分步分解,使用简单的语言易于理解。

NSDT工具推荐Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器 - REVIT导出3D模型插件 - 3D模型语义搜索引擎 - AI模型在线查看 - Three.js虚拟轴心开发包 - 3D模型在线减面 - STL模型在线切割

1、使用必要的工具设置舞台

该应用程序首先导入各种强大的库:

  • Streamlit:用于创建 Web 界面。

  • PyPDF2:用于读取 PDF 文件的工具。

  • Langchain:一套用于自然语言处理和创建对话式 AI 的工具。

  • FAISS:用于高效搜索向量相似性的库,可用于在大型数据集中快速查找信息。

    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"

2、读取和处理 PDF 文件

我们应用程序中的第一个主要功能旨在读取 PDF 文件:

PDF 阅读器:当用户上传一个或多个 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

2、创建可搜索的文本数据库并进行嵌入

为了使文本可搜索,应用程序将文本块转换为矢量表示:

矢量存储:应用程序使用 FAISS 库将文本块转换为矢量,并在本地保存这些矢量。这种转换至关重要,因为它允许系统在文本中执行快速有效的搜索。

复制代码
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")

3、设置对话式 AI

此应用程序的核心是对话式 AI,它使用 OpenAI 的强大模型:

  • AI 配置:该应用程序使用 OpenAI 的 GPT 模型设置对话式 AI。此 AI 旨在根据其处理的 PDF 内容回答问题。

  • 对话链:AI 使用一组提示来理解上下文并为用户查询提供准确的响应。如果文本中没有问题的答案,AI 将被编程为以"上下文中没有答案"来响应,以确保用户不会收到错误的信息。

    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)

4、用户交互

后端准备就绪后,应用程序使用 Streamlit 创建用户友好的界面:

  • 用户界面:用户可以看到一个简单的文本输入框,他们可以在其中输入与 PDF 内容相关的问题。然后,应用程序会直接在网页上显示 AI 的响应。

  • 文件上传和处理:用户可以随时上传新的 PDF 文件。应用程序会实时处理这些文件,并使用新文本更新数据库,以供 AI 搜索。

    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")

5、流程图与完整代码

复制代码
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 run app.py

输出:


原文链接:PDF RAG应用开发实战 - BimAnt

相关推荐
优化控制仿真模型1 天前
【2026考研408】考研计算机408统考历年真题及答案解析PDF电子版(2009-2026年)
经验分享·pdf
南风微微吹1 天前
2026年5月教资面试结构化、试讲真题及答案汇总PDF(中小幼全)
面试·pdf
南风微微吹1 天前
2026年5月初级会计师考试真题试卷及答案解析完整版PDF
pdf
2501_907136821 天前
PDF格式电子发票合并A4纸打印
pdf·软件需求
优化控制仿真模型1 天前
【2026年】初中英语考纲词汇表(1600词)PDF电子版
经验分享·pdf
南风微微吹2 天前
最新国考《行测+申论》历年真题及答案解析电子版pdf(2000-2026年)
pdf
wujian83112 天前
豆包导出pdf方法
人工智能·ai·pdf·豆包·deepseek·ai导出鸭
俊哥工具2 天前
鼠标自动连点怎么设置?详细教学,简单易懂!
python·django·pdf·计算机外设·virtualenv·pygame
2601_950316062 天前
塞尔达攻略+塞尔达设定集+塞尔达传说攻略
游戏·pdf·电视盒子
SunnyDays10112 天前
Java 实现 PDF 附件的添加与删除:四种实用方法
java·pdf·附件