Langchain-Chatchat
概述
Langchain-Chatchat是一個基于ChatGLM大語言模型與Langchain應(yīng)用框架實現(xiàn),開源、可離線部署的檢索增強生成(RAG)大模型的本地知識庫問答應(yīng)用項目。
GitHub:https://github.com/chatchat-space/Langchain-Chatchat
實現(xiàn)原理
本項目實現(xiàn)原理如下圖所示,過程包括加載文件 -> 讀取文本 -> 文本分割 -> 文本向量化 -> 問句向量化 -> 在文本向量中匹配出與問句向量最相似的 top k個 -> 匹配出的文本作為上下文和問題一起添加到 prompt中 -> 提交給 LLM生成回答。
開發(fā)環(huán)境準備
軟件要求
使用Ubuntu系統(tǒng),其他系統(tǒng)可能出現(xiàn)系統(tǒng)兼容性問題
Linux Ubuntu 22.04.5 kernel version 6.7
最低要求
該要求僅針對標準模式,輕量模式使用在線模型,不需要安裝torch等庫,也不需要顯卡即可運行。
Python 版本: >= 3.8(很不穩(wěn)定), < 3.11
CUDA 版本: >= 12.1
推薦要求
開發(fā)者在以下環(huán)境下進行代碼調(diào)試,在該環(huán)境下能夠避免最多環(huán)境問題。
Python 版本 == 3.10.12
CUDA 版本: == 12.3
硬件要求
如果為了體驗使用該項目,可以使用線上模型,不需要太高的硬件要求。
如果想要順利在GPU運行本地模型的 int4 量化版本,至少需要以下的硬件配置
ChatGLM2-6B & LLaMA-7B
最低顯存要求: 7GB
推薦顯卡: RTX 3060, RTX 2060
LLaMA-13B
最低顯存要求: 11GB
推薦顯卡: RTX 2060 12GB, RTX 3060 12GB, RTX 3080, RTX A2000
Qwen-14B-Chat
最低顯存要求: 13GB
推薦顯卡: RTX 3090
LLaMA-30B
最低顯存要求: 22GB
推薦顯卡: RTX A5000, RTX 3090, RTX 4090, RTX 6000, Tesla V100, RTX Tesla P40
LLaMA-65B
最低顯存要求: 40GB
推薦顯卡: A100, A40, A6000
注意:
若使用 int8 推理,則顯存大致為 int4 推理要求的 1.5 倍
若使用 fp16 推理,則顯存大致為 int4 推理要求的 2.5 倍
數(shù)據(jù)僅為估算,實際情況以 nvidia-smi 占用為準。
同時,Embedding 模型將會占用 1-2G 的顯存,歷史記錄最多會占用數(shù) G 顯存,因此,需要多冗余一些顯存。
內(nèi)存最低要求: 內(nèi)存要求至少應(yīng)該比模型運行的顯存大。
部署
拉取倉庫
git clone https://github.com/chatchat-space/Langchain-Chatchat.git
# 進入目錄
cd Langchain-Chatchat
創(chuàng)建虛擬環(huán)境
創(chuàng)建一個虛擬環(huán)境,使項目與項目間進行軟件版本隔離
conda create -n chat python=3.10
# 激活使用虛擬環(huán)境
conda activate chat
安裝全部依賴
在虛擬環(huán)境內(nèi)安裝項目的依賴
pip install -r requirements.txt
pip install -r requirements_api.txt
pip install -r requirements_webui.txt
默認依賴包括基本運行環(huán)境(FAISS向量庫)。如果要使用 milvus/pg_vector 等向量庫,請將 requirements.txt 中相應(yīng)依賴取消注釋再安裝。
初始化配置文件
python copy_config_example.py
腳本將會將所有config目錄下的配置文件樣例復(fù)制一份到config目錄下,方便開發(fā)者進行配置。 接著,開發(fā)者可以根據(jù)自己的需求,對配置文件進行修改。
basic_config.py:基礎(chǔ)配置項:配置記錄日志的格式和儲存路徑,通常不需要修改。
kb_config.py:數(shù)據(jù)庫配置:配置分詞器、知識庫、向量數(shù)據(jù)庫等信息
model_config.py:模型配置項:包含本地LLM模型、本地Embeddings模型、在線LLM模型API的相關(guān)配置
prompt_config.py:提示詞配置項:提示詞配置分為三個板塊,分別對應(yīng)三種聊天類型:基礎(chǔ)的對話提示詞、與知識庫對話的提示詞、與Agent對話的提示詞。
server_config.py:服務(wù)和端口配置項:不需要進行大量的修改,僅需確保對應(yīng)的端口打開,并不互相沖突即可。server_config.py中的配置優(yōu)先于startup.py中的默認值,注意避免配置文件覆蓋
模型下載
模型下載取決于自己的網(wǎng)絡(luò)情況,這里需要提前下載THUDM/chatglm2-6b
與BAAI/bge-large-zh
到本地,然后在model_config.py
中配置
1.若網(wǎng)絡(luò)良好(全球暢通無阻)則完全不需要先下載模型,在執(zhí)行過程中會自動下載相關(guān)模型。
2.如果網(wǎng)絡(luò)存在問題,則可以事先下載好需要的模型,然后在
model_config.py
文件中配置,具體配置參考異常3中的處理辦法
注意:
Windows環(huán)境下,會默認自動將該模型下載到
C:\Users\Admin\.cache\torch\sentence_transformers
目錄下,若下載失敗,參考異常3中的處理辦法
初始化知識庫
第一次運行本項目,知識庫尚未建立,或者配置文件中的知識庫類型、嵌入模型發(fā)生變化,需要以下命令初始化或重建知識庫:
python init_database.py --recreate-vs
如果已經(jīng)有創(chuàng)建過知識庫,可以先執(zhí)行以下命令創(chuàng)建或更新數(shù)據(jù)庫表:
$ python init_database.py --create-tables
第一次使用時,會自動下載BAAI/bge-large-zh模型,用于知識庫的初始化構(gòu)建
(chat) root@master:~/Langchain-Chatchat# python init_database.py --recreate-vs
recreating all vector stores
2023-12-20 21:40:48,647 - faiss_cache.py[line:80] - INFO: loading vector store in 'samples/vector_store/bge-large-zh' from disk.
2023-12-20 21:40:48,999 - SentenceTransformer.py[line:66] - INFO: Load pretrained SentenceTransformer: /root/models/bge-large-zh
Batches: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 1.80it/s]
2023-12-20 21:40:51,466 - loader.py[line:54] - INFO: Loading faiss with AVX2 support.
2023-12-20 21:40:51,751 - loader.py[line:56] - INFO: Successfully loaded faiss with AVX2 support.
2023-12-20 21:40:51,761 - faiss_cache.py[line:80] - INFO: loading vector store in 'samples/vector_store/bge-large-zh' from disk.
Batches: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 72.05it/s]
2023-12-20 21:40:51,783 - utils.py[line:286] - INFO: RapidOCRLoader used for /root/onethingai-tmp/Langchain-Chatchat/knowledge_base/samples/content/llm/img/分布式訓(xùn)練技術(shù)原理-幕布圖片-124076-270516.jpg
2023-12-20 21:40:51,784 - utils.py[line:286] - INFO: RapidOCRLoader used for /root/onethingai-tmp/Langchain-Chatchat/knowledge_base/samples/content/llm/img/分布式訓(xùn)練技術(shù)原理-幕布圖片-20096-279847.jpg
2023-12-20 21:40:51,785 - utils.py[line:286] - INFO: RapidOCRLoader used for /root/onethingai-tmp/Langchain-Chatchat/knowledge_base/samples/content/llm/img/分布式訓(xùn)練技術(shù)原理-幕布圖片-220157-552735.jpg
2023-12-20 21:40:51,785 - utils.py[line:286] - INFO: RapidOCRLoader used for /root/onethingai-tmp/Langchain-Chatchat/knowledge_base/samples/content/llm/img/分布式訓(xùn)練技術(shù)原理-幕布圖片-36114-765327.jpg
2023-12-20 21:40:51,786 - utils.py[line:286] - INFO: RapidOCRLoader used
Batches: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 6/6 [00:01<00:00, 3.43it/s]
正在將 samples//root/onethingai-tmp/Langchain-Chatchat/knowledge_base/samples/content/test_files/test.txt 添加到向量庫,共包含59條文檔████████████████████████████████████▋ | 5/6 [00:01<00:00, 3.05it/s]
Batches: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:00<00:00, 2.41it/s]
正在將 samples//root/onethingai-tmp/Langchain-Chatchat/knowledge_base/samples/content/llm/img/大模型推理優(yōu)化策略-幕布圖片-930255-616209.jpg 添加到向量庫,共包含3條文檔███████████████████████████████████| 2/2 [00:00<00:00, 2.52it/s]
Batches: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 43.48it/s]
正在將 samples//root/onethingai-tmp/Langchain-Chatchat/knowledge_base/samples/content/llm/img/大模型推理優(yōu)化策略-幕布圖片-789705-122117.jpg 添加到向量庫,共包含1條文檔 | 0/1 [00:00<?, ?it/s]
Batches: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 1/1 [00:00<00:00, 63.58it/s]
RapidOCRPDFLoader context page index: 7: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 8/8 [00:48<00:00, 6.11s/it]
文檔切分示例:page_content='See discussions, stats, and author profiles for this publication at: https://www.researchgate.net/publication/372669736\nCreating Large Language Model Applications Utilizing LangChain: A Primer on\nDeveloping LLM Apps Fast\nArticle\xa0\xa0in\xa0\xa0International Conference on Applied Engineering and Natural Sciences · July 2023\nDOI: 10.59287/icaens.1127\nCITATIONS\n0\nREADS\n47\n2 authors:\nSome of the authors of this publication are also working on these related projects:\nTHALIA: Test Harness for the Assessment of Legacy Information Integration Approaches View project\nAnalysis of Feroresonance with Signal Processing Technique View project\nOguzhan Topsakal' metadata={'source': '/root/onethingai-tmp/Langchain-Chatchat/knowledge_base/samples/content/test_files/langchain.pdf'}
正在將 samples//root/onethingai-tmp/Langchain-Chatchat/knowledge_base/samples/content/test_files/langchain.pdf 添加到向量庫,共包含52條文檔
Batches: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 2/2 [00:00<00:00, 3.70it/s]
2023-12-20 21:44:07,719 - faiss_cache.py[line:24] - INFO: 已將向量庫 ('samples', 'bge-large-zh') 保存到磁盤
總計用時: 0:03:19.085059
啟動項目
啟動項目整個過程中,坑也比較多,參考異常2與異常3中的處理辦法。
一鍵啟動腳本 startup.py, 一鍵啟動所有 Fastchat 服務(wù)、API 服務(wù)、WebUI 服務(wù)
python startup.py -a
啟動時,如果沒用在model_config.py
中配置配置模型信息,則會自動模型下載THUDM/chatglm3-6b
到本地使用
==============================Langchain-Chatchat Configuration==============================
操作系統(tǒng):Linux-6.1.56-1.2.3-x86_64-with-glibc2.35.
python版本:3.10.13 | packaged by conda-forge | (main, Oct 26 2023, 18:07:37) [GCC 12.3.0]
項目版本:v0.2.8
langchain版本:0.0.344. fastchat版本:0.2.34
當前使用的分詞器:ChineseRecursiveTextSplitter
當前啟動的LLM模型:['chatglm3-6b', 'zhipu-api', 'openai-api'] @ cuda
{'device': 'cuda',
'host': '0.0.0.0',
'infer_turbo': False,
'model_path': '/root/models/chatglm3-6b',
'model_path_exists': True,
'port': 20002}
{'api_key': '',
'device': 'auto',
'host': '0.0.0.0',
'infer_turbo': False,
'online_api': True,
'port': 21001,
'provider': 'ChatGLMWorker',
'version': 'chatglm_turbo',
'worker_class': <class 'server.model_workers.zhipu.ChatGLMWorker'>}
{'api_base_url': 'https://api.openai.com/v1',
'api_key': '',
'device': 'auto',
'host': '0.0.0.0',
'infer_turbo': False,
'model_name': 'gpt-3.5-turbo',
'online_api': True,
'openai_proxy': '',
'port': 20002}
當前Embbedings模型: bge-large-zh @ cuda
==============================Langchain-Chatchat Configuration==============================
2023-12-20 21:44:16,058 - startup.py[line:650] - INFO: 正在啟動服務(wù):
2023-12-20 21:44:16,058 - startup.py[line:651] - INFO: 如需查看 llm_api 日志,請前往 /root/Langchain-Chatchat/logs
2023-12-20 21:44:20 | INFO | model_worker | Register to controller
2023-12-20 21:44:20 | ERROR | stderr | INFO: Started server process [8455]
2023-12-20 21:44:20 | ERROR | stderr | INFO: Waiting for application startup.
2023-12-20 21:44:20 | ERROR | stderr | INFO: Application startup complete.
2023-12-20 21:44:20 | ERROR | stderr | INFO: Uvicorn running on http://0.0.0.0:20000 (Press CTRL+C to quit)
2023-12-20 21:44:21 | INFO | model_worker | Loading the model ['chatglm3-6b'] on worker 6c239f49 ...
Loading checkpoint shards: 0%| | 0/7 [00:00<?, ?it/s]
Loading checkpoint shards: 14%|████████████████████████▎ | 1/7 [00:02<00:14, 2.42s/it]
Loading checkpoint shards: 29%|████████████████████████████████████████████████▌ | 2/7 [00:04<00:12, 2.42s/it]
Loading checkpoint shards: 43%|████████████████████████████████████████████████████████████████████████▊ | 3/7 [00:06<00:07, 1.98s/it]
Loading checkpoint shards: 57%|█████████████████████████████████████████████████████████████████████████████████████████████████▏ | 4/7 [00:08<00:05, 1.91s/it]
Loading checkpoint shards: 71%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▍ | 5/7 [00:10<00:04, 2.09s/it]
Loading checkpoint shards: 86%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████▋ | 6/7 [00:12<00:02, 2.19s/it]
Loading checkpoint shards: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 7/7 [00:14<00:00, 1.95s/it]
Loading checkpoint shards: 100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 7/7 [00:14<00:00, 2.05s/it]
2023-12-20 21:44:35 | ERROR | stderr |
2023-12-20 21:44:38 | INFO | model_worker | Register to controller
INFO: Started server process [9192]
INFO: Waiting for application startup.
INFO: Application startup complete.
ERROR: [Errno 98] error while attempting to bind on address ('0.0.0.0', 7861): address already in use
INFO: Waiting for application shutdown.
INFO: Application shutdown complete.
==============================Langchain-Chatchat Configuration==============================
操作系統(tǒng):Linux-6.1.56-1.2.3-x86_64-with-glibc2.35.
python版本:3.10.13 | packaged by conda-forge | (main, Oct 26 2023, 18:07:37) [GCC 12.3.0]
項目版本:v0.2.8
langchain版本:0.0.344. fastchat版本:0.2.34
當前使用的分詞器:ChineseRecursiveTextSplitter
當前啟動的LLM模型:['chatglm3-6b', 'zhipu-api', 'openai-api'] @ cuda
{'device': 'cuda',
'host': '0.0.0.0',
'infer_turbo': False,
'model_path': '/root/models/chatglm3-6b',
'model_path_exists': True,
'port': 20002}
{'api_key': '',
'device': 'auto',
'host': '0.0.0.0',
'infer_turbo': False,
'online_api': True,
'port': 21001,
'provider': 'ChatGLMWorker',
'version': 'chatglm_turbo',
'worker_class': <class 'server.model_workers.zhipu.ChatGLMWorker'>}
{'api_base_url': 'https://api.openai.com/v1',
'api_key': '',
'device': 'auto',
'host': '0.0.0.0',
'infer_turbo': False,
'model_name': 'gpt-3.5-turbo',
'online_api': True,
'openai_proxy': '',
'port': 20002}
當前Embbedings模型: bge-large-zh @ cuda
服務(wù)端運行信息:
OpenAI API Server: http://127.0.0.1:20000/v1
Chatchat API Server: http://127.0.0.1:7861
Chatchat WEBUI Server: http://0.0.0.0:8501
==============================Langchain-Chatchat Configuration==============================
Collecting usage statistics. To deactivate, set browser.gatherUsageStats to False.
You can now view your Streamlit app in your browser.
URL: http://0.0.0.0:8501
訪問Web UI
Web UI地址:http://127.0.0.1:8501
API服務(wù)
不是一鍵啟動,則可以單獨啟動API服務(wù):
python server/api.py
訪問:http://0.0.0.0:7861/docs
Web UI服務(wù)
不是一鍵啟動,則可以單獨啟動Web UI服務(wù):
streamlit run webui.py
訪問:http://localhost:8501/
使用
對話功能
可以選擇本地模型,線上模型,然后進行對話
知識庫管理
可以新建知識庫,上傳相關(guān)資料信息
上傳后會建立向量數(shù)據(jù)庫
進行提問,回答基于知識庫進行回答
文件對話
上傳一個報銷制度文件,然后提問
搜索引擎問答
異常集合
異常1
場景:
初始化配置文件
python init_database.py --recreate-vs
問題:
cannot import name 'Doc' from 'typing_extensions'
解決:
因為安裝的typing_extensions版本不正確,需要重新安裝
pip install typing_extensions==4.8.0
異常2
場景:
啟動項目
python startup.py -a
問題:
OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.
OMP: Hint This means that multiple copies of the OpenMP runtime have been linked into the program. That is dangerous, since it can degrade performance or cause incorrect results. The best thing to do is to ensure that only a singl
e OpenMP runtime is linked into the process, e.g. by avoiding static linking of the OpenMP runtime in any library. As an unsafe, unsupported, undocumented workaround you can set the environment variable KMP_DUPLICATE_LIB_OK=TRUE t
o allow the program to continue to execute, but that may cause crashes or silently produce incorrect results. For more information, please see http://www.intel.com/software/products/support/.
解決1:
這里使用Anaconda創(chuàng)建虛擬環(huán)境,其中有
ibiomp5md.dll
文件,重命名以備份該文件,如:libiomp5md.dll.back
解決2:
在
startup.py
文件上方設(shè)置環(huán)境變量,保證前后順序
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
異常3
場景:
啟動項目過程中
python startup.py -a
問題:
| OSError: We couldn't connect to 'https://huggingface.co' to load this file, couldn't find it in the cached files and it looks like THUDM/chatglm3-6b is not the path to a directory containing
a file named config.json.
解決:
默認使用的LLM 模型 THUDM/ChatGLM3-6B 與 Embedding 模型BAAI/bge-large-zh,會遠程連接模型網(wǎng)站。這里使用魔法也不得行,不知為啥,具體模型網(wǎng)站能訪問的。
下載LLM 模型THUDM/ChatGLM3-6B
與Embedding模型BAAI/bge-large-zh
1.訪問https://huggingface.co/BAAI/bge-large-zh
下載
2.訪問https://huggingface.co/THUDM/chatglm3-6b
下載文章來源:http://www.zghlxwxcb.cn/news/detail-758027.html
然后修改
configs/model_config.py
文件,指定模型存放位置與使用模型名稱,需保證存放模型目錄下的模型文件名與model_config.py
文件使用的名稱一致。文章來源地址http://www.zghlxwxcb.cn/news/detail-758027.html
# 統(tǒng)一存放模型位置
MODEL_ROOT_PATH = "../../../models"
# 選用的 Embedding 名稱
EMBEDDING_MODEL = "bge-large-zh"
# 要運行的LLM名稱,可以包括本地模型和在線模型
LLM_MODELS = ["chatglm3-6b", "zhipu-api", "openai-api"]
MODEL_PATH = {
"embed_model": {
"ernie-tiny": "nghuyong/ernie-3.0-nano-zh",
"ernie-base": "nghuyong/ernie-3.0-base-zh",
"text2vec-base": "shibing624/text2vec-base-chinese",
"text2vec": "GanymedeNil/text2vec-large-chinese",
"text2vec-paraphrase": "shibing624/text2vec-base-chinese-paraphrase",
"text2vec-sentence": "shibing624/text2vec-base-chinese-sentence",
"text2vec-multilingual": "shibing624/text2vec-base-multilingual",
"text2vec-bge-large-chinese": "shibing624/text2vec-bge-large-chinese",
"m3e-small": "moka-ai/m3e-small",
"m3e-base": "moka-ai/m3e-base",
"m3e-large": "moka-ai/m3e-large",
"bge-small-zh": "BAAI/bge-small-zh",
"bge-base-zh": "BAAI/bge-base-zh",
# "bge-large-zh": "BAAI/bge-large-zh",
# 如果模型目錄名稱和 MODEL_PATH 中的 key 或 value 相同,程序會自動檢測加載,無需修改 MODEL_PATH 中的路徑。
"bge-large-zh": "bge-large-zh",
"bge-large-zh-noinstruct": "BAAI/bge-large-zh-noinstruct",
"bge-base-zh-v1.5": "BAAI/bge-base-zh-v1.5",
"bge-large-zh-v1.5": "BAAI/bge-large-zh-v1.5",
"piccolo-base-zh": "sensenova/piccolo-base-zh",
"piccolo-large-zh": "sensenova/piccolo-large-zh",
"nlp_gte_sentence-embedding_chinese-large": "damo/nlp_gte_sentence-embedding_chinese-large",
"text-embedding-ada-002": "your OPENAI_API_KEY",
},
"llm_model": {
# 以下部分模型并未完全測試,僅根據(jù)fastchat和vllm模型的模型列表推定支持
# "chatglm2-6b": "THUDM/chatglm2-6b",
# 如果模型目錄名稱和 MODEL_PATH 中的 key 或 value 相同,程序會自動檢測加載,無需修改 MODEL_PATH 中的路徑。
"chatglm2-6b": "chatglm2-6b",
"chatglm2-6b-32k": "THUDM/chatglm2-6b-32k",
"chatglm3-6b": "THUDM/chatglm3-6b",
"chatglm3-6b-32k": "THUDM/chatglm3-6b-32k",
"chatglm3-6b-base": "THUDM/chatglm3-6b-base",
},
到了這里,關(guān)于Langchain-Chatchat大語言模型本地知識庫的踩坑、部署、使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!