用通俗易懂的方式讲解:使用 Mistral-7B 和 Langchain 搭建基于PDF文件的聊天机器人

在本文中,使用LangChain、HuggingFaceEmbeddings和HuggingFace的Mistral-7B LLM创建一个简单的Python程序,可以从任何pdf文件中回答问题。

一、LangChain简介

LangChain是一个在语言模型之上开发上下文感知应用程序的框架。LangChain使用带prompt和few-shot示例的LLM来提供相关响应和推理。LangChain擅长文档问答、聊天机器人、分析结构化数据等。LangChain提供方便处理LLM的抽象组件及其实现,还为更高级别的任务提供组件Chain。

安装langchain:

bash 复制代码
pip install langchain

LangChain中的模块 :Model I/O(模型I/O) , Retrieval(检索) , Chains(链 ), Agents(代理 ), Memory(记忆), Callbacks(回调)

1.1 模型I/O模块

模型I/O是应用程序的核心元素。使用LangChain,可以使用任何大语言模型。这个接口需要三个组件:大语言模型 、提示 和输出解析器。

LangChain提供了许多类 和函数 来构建提示,为各种任务提供现成的**提示模板,**也可以自定义提示模板。

LangChain可以使用LLM,也可以使用以聊天消息列表为输入并返回聊天聊天消息。它可以与许多LLM一起工作,包括OpenAI LLMs和开源LLM。

输出解析器用于构建从LLM接收的响应,PydanticOutputParser是LangChain中输出解析器的主要类型。

1.2 检索模块

检索模块实现了检索增强生成(RAG),可以访问大模型训练数据之外的用户私有数据。检索步骤包括以下几步:加载数据、转换数据、创建或获取嵌入、存储嵌入和检索嵌入。LangChain拥有大约100个文档加载器,可以读取主要的文档格式,比如CSV、HTML、pdf、代码等。它可以使用不同的算法转换数据。LangChain集成了超过25个嵌入模型和超过50家向量数据库。

1.3 链条模块

复杂的应用程序通常需要组合多个LLM来完成。LangChain提供了Chain功能,可以集成多个LLM,Chain也可以调用其他Chain。

1.4 代理模块

代理也是一种Chain,负责决定下一步动作。代理由一个语言模型和一个提示组成,它需要以下输入:可用工具列表 、用户输入和历史执行信息(如果有的话)。代理cals的功能被称为"工具"。代理使用LLM来决定要采取的操作和顺序。操作包括------使用工具,观察工具的输出,向用户返回响应。

1.5 记忆模块

记忆模块使系统能够记住过去的信息,这在对话机器人中非常重要。

1.6 回调模块

回调机制允许用户使用API的"回调"参数返回LLM应用程序不同阶段的信息,比如用于日志记录、监控、流式传输等。

二、Mistral-7B

Mistral-7B是一个强大的语言模型(目前是开源的),具有73亿个参数,性能优于很多参数量更高的大模型。它可以下载以供离线使用,也可以在云中使用或从HuggingFace下载。使用langchain中的HuggingFaceHub,可以使用以下代码加载并使用Mistral-7B:

python 复制代码
repo_id = "mistralai/Mistral-7B-v0.1"
llm = HuggingFaceHub(huggingfacehub_api_token='your huggingface access token here', 
                     repo_id=repo_id, model_kwargs={"temperature":0.2, "max_new_tokens":50})

三、HuggingFace Embedding

在处理文本、图像、音频、视频、文档等数据时,通常首先会进行embedding把他们表示成数字类型,这样便于神经网络处理,embedding不仅仅是一种数字表示,它也可以捕捉数据的上下文语义信息。

HuggingFace提供了Sentence Transformers模型可以进行embedding,安装如下所示:

bash 复制代码
pip install -U sentence-transformers

然后使用它加载一个预先训练好的模型来对文本句子进行编码。

四、chroma向量存储

chroma是一个开源的嵌入数据库(矢量存储),用于创建、存储、检索和进行嵌入的语义搜索。安装如下:

bash 复制代码
pip install chroma

它允许用户连接到chroma客户端,创建一个集合,将带有元数据和id的文档添加到集合(此步骤创建嵌入),然后查询此集合(语义检索)。

五、pypdf 库

pypdf库可以读取、拆分、合并、裁剪、转换pdf文件的页面,添加自定义数据,更改查看选项,为pdf文件添加密码,从pdf文件中检索文本和元数据。安装如下所示:

bash 复制代码
pip install pypdf

要将pypdf与AES加密或解密一起使用,请安装额外的依赖项:

bash 复制代码
pip install pypdf[crypto]

六、实现代码

