mirror of
https://github.com/RYDE-WORK/Langchain-Chatchat.git
synced 2026-02-01 20:14:03 +08:00
commit
03edc3e501
4
.gitignore
vendored
4
.gitignore
vendored
@ -173,4 +173,8 @@ cython_debug/
|
||||
.pytest_cache
|
||||
.DS_Store
|
||||
|
||||
# Test File
|
||||
test.py
|
||||
configs/*.py
|
||||
|
||||
|
||||
|
||||
@ -8,7 +8,7 @@
|
||||
基于 ChatGLM 等大语言模型与 Langchain 等应用框架实现,开源、可离线部署的检索增强生成(RAG)大模型知识库项目。
|
||||
|
||||
⚠️`0.2.10`将会是`0.2.x`系列的最后一个版本,`0.2.x`系列版本将会停止更新和技术支持,全力研发具有更强应用性的 `Langchain-Chatchat 0.3.x`。
|
||||
|
||||
`0.2.10` 的后续 bug 修复将会直接推送到`master`分支,而不在进行版本更新。
|
||||
---
|
||||
|
||||
## 目录
|
||||
@ -52,10 +52,11 @@ OpenAI GPT API 的调用,并将在后续持续扩充对各类模型及模型 A
|
||||
|
||||
🚩 本项目未涉及微调、训练过程,但可利用微调或训练对本项目效果进行优化。
|
||||
|
||||
🌐 [AutoDL 镜像](https://www.codewithgpu.com/i/chatchat-space/Langchain-Chatchat/Langchain-Chatchat) 中 `v0.2.10`
|
||||
🌐 [AutoDL 镜像](https://www.codewithgpu.com/i/chatchat-space/Langchain-Chatchat/Langchain-Chatchat) 中 `0.2.10`
|
||||
|
||||
版本所使用代码已更新至本项目 `v0.2.10` 版本。
|
||||
|
||||
🐳 [Docker 镜像](registry.cn-beijing.aliyuncs.com/chatchat/chatchat:0.2.6) 已经更新到 ```0.2.7``` 版本。
|
||||
🐳 [Docker 镜像](registry.cn-beijing.aliyuncs.com/chatchat/chatchat:0.2.7) 已经更新到 ```0.2.7``` 版本。
|
||||
|
||||
🌲 一行命令运行 Docker :
|
||||
|
||||
@ -197,4 +198,4 @@ $ python startup.py -a
|
||||
|
||||
<img src="img/official_wechat_mp_account.png" alt="二维码" width="300" />
|
||||
|
||||
🎉 Langchain-Chatchat 项目官方公众号,欢迎扫码关注。
|
||||
🎉 Langchain-Chatchat 项目官方公众号,欢迎扫码关注。
|
||||
@ -9,7 +9,8 @@ A LLM application aims to implement knowledge and search engine based QA based o
|
||||
LLM API.
|
||||
|
||||
⚠️`0.2.10` will be the last version of the `0.2.x` series. The `0.2.x` series will stop updating and technical support,
|
||||
and strive to develop `Langchain-Chachat 0.3.x with stronger applicability. `.
|
||||
and strive to develop `Langchain-Chachat 0.3.x` with stronger applicability.
|
||||
Subsequent bug fixes for `0.2.10` will be pushed directly to the `master` branch without version updates.
|
||||
|
||||
|
||||
---
|
||||
@ -61,7 +62,7 @@ The main process analysis from the aspect of document process:
|
||||
🚩 The training or fine-tuning are not involved in the project, but still, one always can improve performance by do
|
||||
these.
|
||||
|
||||
🌐 [AutoDL image](https://www.codewithgpu.com/i/chatchat-space/Langchain-Chatchat/Langchain-Chatchat) is supported, and in v13 the codes are update to v0.2.9.
|
||||
🌐 [AutoDL image](https://www.codewithgpu.com/i/chatchat-space/Langchain-Chatchat/Langchain-Chatchat) is supported, and in `0.2.10` the codes are update to v0.2.10.
|
||||
|
||||
🐳 [Docker image](registry.cn-beijing.aliyuncs.com/chatchat/chatchat:0.2.7) is supported to 0.2.7
|
||||
|
||||
@ -191,7 +192,7 @@ please refer to the [Wiki](https://github.com/chatchat-space/Langchain-Chatchat/
|
||||
|
||||
### WeChat Group
|
||||
|
||||
<img src="img/qr_code_87.jpg" alt="二维码" width="300" height="300" />
|
||||
<img src="img/qr_code_88.jpg" alt="二维码" width="300" height="300" />
|
||||
|
||||
### WeChat Official Account
|
||||
|
||||
|
||||
66
README_ja.md
66
README_ja.md
@ -3,9 +3,14 @@
|
||||
🌍 [中文文档](README.md)
|
||||
🌍 [READ THIS IN ENGLISH](README_en.md)
|
||||
|
||||
📃 **LangChain-Chatchat** (旧名 Langchain-ChatGLM):
|
||||
📃 **LangChain-Chatchat** (旧名 Langchain-ChatGLM)
|
||||
|
||||
LLM アプリケーションは、Langchain とオープンソースまたはリモートの LLM API に基づいて、知識と検索エンジンベースの QA を実装することを目的としています。
|
||||
ChatGLM などの大規模な言語モデルや Langchain などのアプリケーション フレームワークに基づいた、オープン
|
||||
ソースのオフライン展開可能な検索拡張生成 (RAG) 大規模モデル ナレッジ ベース プロジェクトです。
|
||||
|
||||
⚠️`0.2.10` は `0.2.x` シリーズの最終バージョンとなり、`0.2.x`
|
||||
シリーズはアップデートと技術サポートを終了し、より適用性の高い `Langchain-Chachat 0.3.x` の開発に努めます。 。
|
||||
`0.2.10` のその後のバグ修正は、バージョン更新なしで `master` ブランチに直接プッシュされます。
|
||||
|
||||
---
|
||||
|
||||
@ -23,20 +28,29 @@ LLM アプリケーションは、Langchain とオープンソースまたはリ
|
||||
|
||||
## イントロ
|
||||
|
||||
🤖️ [langchain](https://github.com/hwchase17/langchain) のアイデアを用いて実装された、ローカルナレッジベースに基づく Q&A アプリケーション。
|
||||
目標は、中国のシナリオとオープンソースモデルに親和性があり、オフラインとオンラインの両方で実行可能な KBQA(ナレッジベースの Q&A)ソリューションを構築することです。
|
||||
🤖️ [langchain](https://github.com/hwchase17/langchain) のアイデアを用いて実装された、ローカルナレッジベースに基づく Q&A
|
||||
アプリケーション。
|
||||
目標は、中国のシナリオとオープンソースモデルに親和性があり、オフラインとオンラインの両方で実行可能な KBQA(ナレッジベースの
|
||||
Q&A)ソリューションを構築することです。
|
||||
|
||||
💡 [document.ai](https://github.com/GanymedeNil/document.ai) と [ChatGLM-6B Pull Request](https://github.com/THUDM/ChatGLM-6B/pull/216) に触発され、
|
||||
💡 [document.ai](https://github.com/GanymedeNil/document.ai)
|
||||
と [ChatGLM-6B Pull Request](https://github.com/THUDM/ChatGLM-6B/pull/216) に触発され、
|
||||
プロセス全体を通してオープンソースモデルまたはリモート LLM api を使用して実装することができるローカルナレッジベースの質問応答アプリケーションを構築します。
|
||||
このプロジェクトの最新バージョンでは、[FastChat](https://github.com/lm-sys/FastChat) を使用して、Vicuna、Alpaca、LLaMA、Koala、RWKV、その他多くのモデルにアクセスしています。
|
||||
このプロジェクトは [langchain](https://github.com/langchain-ai/langchain) に依存し、[FastAPI](https://github.com/tiangolo/fastapi) に基づいて提供されるAPIを通してサービスを呼び出したり、
|
||||
このプロジェクトの最新バージョンでは、[FastChat](https://github.com/lm-sys/FastChat)
|
||||
を使用して、Vicuna、Alpaca、LLaMA、Koala、RWKV、その他多くのモデルにアクセスしています。
|
||||
このプロジェクトは [langchain](https://github.com/langchain-ai/langchain)
|
||||
に依存し、[FastAPI](https://github.com/tiangolo/fastapi) に基づいて提供されるAPIを通してサービスを呼び出したり、
|
||||
[Streamlit](https://github.com/streamlit/streamlit) に基づいて WebUI を使ったりすることをサポートしています。
|
||||
|
||||
✅ オープンソースの LLM と Embedding モデルに依存して、このプロジェクトはフルプロセスの **オフラインプライベートデプロイメント** を実現することができます。
|
||||
同時に、本プロジェクトは OpenAI GPT API や Zhipu API の呼び出しにも対応しており、今後も様々な機種やリモート API へのアクセスを拡大していきます。
|
||||
✅ オープンソースの LLM と Embedding モデルに依存して、このプロジェクトはフルプロセスの **オフラインプライベートデプロイメント
|
||||
** を実現することができます。
|
||||
同時に、本プロジェクトは OpenAI GPT API や Zhipu API の呼び出しにも対応しており、今後も様々な機種やリモート API
|
||||
へのアクセスを拡大していきます。
|
||||
|
||||
⛓️ このプロジェクトの実施原則を下のグラフに示します。主なプロセスは以下の通りです:
|
||||
ファイルの読み込み -> テキストの読み込み -> テキストのセグメンテーション -> テキストのベクトル化 -> 質問のベクトル化 -> 質問ベクトルと最も似ている `top-k` をテキストベクトルでマッチング -> マッチしたテキストをコンテキストと質問として `prompt` に追加 -> 回答を生成するために `LLM` に送信。
|
||||
ファイルの読み込み -> テキストの読み込み -> テキストのセグメンテーション -> テキストのベクトル化 -> 質問のベクトル化 ->
|
||||
質問ベクトルと最も似ている `top-k` をテキストベクトルでマッチング ->
|
||||
マッチしたテキストをコンテキストと質問として `prompt` に追加 -> 回答を生成するために `LLM` に送信。
|
||||
|
||||
📺[video introduction](https://www.bilibili.com/video/BV13M4y1e7cN/?share_source=copy_web&vd_source=e6c5aafe684f30fbe41925d61ca6d514)
|
||||
|
||||
@ -48,7 +62,8 @@ LLM アプリケーションは、Langchain とオープンソースまたはリ
|
||||
|
||||
🚩 トレーニングやファインチューニングはプロジェクトには含まれないが、これらを行うことで必ずパフォーマンスを向上させることができます。
|
||||
|
||||
🌐 [AutoDL イメージ](registry.cn-beijing.aliyuncs.com/chatchat/chatchat:0.2.5)がサポートされ、v13 では v0.2.9 にアップデートされました。
|
||||
🌐 [AutoDL イメージ](registry.cn-beijing.aliyuncs.com/chatchat/chatchat:0.2.5)がサポートされ、`0.2.10` では v0.2.10
|
||||
にアップデートされました。
|
||||
|
||||
🐳 [Docker イメージ](registry.cn-beijing.aliyuncs.com/chatchat/chatchat:0.2.7)
|
||||
|
||||
@ -67,7 +82,7 @@ LLM アプリケーションは、Langchain とオープンソースまたはリ
|
||||
|
||||
```
|
||||
$ python --version
|
||||
Python 3.10.12
|
||||
Python 3.11.7
|
||||
```
|
||||
|
||||
次に、仮想環境を作成し、プロジェクトの依存関係を仮想環境内にインストールする。
|
||||
@ -87,6 +102,7 @@ $ pip install -r requirements_webui.txt
|
||||
|
||||
# デフォルトの依存関係には、基本的な実行環境(FAISS ベクターライブラリ)が含まれます。milvus/pg_vector などのベクターライブラリを使用する場合は、requirements.txt 内の対応する依存関係のコメントを解除してからインストールしてください。
|
||||
```
|
||||
|
||||
LangChain-Chachat `0.2.x` シリーズは Langchain `0.0.x` シリーズ用です。Langchain `0.1.x` シリーズをお使いの場合は、ダウングレードする必要があります。
|
||||
|
||||
### モデルをダウンロード
|
||||
@ -94,9 +110,12 @@ LangChain-Chachat `0.2.x` シリーズは Langchain `0.0.x` シリーズ用で
|
||||
このプロジェクトをローカルまたはオフライン環境で実行する必要がある場合は、まずプロジェクトに必要なモデルをダウンロードする必要があります。
|
||||
通常、オープンソースの LLM と Embedding モデルは Hugging Face からダウンロードできる。
|
||||
|
||||
このプロジェクトで使用されているデフォルトの LLM モデルである [THUDM/chatglm2-6b](https://huggingface.co/THUDM/chatglm2-6b)と、Embedding モデル [moka-ai/m3e-base](https://huggingface.co/moka-ai/m3e-base) を例にとると、次のようになります:
|
||||
このプロジェクトで使用されているデフォルトの LLM
|
||||
モデルである [THUDM/chatglm2-6b](https://huggingface.co/THUDM/chatglm2-6b)と、Embedding
|
||||
モデル [moka-ai/m3e-base](https://huggingface.co/moka-ai/m3e-base) を例にとると、次のようになります:
|
||||
|
||||
モデルをダウンロードするには、まず [Git LFS](https://docs.github.com/zh/repositories/working-with-files/managing-large-files/installing-git-large-file-storage) をインストールし、次のように実行する必要があります:
|
||||
モデルをダウンロードするには、まず [Git LFS](https://docs.github.com/zh/repositories/working-with-files/managing-large-files/installing-git-large-file-storage)
|
||||
をインストールし、次のように実行する必要があります:
|
||||
|
||||
```Shell
|
||||
$ git lfs install
|
||||
@ -139,7 +158,22 @@ $ python startup.py -a
|
||||
|
||||
### 注
|
||||
|
||||
上記の手順はクイックスタートのために提供されています。より多くの機能が必要な場合や、起動方法をカスタマイズしたい場合は、[Wiki](https://github.com/chatchat-space/Langchain-Chatchat/wiki/) を参照してください。
|
||||
上記の手順はクイックスタートのために提供されています。より多くの機能が必要な場合や、起動方法をカスタマイズしたい場合は、[Wiki](https://github.com/chatchat-space/Langchain-Chatchat/wiki/)
|
||||
を参照してください。
|
||||
|
||||
---
|
||||
|
||||
## プロジェクトのマイルストーン
|
||||
|
||||
+ `2023 年 4 月`: `Langchain-ChatGLM 0.1.0` がリリースされ、ChatGLM-6B モデルに基づくローカル ナレッジ ベースの質問と回答がサポートされました。
|
||||
+ `2023 年 8 月`: `Langchain-ChatGLM` は `Langchain-Chatchat` に名前変更され、モデル読み込みソリューションとして `fastchat` を使用し、より多くのモデルとデータベースをサポートする `0.2.0` がリリースされました。
|
||||
+ `2023 年 10 月`: `Langchain-Chachat 0.2.5` リリース、エージェント コンテンツ、オープンソース プロジェクトを`Founder Park & Zhipu AI & Zilliz`で開始
|
||||
開催したハッカソンでは3位に入賞しました。
|
||||
+ `2023 年 12 月`: `Langchain-Chachat`オープンソース プロジェクトは **20,000** つ以上のスターを獲得しました。
|
||||
+ `2024 年 1 月`: `LangChain 0.1.x` がリリースされ、`Langchain-Chachat 0.2.x` が安定版 `0.2.10` をリリースしました。
|
||||
今後はアップデートと技術サポートを停止し、より適用性の高い`Langchain-Chachat 0.3.x`の開発に努める予定です。
|
||||
|
||||
+ 🔥 これからのChatchatストーリーを一緒に楽しみにしましょう···
|
||||
|
||||
---
|
||||
|
||||
@ -151,7 +185,7 @@ $ python startup.py -a
|
||||
|
||||
### WeChat グループ
|
||||
|
||||
<img src="img/qr_code_67.jpg" alt="二维码" width="300" height="300" />
|
||||
<img src="img/qr_code_88.jpg" alt="二维码" width="300" height="300" />
|
||||
|
||||
### WeChat 公式アカウント
|
||||
|
||||
|
||||
@ -3,7 +3,7 @@ import os
|
||||
# 默认使用的知识库
|
||||
DEFAULT_KNOWLEDGE_BASE = "samples"
|
||||
|
||||
# 默认向量库/全文检索引擎类型。可选:faiss, milvus(离线) & zilliz(在线), pgvector,全文检索引擎es
|
||||
# 默认向量库/全文检索引擎类型。可选:faiss, milvus(离线) & zilliz(在线), pgvector, chromadb 全文检索引擎es
|
||||
DEFAULT_VS_TYPE = "faiss"
|
||||
|
||||
# 缓存向量库数量(针对FAISS)
|
||||
@ -110,7 +110,8 @@ kbs_config = {
|
||||
"milvus_kwargs":{
|
||||
"search_params":{"metric_type": "L2"}, #在此处增加search_params
|
||||
"index_params":{"metric_type": "L2","index_type": "HNSW"} # 在此处增加index_params
|
||||
}
|
||||
},
|
||||
"chromadb": {}
|
||||
}
|
||||
|
||||
# TextSplitter配置项,如果你不明白其中的含义,就不要修改。
|
||||
|
||||
@ -1,5 +1,8 @@
|
||||
from typing import List
|
||||
from langchain.document_loaders.unstructured import UnstructuredFileLoader
|
||||
import cv2
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
from configs import PDF_OCR_THRESHOLD
|
||||
from document_loaders.ocr import get_ocr
|
||||
import tqdm
|
||||
@ -7,6 +10,30 @@ import tqdm
|
||||
|
||||
class RapidOCRPDFLoader(UnstructuredFileLoader):
|
||||
def _get_elements(self) -> List:
|
||||
def rotate_img(img, angle):
|
||||
'''
|
||||
img --image
|
||||
angle --rotation angle
|
||||
return--rotated img
|
||||
'''
|
||||
|
||||
h, w = img.shape[:2]
|
||||
rotate_center = (w/2, h/2)
|
||||
#获取旋转矩阵
|
||||
# 参数1为旋转中心点;
|
||||
# 参数2为旋转角度,正值-逆时针旋转;负值-顺时针旋转
|
||||
# 参数3为各向同性的比例因子,1.0原图,2.0变成原来的2倍,0.5变成原来的0.5倍
|
||||
M = cv2.getRotationMatrix2D(rotate_center, angle, 1.0)
|
||||
#计算图像新边界
|
||||
new_w = int(h * np.abs(M[0, 1]) + w * np.abs(M[0, 0]))
|
||||
new_h = int(h * np.abs(M[0, 0]) + w * np.abs(M[0, 1]))
|
||||
#调整旋转矩阵以考虑平移
|
||||
M[0, 2] += (new_w - w) / 2
|
||||
M[1, 2] += (new_h - h) / 2
|
||||
|
||||
rotated_img = cv2.warpAffine(img, M, (new_w, new_h))
|
||||
return rotated_img
|
||||
|
||||
def pdf2text(filepath):
|
||||
import fitz # pyMuPDF里面的fitz包,不要与pip install fitz混淆
|
||||
import numpy as np
|
||||
@ -30,7 +57,16 @@ class RapidOCRPDFLoader(UnstructuredFileLoader):
|
||||
or (bbox[3] - bbox[1]) / (page.rect.height) < PDF_OCR_THRESHOLD[1]):
|
||||
continue
|
||||
pix = fitz.Pixmap(doc, xref)
|
||||
img_array = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width, -1)
|
||||
samples = pix.samples
|
||||
if int(page.rotation)!=0: #如果Page有旋转角度,则旋转图片
|
||||
img_array = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width, -1)
|
||||
tmp_img = Image.fromarray(img_array);
|
||||
ori_img = cv2.cvtColor(np.array(tmp_img),cv2.COLOR_RGB2BGR)
|
||||
rot_img = rotate_img(img=ori_img, angle=360-page.rotation)
|
||||
img_array = cv2.cvtColor(rot_img, cv2.COLOR_RGB2BGR)
|
||||
else:
|
||||
img_array = np.frombuffer(pix.samples, dtype=np.uint8).reshape(pix.height, pix.width, -1)
|
||||
|
||||
result, _ = ocr(img_array)
|
||||
if result:
|
||||
ocr_result = [line[1] for line in result]
|
||||
@ -46,6 +82,6 @@ class RapidOCRPDFLoader(UnstructuredFileLoader):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
loader = RapidOCRPDFLoader(file_path="../tests/samples/ocr_test.pdf")
|
||||
loader = RapidOCRPDFLoader(file_path="/Users/tonysong/Desktop/test.pdf")
|
||||
docs = loader.load()
|
||||
print(docs)
|
||||
|
||||
@ -2,7 +2,7 @@ torch==2.1.2
|
||||
torchvision==0.16.2
|
||||
torchaudio==2.1.2
|
||||
xformers==0.0.23.post1
|
||||
transformers==4.36.2
|
||||
transformers==4.37.1
|
||||
sentence_transformers==2.2.2
|
||||
langchain==0.0.354
|
||||
langchain-experimental==0.0.47
|
||||
@ -12,7 +12,7 @@ openai==1.9.0
|
||||
fastapi==0.109.0
|
||||
sse_starlette==1.8.2
|
||||
nltk==3.8.1
|
||||
uvicorn==0.24.0.post1
|
||||
uvicorn>=0.27.0.post1
|
||||
starlette==0.35.0
|
||||
unstructured[all-docs] # ==0.11.8
|
||||
python-magic-bin; sys_platform == 'win32'
|
||||
@ -38,15 +38,17 @@ transformers_stream_generator==0.0.4
|
||||
vllm==0.2.7; sys_platform == "linux"
|
||||
llama-index==0.9.35
|
||||
|
||||
#jq==1.6.0
|
||||
# jq==1.6.0
|
||||
# beautifulsoup4==4.12.2
|
||||
# pysrt==1.1.2
|
||||
# dashscope==1.13.6 # qwen
|
||||
# volcengine==1.0.119 # fangzhou
|
||||
# uncomment libs if you want to use corresponding vector store
|
||||
# pymilvus==2.3.4
|
||||
# pymilvus==2.3.6
|
||||
# psycopg2==2.9.9
|
||||
# pgvector==0.2.4
|
||||
# pgvector>=0.2.4
|
||||
# chromadb==0.4.13
|
||||
|
||||
#flash-attn==2.4.2 # For Orion-14B-Chat and Qwen-14B-Chat
|
||||
#autoawq==0.1.8 # For Int4
|
||||
#rapidocr_paddle[gpu]==1.3.11 # gpu accelleration for ocr of pdf and image files
|
||||
@ -63,4 +65,4 @@ streamlit-modal==0.1.0
|
||||
streamlit-aggrid==0.3.4.post3
|
||||
httpx==0.26.0
|
||||
watchdog==3.0.0
|
||||
jwt==1.3.1
|
||||
pyjwt==2.8.0
|
||||
|
||||
@ -2,7 +2,7 @@ torch~=2.1.2
|
||||
torchvision~=0.16.2
|
||||
torchaudio~=2.1.2
|
||||
xformers>=0.0.23.post1
|
||||
transformers==4.36.2
|
||||
transformers==4.37.1
|
||||
sentence_transformers==2.2.2
|
||||
langchain==0.0.354
|
||||
langchain-experimental==0.0.47
|
||||
@ -12,7 +12,7 @@ openai~=1.9.0
|
||||
fastapi~=0.109.0
|
||||
sse_starlette==1.8.2
|
||||
nltk>=3.8.1
|
||||
uvicorn>=0.24.0.post1
|
||||
uvicorn>=0.27.0.post1
|
||||
starlette~=0.35.0
|
||||
unstructured[all-docs]==0.11.0
|
||||
python-magic-bin; sys_platform == 'win32'
|
||||
@ -38,6 +38,7 @@ transformers_stream_generator==0.0.4
|
||||
vllm==0.2.7; sys_platform == "linux"
|
||||
httpx==0.26.0
|
||||
llama-index==0.9.35
|
||||
pyjwt==2.8.0
|
||||
|
||||
# jq==1.6.0
|
||||
# beautifulsoup4~=4.12.2
|
||||
@ -49,9 +50,11 @@ llama-index==0.9.35
|
||||
# metaphor-python~=0.1.23
|
||||
|
||||
# volcengine>=1.0.119
|
||||
# pymilvus>=2.3.4
|
||||
# pymilvus==2.3.6
|
||||
# psycopg2==2.9.9
|
||||
# pgvector>=0.2.4
|
||||
# chromadb==0.4.13
|
||||
|
||||
#flash-attn==2.4.2 # For Orion-14B-Chat and Qwen-14B-Chat
|
||||
#autoawq==0.1.8 # For Int4
|
||||
#rapidocr_paddle[gpu]==1.3.11 # gpu accelleration for ocr of pdf and image files
|
||||
@ -6,7 +6,7 @@ openai~=1.9.0
|
||||
fastapi~=0.109.0
|
||||
sse_starlette~=1.8.2
|
||||
nltk~=3.8.1
|
||||
uvicorn~=0.24.0.post1
|
||||
uvicorn>=0.27.0.post1
|
||||
starlette~=0.35.0
|
||||
unstructured[all-docs]~=0.12.0
|
||||
python-magic-bin; sys_platform == 'win32'
|
||||
@ -20,6 +20,7 @@ requests~=2.31.0
|
||||
pathlib~=1.0.1
|
||||
pytest~=7.4.3
|
||||
llama-index==0.9.35
|
||||
pyjwt==2.8.0
|
||||
|
||||
dashscope==1.13.6
|
||||
arxiv~=2.1.0
|
||||
@ -30,4 +31,10 @@ watchdog~=3.0.0
|
||||
# volcengine>=1.0.119
|
||||
# pymilvus>=2.3.4
|
||||
# psycopg2==2.9.9
|
||||
# pgvector>=0.2.4
|
||||
# pgvector>=0.2.4
|
||||
# chromadb==0.4.13
|
||||
|
||||
# jq==1.6.0
|
||||
# beautifulsoup4~=4.12.2
|
||||
# pysrt~=1.1.2
|
||||
|
||||
|
||||
@ -47,6 +47,7 @@ class SupportedVSType:
|
||||
ZILLIZ = 'zilliz'
|
||||
PG = 'pg'
|
||||
ES = 'es'
|
||||
CHROMADB = 'chromadb'
|
||||
|
||||
|
||||
class KBService(ABC):
|
||||
@ -319,6 +320,9 @@ class KBServiceFactory:
|
||||
elif SupportedVSType.ES == vector_store_type:
|
||||
from server.knowledge_base.kb_service.es_kb_service import ESKBService
|
||||
return ESKBService(kb_name, embed_model=embed_model)
|
||||
elif SupportedVSType.CHROMADB == vector_store_type:
|
||||
from server.knowledge_base.kb_service.chromadb_kb_service import ChromaKBService
|
||||
return ChromaKBService(kb_name, embed_model=embed_model)
|
||||
elif SupportedVSType.DEFAULT == vector_store_type: # kb_exists of default kbservice is False, to make validation easier.
|
||||
from server.knowledge_base.kb_service.default_kb_service import DefaultKBService
|
||||
return DefaultKBService(kb_name)
|
||||
|
||||
105
server/knowledge_base/kb_service/chromadb_kb_service.py
Normal file
105
server/knowledge_base/kb_service/chromadb_kb_service.py
Normal file
@ -0,0 +1,105 @@
|
||||
import uuid
|
||||
from typing import Any, Dict, List, Tuple
|
||||
|
||||
import chromadb
|
||||
from chromadb.api.types import (GetResult, QueryResult)
|
||||
from langchain.docstore.document import Document
|
||||
|
||||
from configs import SCORE_THRESHOLD
|
||||
from server.knowledge_base.kb_service.base import (EmbeddingsFunAdapter,
|
||||
KBService, SupportedVSType)
|
||||
from server.knowledge_base.utils import KnowledgeFile, get_kb_path, get_vs_path
|
||||
|
||||
|
||||
def _get_result_to_documents(get_result: GetResult) -> List[Document]:
|
||||
if not get_result['documents']:
|
||||
return []
|
||||
|
||||
_metadatas = get_result['metadatas'] if get_result['metadatas'] else [{}] * len(get_result['documents'])
|
||||
|
||||
document_list = []
|
||||
for page_content, metadata in zip(get_result['documents'], _metadatas):
|
||||
document_list.append(Document(**{'page_content': page_content, 'metadata': metadata}))
|
||||
|
||||
return document_list
|
||||
|
||||
|
||||
def _results_to_docs_and_scores(results: Any) -> List[Tuple[Document, float]]:
|
||||
"""
|
||||
from langchain_community.vectorstores.chroma import Chroma
|
||||
"""
|
||||
return [
|
||||
# TODO: Chroma can do batch querying,
|
||||
(Document(page_content=result[0], metadata=result[1] or {}), result[2])
|
||||
for result in zip(
|
||||
results["documents"][0],
|
||||
results["metadatas"][0],
|
||||
results["distances"][0],
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
class ChromaKBService(KBService):
|
||||
vs_path: str
|
||||
kb_path: str
|
||||
|
||||
client = None
|
||||
collection = None
|
||||
|
||||
def vs_type(self) -> str:
|
||||
return SupportedVSType.CHROMADB
|
||||
|
||||
def get_vs_path(self) -> str:
|
||||
return get_vs_path(self.kb_name, self.embed_model)
|
||||
|
||||
def get_kb_path(self) -> str:
|
||||
return get_kb_path(self.kb_name)
|
||||
|
||||
def do_init(self) -> None:
|
||||
self.kb_path = self.get_kb_path()
|
||||
self.vs_path = self.get_vs_path()
|
||||
self.client = chromadb.PersistentClient(path=self.vs_path)
|
||||
self.collection = self.client.get_or_create_collection(self.kb_name)
|
||||
|
||||
def do_create_kb(self) -> None:
|
||||
# In ChromaDB, creating a KB is equivalent to creating a collection
|
||||
self.collection = self.client.get_or_create_collection(self.kb_name)
|
||||
|
||||
def do_drop_kb(self):
|
||||
# Dropping a KB is equivalent to deleting a collection in ChromaDB
|
||||
try:
|
||||
self.client.delete_collection(self.kb_name)
|
||||
except ValueError as e:
|
||||
if not str(e) == f"Collection {self.kb_name} does not exist.":
|
||||
raise e
|
||||
|
||||
def do_search(self, query: str, top_k: int, score_threshold: float = SCORE_THRESHOLD) -> List[
|
||||
Tuple[Document, float]]:
|
||||
embed_func = EmbeddingsFunAdapter(self.embed_model)
|
||||
embeddings = embed_func.embed_query(query)
|
||||
query_result: QueryResult = self.collection.query(query_embeddings=embeddings, n_results=top_k)
|
||||
return _results_to_docs_and_scores(query_result)
|
||||
|
||||
def do_add_doc(self, docs: List[Document], **kwargs) -> List[Dict]:
|
||||
doc_infos = []
|
||||
data = self._docs_to_embeddings(docs)
|
||||
ids = [str(uuid.uuid1()) for _ in range(len(data["texts"]))]
|
||||
for _id, text, embedding, metadata in zip(ids, data["texts"], data["embeddings"], data["metadatas"]):
|
||||
self.collection.add(ids=_id, embeddings=embedding, metadatas=metadata, documents=text)
|
||||
doc_infos.append({"id": _id, "metadata": metadata})
|
||||
return doc_infos
|
||||
|
||||
def get_doc_by_ids(self, ids: List[str]) -> List[Document]:
|
||||
get_result: GetResult = self.collection.get(ids=ids)
|
||||
return _get_result_to_documents(get_result)
|
||||
|
||||
def del_doc_by_ids(self, ids: List[str]) -> bool:
|
||||
self.collection.delete(ids=ids)
|
||||
return True
|
||||
|
||||
def do_clear_vs(self):
|
||||
# Clearing the vector store might be equivalent to dropping and recreating the collection
|
||||
self.do_drop_kb()
|
||||
|
||||
def do_delete_doc(self, kb_file: KnowledgeFile, **kwargs):
|
||||
return self.collection.delete(where={"source": kb_file.filepath})
|
||||
@ -2,6 +2,7 @@ from typing import List, Dict, Optional
|
||||
|
||||
from langchain.schema import Document
|
||||
from langchain.vectorstores.milvus import Milvus
|
||||
import os
|
||||
|
||||
from configs import kbs_config
|
||||
|
||||
@ -85,6 +86,7 @@ class MilvusKBService(KBService):
|
||||
def do_delete_doc(self, kb_file: KnowledgeFile, **kwargs):
|
||||
if self.milvus.col:
|
||||
filepath = kb_file.filepath.replace('\\', '\\\\')
|
||||
filename = os.path.basename(filepath)
|
||||
delete_list = [item.get("pk") for item in
|
||||
self.milvus.col.query(expr=f'source == "{filepath}"', output_fields=["pk"])]
|
||||
self.milvus.col.delete(expr=f'pk in {delete_list}')
|
||||
|
||||
File diff suppressed because one or more lines are too long
10
startup.py
10
startup.py
@ -763,24 +763,23 @@ async def start_main_server():
|
||||
p.start()
|
||||
p.name = f"{p.name} ({p.pid})"
|
||||
|
||||
# 等待所有model_worker启动完成
|
||||
for e in model_worker_started:
|
||||
e.wait()
|
||||
|
||||
if p := processes.get("api"):
|
||||
p.start()
|
||||
p.name = f"{p.name} ({p.pid})"
|
||||
api_started.wait() # 等待api.py启动完成
|
||||
api_started.wait()
|
||||
|
||||
if p := processes.get("webui"):
|
||||
p.start()
|
||||
p.name = f"{p.name} ({p.pid})"
|
||||
webui_started.wait() # 等待webui.py启动完成
|
||||
webui_started.wait()
|
||||
|
||||
dump_server_info(after_start=True, args=args)
|
||||
|
||||
while True:
|
||||
cmd = queue.get() # 收到切换模型的消息
|
||||
cmd = queue.get()
|
||||
e = manager.Event()
|
||||
if isinstance(cmd, list):
|
||||
model_name, cmd, new_model_name = cmd
|
||||
@ -851,9 +850,6 @@ async def start_main_server():
|
||||
logger.error(e)
|
||||
logger.warning("Caught KeyboardInterrupt! Setting stop event...")
|
||||
finally:
|
||||
# Send SIGINT if process doesn't exit quickly enough, and kill it as last resort
|
||||
# .is_alive() also implicitly joins the process (good practice in linux)
|
||||
# while alive_procs := [p for p in processes.values() if p.is_alive()]:
|
||||
|
||||
for p in processes.values():
|
||||
logger.warning("Sending SIGKILL to %s", p)
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user