bash 复制代码
# Install dependencies
!pip install huggingface_hub
!pip install chromadb
!pip install langchain
!pip install pypdf
!pip install sentence-transformers
python 复制代码
# import required libraries
from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import HuggingFaceEmbeddings
from langchain.llms import HuggingFaceHub
from langchain.vectorstores import Chroma
from langchain.chains import ConversationalRetrievalChain
python 复制代码
# Load the pdf file and split it into smaller chunks
loader = PyPDFLoader('report.pdf')
documents = loader.load()

# Split the documents into smaller chunks 
text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
texts = text_splitter.split_documents(documents)
python 复制代码
# We will use HuggingFace embeddings 
embeddings = HuggingFaceEmbeddings()
python 复制代码
#Using Chroma vector database to store and retrieve embeddings of our text
db = Chroma.from_documents(texts, embeddings)
retriever = db.as_retriever(search_kwargs={'k': 2})
python 复制代码
# We are using Mistral-7B for this question answering 
repo_id = "mistralai/Mistral-7B-v0.1"
llm = HuggingFaceHub(huggingfacehub_api_token='your huggingface access token here', 
                     repo_id=repo_id, model_kwargs={"temperature":0.2, "max_new_tokens":50})
python 复制代码
# Create the Conversational Retrieval Chain
qa_chain = ConversationalRetrievalChain.from_llm(llm, retriever,return_source_documents=True)
python 复制代码
#We will run an infinite loop to ask questions to LLM and retrieve answers untill the user wants to quit
import sys
chat_history = []
while True:
    query = input('Prompt: ')
    #To exit: use 'exit', 'quit', 'q', or Ctrl-D.",
    if query.lower() in ["exit", "quit", "q"]:
        print('Exiting')
        sys.exit()
    result = qa_chain({'question': query, 'chat_history': chat_history})
    print('Answer: ' + result['answer'] + '\n')
    chat_history.append((query, result['answer']))

至此,基于PDF的聊天机器人就搭建好了,你可以从一个长而难的pdf中回答你的所有问题。Just do it!

通俗易懂讲解大模型系列

技术交流

建了AIGC大模型技术交流群! 想要学习、技术交流、获取如下原版资料的同学,可以直接加微信号:mlc2060。加的时候备注一下:研究方向 +学校/公司+CSDN,即可。然后就可以拉你进群了。

方式①、微信搜索公众号:机器学习社区 ,后台回复:加群

方式②、添加微信号:mlc2060,备注:来自CSDN + 技术交流

参考文献:

1 https://medium.com/@nimritakoul01/chat-with-your-pdf-files-using-mistral-7b-and-langchain-f3be9363301c

2 https://colab.research.google.com/corgiredirector?site=https%3A%2F%2Fmedium.com%2F%40woyera%2Fhow-to-chat-with-your-pdf-using-python-llama-2-41df80c4e674

3 https://www.shakudo.io/blog/build-pdf-bot-open-source-llms

相关推荐
Thanks_ks36 分钟前
AI Agent 开发入门:用 Function Calling 让大模型学会 “动手干活”,附订单查询机器人实战
python·ai·大模型·openai·agent·通义千问·mcp
硅谷秋水6 小时前
面向精确到达任务的机器人-对齐3D高斯溅射方法——基于腕部-相机VLA策略
数码相机·机器学习·计算机视觉·3d·机器人
Dawson Zhu9 小时前
【模型量化⑦】W4A8与GPTQ-Int4:极限压缩与MLC-LLM部署实战
人工智能·语言模型·架构·aigc·agi
天树星智源10 小时前
KV 剪枝的同一个误差,模型确定时只改 1.4% 的 token,不确定时改 65%:接上不确定性,AIME25 端到端快 1.27 倍
人工智能·大模型
科研邪修法19 小时前
PDF新增页面文字与文本批注怎么区分?以双版本培训讲义为例
前端·css·pdf
ComPDFKit20 小时前
RAG 回答只显示 PDF 文件名?用 Python 保留引用页码
开发语言·python·pdf·rag
Csvn21 小时前
如果明天供应商涨价 3 倍?三层解耦,换模型只改一行配置(C05)
人工智能·aigc·agent
zhuangzhao11921 小时前
第一性原理大模型课程 · 第 21 课:从 Prompt 到 Agent:四件套、错误累积与 ReAct 手算
大模型·react·ai agent·错误累积·大模型课程
YIAN1 天前
从 LangChain 到 DeepAgents:手把手拆解 createAgent、Middleware 与复杂 Agent
javascript·langchain·deepseek
科研邪修法1 天前
固定列宽PDF表格改字:文本边界、单位字段与修改前后复核
pdf