mirror of
https://github.com/csunny/DB-GPT.git
synced 2025-07-24 20:47:46 +00:00
update:merge
This commit is contained in:
parent
e50c04ead2
commit
e59c3834eb
@ -17,6 +17,10 @@
|
||||
#*******************************************************************#
|
||||
#** LLM MODELS **#
|
||||
#*******************************************************************#
|
||||
LLM_MODEL=vicuna-13b
|
||||
MODEL_SERVER=http://your_model_server_url
|
||||
LIMIT_MODEL_CONCURRENCY=5
|
||||
MAX_POSITION_EMBEDDINGS=4096
|
||||
|
||||
## SMART_LLM_MODEL - Smart language model (Default: vicuna-13b)
|
||||
## FAST_LLM_MODEL - Fast language model (Default: chatglm-6b)
|
||||
@ -36,10 +40,10 @@
|
||||
#*******************************************************************#
|
||||
#** DATABASE SETTINGS **#
|
||||
#*******************************************************************#
|
||||
DB_SETTINGS_MYSQL_USER=root
|
||||
DB_SETTINGS_MYSQL_PASSWORD=password
|
||||
DB_SETTINGS_MYSQL_HOST=localhost
|
||||
DB_SETTINGS_MYSQL_PORT=3306
|
||||
LOCAL_DB_USER=root
|
||||
LOCAL_DB_PASSWORD=aa12345678
|
||||
LOCAL_DB_HOST=127.0.0.1
|
||||
LOCAL_DB_PORT=3306
|
||||
|
||||
|
||||
### MILVUS
|
||||
@ -55,6 +59,13 @@ DB_SETTINGS_MYSQL_PORT=3306
|
||||
# MILVUS_SECURE=
|
||||
# MILVUS_COLLECTION=dbgpt
|
||||
|
||||
#*******************************************************************#
|
||||
#** COMMANDS **#
|
||||
#*******************************************************************#
|
||||
EXECUTE_LOCAL_COMMANDS=False
|
||||
|
||||
|
||||
|
||||
#*******************************************************************#
|
||||
#** ALLOWLISTED PLUGINS **#
|
||||
#*******************************************************************#
|
||||
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -6,6 +6,7 @@ __pycache__/
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
.env
|
||||
.idea
|
||||
.vscode
|
||||
.idea
|
||||
|
223
README.en.md
223
README.en.md
@ -1,223 +0,0 @@
|
||||
# DB-GPT 
|
||||
|
||||
---
|
||||
|
||||
[中文版](README.md)
|
||||
|
||||
[](https://star-history.com/#csunny/DB-GPT)
|
||||
|
||||
## What is DB-GPT?
|
||||
|
||||
As large models are released and iterated upon, they are becoming increasingly intelligent. However, in the process of using large models, we face significant challenges in data security and privacy. We need to ensure that our sensitive data and environments remain completely controlled and avoid any data privacy leaks or security risks. Based on this, we have launched the DB-GPT project to build a complete private large model solution for all database-based scenarios. This solution supports local deployment, allowing it to be applied not only in independent private environments but also to be independently deployed and isolated according to business modules, ensuring that the ability of large models is absolutely private, secure, and controllable.
|
||||
|
||||
DB-GPT is an experimental open-source project that uses localized GPT large models to interact with your data and environment. With this solution, you can be assured that there is no risk of data leakage, and your data is 100% private and secure.
|
||||
|
||||
## Features
|
||||
|
||||
Currently, we have released multiple key features, which are listed below to demonstrate our current capabilities:
|
||||
|
||||
- SQL language capabilities
|
||||
- SQL generation
|
||||
- SQL diagnosis
|
||||
- Private domain Q&A and data processing
|
||||
- Database knowledge Q&A
|
||||
- Data processing
|
||||
- Plugins
|
||||
- Support custom plugin execution tasks and natively support the Auto-GPT plugin, such as:
|
||||
- Automatic execution of SQL and retrieval of query results
|
||||
- Automatic crawling and learning of knowledge
|
||||
- Unified vector storage/indexing of knowledge base
|
||||
- Support for unstructured data such as PDF, Markdown, CSV, and WebURL
|
||||
|
||||
|
||||
## Demo
|
||||
|
||||
Run on an RTX 4090 GPU. [YouTube](https://www.youtube.com/watch?v=1PWI6F89LPo)
|
||||
|
||||
### Run
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/demo_en.gif" width="600px" />
|
||||
</p>
|
||||
|
||||
### SQL Generation
|
||||
|
||||
1. Generate Create Table SQL
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/SQL_Gen_CreateTable_en.png" width="600px" />
|
||||
</p>
|
||||
|
||||
2. Generating executable SQL:To generate executable SQL, first select the corresponding database and then the model can generate SQL based on the corresponding database schema information. The successful result of running it would be demonstrated as follows:
|
||||
<p align="center">
|
||||
<img src="./assets/exeable_en.png" width="600px" />
|
||||
</p>
|
||||
|
||||
### Q&A
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/DB_QA_en.png" width="600px" />
|
||||
</p>
|
||||
|
||||
1. Based on the default built-in knowledge base, question and answer.
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/Knownledge_based_QA_en.png" width="600px" />
|
||||
</p>
|
||||
|
||||
2. Add your own knowledge base.
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/new_knownledge_en.gif" width="600px" />
|
||||
</p>
|
||||
|
||||
3. Learning from crawling data from the Internet
|
||||
|
||||
- TODO
|
||||
|
||||
|
||||
## Introduction
|
||||
DB-GPT creates a vast model operating system using [FastChat](https://github.com/lm-sys/FastChat) and offers a large language model powered by [Vicuna](https://huggingface.co/Tribbiani/vicuna-7b). In addition, we provide private domain knowledge base question-answering capability through LangChain. Furthermore, we also provide support for additional plugins, and our design natively supports the Auto-GPT plugin.
|
||||
|
||||
Is the architecture of the entire DB-GPT shown in the following figure:
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/DB-GPT.png" width="600px" />
|
||||
</p>
|
||||
|
||||
The core capabilities mainly consist of the following parts:
|
||||
1. Knowledge base capability: Supports private domain knowledge base question-answering capability.
|
||||
2. Large-scale model management capability: Provides a large model operating environment based on FastChat.
|
||||
3. Unified data vector storage and indexing: Provides a uniform way to store and index various data types.
|
||||
4. Connection module: Used to connect different modules and data sources to achieve data flow and interaction.
|
||||
5. Agent and plugins: Provides Agent and plugin mechanisms, allowing users to customize and enhance the system's behavior.
|
||||
6. Prompt generation and optimization: Automatically generates high-quality prompts and optimizes them to improve system response efficiency.
|
||||
7. Multi-platform product interface: Supports various client products, such as web, mobile applications, and desktop applications.
|
||||
|
||||
Below is a brief introduction to each module:
|
||||
|
||||
### Knowledge base capability
|
||||
|
||||
As the knowledge base is currently the most significant user demand scenario, we natively support the construction and processing of knowledge bases. At the same time, we also provide multiple knowledge base management strategies in this project, such as:
|
||||
1. Default built-in knowledge base
|
||||
2. Custom addition of knowledge bases
|
||||
3. Various usage scenarios such as constructing knowledge bases through plugin capabilities and web crawling. Users only need to organize the knowledge documents, and they can use our existing capabilities to build the knowledge base required for the large model.
|
||||
|
||||
### LLMs Management
|
||||
|
||||
In the underlying large model integration, we have designed an open interface that supports integration with various large models. At the same time, we have a very strict control and evaluation mechanism for the effectiveness of the integrated models. In terms of accuracy, the integrated models need to align with the capability of ChatGPT at a level of 85% or higher. We use higher standards to select models, hoping to save users the cumbersome testing and evaluation process in the process of use.
|
||||
|
||||
### Vector storage and indexing
|
||||
|
||||
In order to facilitate the management of knowledge after vectorization, we have built-in multiple vector storage engines, from memory-based Chroma to distributed Milvus. Users can choose different storage engines according to their own scenario needs. The storage of knowledge vectors is the cornerstone of AI capability enhancement. As the intermediate language for interaction between humans and large language models, vectors play a very important role in this project.
|
||||
|
||||
### Connections
|
||||
|
||||
In order to interact more conveniently with users' private environments, the project has designed a connection module, which can support connection to databases, Excel, knowledge bases, and other environments to achieve information and data exchange.
|
||||
|
||||
### Agent and Plugin
|
||||
|
||||
The ability of Agent and Plugin is the core of whether large models can be automated. In this project, we natively support the plugin mode, and large models can automatically achieve their goals. At the same time, in order to give full play to the advantages of the community, the plugins used in this project natively support the Auto-GPT plugin ecology, that is, Auto-GPT plugins can directly run in our project.
|
||||
|
||||
### Prompt Automatic Generation and Optimization
|
||||
|
||||
Prompt is a very important part of the interaction between the large model and the user, and to a certain extent, it determines the quality and accuracy of the answer generated by the large model. In this project, we will automatically optimize the corresponding prompt according to user input and usage scenarios, making it easier and more efficient for users to use large language models.
|
||||
|
||||
### Multi-Platform Product Interface
|
||||
|
||||
TODO: In terms of terminal display, we will provide a multi-platform product interface, including PC, mobile phone, command line, Slack and other platforms.
|
||||
|
||||
## Deployment
|
||||
|
||||
### 1. Hardware Requirements
|
||||
As our project has the ability to achieve ChatGPT performance of over 85%, there are certain hardware requirements. However, overall, the project can be deployed and used on consumer-grade graphics cards. The specific hardware requirements for deployment are as follows:
|
||||
|
||||
| GPU | VRAM Size | Performance |
|
||||
| --------- | --------- | ------------------------------------------- |
|
||||
| RTX 4090 | 24 GB | Smooth conversation inference |
|
||||
| RTX 3090 | 24 GB | Smooth conversation inference, better than V100 |
|
||||
| V100 | 16 GB | Conversation inference possible, noticeable stutter |
|
||||
|
||||
### 2. Install
|
||||
|
||||
This project relies on a local MySQL database service, which you need to install locally. We recommend using Docker for installation.
|
||||
|
||||
```bash
|
||||
$ docker run --name=mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=aa12345678 -dit mysql:latest
|
||||
```
|
||||
We use [Chroma embedding database](https://github.com/chroma-core/chroma) as the default for our vector database, so there is no need for special installation. If you choose to connect to other databases, you can follow our tutorial for installation and configuration.
|
||||
For the entire installation process of DB-GPT, we use the miniconda3 virtual environment. Create a virtual environment and install the Python dependencies.
|
||||
```
|
||||
python>=3.10
|
||||
conda create -n dbgpt_env python=3.10
|
||||
conda activate dbgpt_env
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
Alternatively, you can use the following command:
|
||||
```
|
||||
cd DB-GPT
|
||||
conda env create -f environment.yml
|
||||
```
|
||||
It is recommended to set the Python package path to avoid runtime errors due to package not found.
|
||||
```
|
||||
echo "/root/workspace/DB-GPT" > /root/miniconda3/env/dbgpt_env/lib/python3.10/site-packages/dbgpt.pth
|
||||
```
|
||||
Notice: You need replace the path to your owner.
|
||||
|
||||
### 3. Run
|
||||
You can refer to this document to obtain the Vicuna weights: [Vicuna](https://github.com/lm-sys/FastChat/blob/main/README.md#model-weights) .
|
||||
|
||||
If you have difficulty with this step, you can also directly use the model from [this link](https://huggingface.co/Tribbiani/vicuna-7b) as a replacement.
|
||||
|
||||
1. Run server
|
||||
```bash
|
||||
$ python pilot/server/llmserver.py
|
||||
```
|
||||
|
||||
Run gradio webui
|
||||
|
||||
```bash
|
||||
$ python pilot/server/webserver.py
|
||||
```
|
||||
Notice: the webserver need to connect llmserver, so you need change the pilot/configs/model_config.py file. change the VICUNA_MODEL_SERVER = "http://127.0.0.1:8000" to your address. It's very important.
|
||||
|
||||
## Usage Instructions
|
||||
We provide a user interface for Gradio, which allows you to use DB-GPT through our user interface. Additionally, we have prepared several reference articles (written in Chinese) that introduce the code and principles related to our project.
|
||||
- [LLM Practical In Action Series (1) — Combined Langchain-Vicuna Application Practical](https://medium.com/@cfqcsunny/llm-practical-in-action-series-1-combined-langchain-vicuna-application-practical-701cd0413c9f)
|
||||
|
||||
## Acknowledgement
|
||||
|
||||
The achievements of this project are thanks to the technical community, especially the following projects:
|
||||
- [FastChat](https://github.com/lm-sys/FastChat) for providing chat services
|
||||
- [vicuna-13b](https://lmsys.org/blog/2023-03-30-vicuna/) as the base model
|
||||
- [langchain](https://langchain.readthedocs.io/) tool chain
|
||||
- [Auto-GPT](https://github.com/Significant-Gravitas/Auto-GPT) universal plugin template
|
||||
- [Hugging Face](https://huggingface.co/) for big model management
|
||||
- [Chroma](https://github.com/chroma-core/chroma) for vector storage
|
||||
- [Milvus](https://milvus.io/) for distributed vector storage
|
||||
- [ChatGLM](https://github.com/THUDM/ChatGLM-6B) as the base model
|
||||
- [llama_index](https://github.com/jerryjliu/llama_index) for enhancing database-related knowledge using [in-context learning](https://arxiv.org/abs/2301.00234) based on existing knowledge bases.
|
||||
|
||||
<!-- GITCONTRIBUTOR_START -->
|
||||
|
||||
## Contributors
|
||||
|
||||
|[<img src="https://avatars.githubusercontent.com/u/17919400?v=4" width="100px;"/><br/><sub><b>csunny</b></sub>](https://github.com/csunny)<br/>|[<img src="https://avatars.githubusercontent.com/u/1011681?v=4" width="100px;"/><br/><sub><b>xudafeng</b></sub>](https://github.com/xudafeng)<br/>|[<img src="https://avatars.githubusercontent.com/u/7636723?s=96&v=4" width="100px;"/><br/><sub><b>明天</b></sub>](https://github.com/yhjun1026)<br/> | [<img src="https://avatars.githubusercontent.com/u/13723926?v=4" width="100px;"/><br/><sub><b>Aries-ckt</b></sub>](https://github.com/Aries-ckt)<br/>|[<img src="https://avatars.githubusercontent.com/u/95130644?v=4" width="100px;"/><br/><sub><b>thebigbone</b></sub>](https://github.com/thebigbone)<br/>|
|
||||
| :---: | :---: | :---: | :---: |:---: |
|
||||
|
||||
|
||||
This project follows the git-contributor [spec](https://github.com/xudafeng/git-contributor), auto updated at `Sun May 14 2023 23:02:43 GMT+0800`.
|
||||
|
||||
<!-- GITCONTRIBUTOR_END -->
|
||||
|
||||
## Licence
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
## Contact Information
|
||||
We are working on building a community, if you have any ideas about building the community, feel free to contact me us.
|
||||
|
||||
name | email|
|
||||
---------|---------------------
|
||||
yushun06| my_prophet@hotmail.com
|
||||
csunny | cfqcsunny@gmail.com
|
264
README.md
264
README.md
@ -1,205 +1,192 @@
|
||||
# DB-GPT 
|
||||
|
||||
[English Edition](README.en.md)
|
||||
---
|
||||
|
||||
[简体中文](README.zh.md)
|
||||
|
||||
[](https://star-history.com/#csunny/DB-GPT)
|
||||
|
||||
## DB-GPT 是什么?
|
||||
随着大模型的发布迭代,大模型变得越来越智能,在使用大模型的过程当中,遇到极大的数据安全与隐私挑战。在利用大模型能力的过程中我们的私密数据跟环境需要掌握自己的手里,完全可控,避免任何的数据隐私泄露以及安全风险。基于此,我们发起了DB-GPT项目,为所有以数据库为基础的场景,构建一套完整的私有大模型解决方案。 此方案因为支持本地部署,所以不仅仅可以应用于独立私有环境,而且还可以根据业务模块独立部署隔离,让大模型的能力绝对私有、安全、可控。
|
||||
## What is DB-GPT?
|
||||
|
||||
DB-GPT 是一个开源的以数据库为基础的GPT实验项目,使用本地化的GPT大模型与您的数据和环境进行交互,无数据泄露风险,100% 私密,100% 安全。
|
||||
As large models are released and iterated upon, they are becoming increasingly intelligent. However, in the process of using large models, we face significant challenges in data security and privacy. We need to ensure that our sensitive data and environments remain completely controlled and avoid any data privacy leaks or security risks. Based on this, we have launched the DB-GPT project to build a complete private large model solution for all database-based scenarios. This solution supports local deployment, allowing it to be applied not only in independent private environments but also to be independently deployed and isolated according to business modules, ensuring that the ability of large models is absolutely private, secure, and controllable.
|
||||
|
||||
DB-GPT is an experimental open-source project that uses localized GPT large models to interact with your data and environment. With this solution, you can be assured that there is no risk of data leakage, and your data is 100% private and secure.
|
||||
|
||||
## Features
|
||||
|
||||
Currently, we have released multiple key features, which are listed below to demonstrate our current capabilities:
|
||||
|
||||
- SQL language capabilities
|
||||
- SQL generation
|
||||
- SQL diagnosis
|
||||
- Private domain Q&A and data processing
|
||||
- Database knowledge Q&A
|
||||
- Data processing
|
||||
- Plugins
|
||||
- Support custom plugin execution tasks and natively support the Auto-GPT plugin, such as:
|
||||
- Automatic execution of SQL and retrieval of query results
|
||||
- Automatic crawling and learning of knowledge
|
||||
- Unified vector storage/indexing of knowledge base
|
||||
- Support for unstructured data such as PDF, Markdown, CSV, and WebURL
|
||||
|
||||
|
||||
## 特性一览
|
||||
## Demo
|
||||
|
||||
目前我们已经发布了多种关键的特性,这里一一列举展示一下当前发布的能力。
|
||||
- SQL 语言能力
|
||||
- SQL生成
|
||||
- SQL诊断
|
||||
- 私域问答与数据处理
|
||||
- 数据库知识问答
|
||||
- 数据处理
|
||||
- 插件模型
|
||||
- 支持自定义插件执行任务,原生支持Auto-GPT插件。如:
|
||||
- SQL自动执行,获取查询结果
|
||||
- 自动爬取学习知识
|
||||
- 知识库统一向量存储/索引
|
||||
- 非结构化数据支持包括PDF、MarkDown、CSV、WebURL
|
||||
Run on an RTX 4090 GPU. [YouTube](https://www.youtube.com/watch?v=1PWI6F89LPo)
|
||||
|
||||
## 效果演示
|
||||
|
||||
示例通过 RTX 4090 GPU 演示,[YouTube 地址](https://www.youtube.com/watch?v=1PWI6F89LPo)
|
||||
### 运行环境演示
|
||||
### Run
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/演示.gif" width="600px" />
|
||||
<img src="./assets/demo_en.gif" width="600px" />
|
||||
</p>
|
||||
|
||||
### SQL Generation
|
||||
|
||||
1. Generate Create Table SQL
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/Auto-DB-GPT.gif" width="600px" />
|
||||
<img src="./assets/SQL_Gen_CreateTable_en.png" width="600px" />
|
||||
</p>
|
||||
|
||||
### SQL 生成
|
||||
2. Generating executable SQL:To generate executable SQL, first select the corresponding database and then the model can generate SQL based on the corresponding database schema information. The successful result of running it would be demonstrated as follows:
|
||||
<p align="center">
|
||||
<img src="./assets/exeable_en.png" width="600px" />
|
||||
</p>
|
||||
|
||||
1. 生成建表语句
|
||||
### Q&A
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/SQL_Gen_CreateTable.png" width="600px" />
|
||||
<img src="./assets/DB_QA_en.png" width="600px" />
|
||||
</p>
|
||||
|
||||
2. 生成可运行SQL
|
||||
首先选择对应的数据库, 然后模型即可根据对应的数据库 Schema 信息生成 SQL, 运行成功的效果如下面的演示:
|
||||
1. Based on the default built-in knowledge base, question and answer.
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/exeable.png" width="600px" />
|
||||
<img src="./assets/Knownledge_based_QA_en.png" width="600px" />
|
||||
</p>
|
||||
|
||||
3. 自动分析执行SQL输出运行结果
|
||||
2. Add your own knowledge base.
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/Auto-DB-GPT.png" width="600px" />
|
||||
<img src="./assets/new_knownledge_en.gif" width="600px" />
|
||||
</p>
|
||||
|
||||
### 数据库问答
|
||||
3. Learning from crawling data from the Internet
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/DB_QA.png" width="600px" />
|
||||
</p>
|
||||
- TODO
|
||||
|
||||
|
||||
1. 基于默认内置知识库问答
|
||||
## Introduction
|
||||
DB-GPT creates a vast model operating system using [FastChat](https://github.com/lm-sys/FastChat) and offers a large language model powered by [Vicuna](https://huggingface.co/Tribbiani/vicuna-7b). In addition, we provide private domain knowledge base question-answering capability through LangChain. Furthermore, we also provide support for additional plugins, and our design natively supports the Auto-GPT plugin.
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/VectorDBQA.png" width="600px" />
|
||||
</p>
|
||||
|
||||
2. 自己新增知识库
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/new_knownledge.gif" width="600px" />
|
||||
</p>
|
||||
|
||||
3. 从网络自己爬取数据学习
|
||||
- TODO
|
||||
|
||||
## 架构方案
|
||||
DB-GPT基于 [FastChat](https://github.com/lm-sys/FastChat) 构建大模型运行环境,并提供 vicuna 作为基础的大语言模型。此外,我们通过LangChain提供私域知识库问答能力。同时我们支持插件模式, 在设计上原生支持Auto-GPT插件。
|
||||
|
||||
整个DB-GPT的架构,如下图所示
|
||||
Is the architecture of the entire DB-GPT shown in the following figure:
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/DB-GPT.png" width="600px" />
|
||||
</p>
|
||||
|
||||
核心能力主要有以下几个部分。
|
||||
1. 知识库能力:支持私域知识库问答能力
|
||||
2. 大模型管理能力:基于FastChat提供一个大模型的运营环境。
|
||||
3. 统一的数据向量化存储与索引:提供一种统一的方式来存储和索引各种数据类型。
|
||||
4. 连接模块:用于连接不同的模块和数据源,实现数据的流转和交互。
|
||||
5. Agent与插件:提供Agent和插件机制,使得用户可以自定义并增强系统的行为。
|
||||
6. Prompt自动生成与优化:自动化生成高质量的Prompt,并进行优化,提高系统的响应效率。
|
||||
7. 多端产品界面:支持多种不同的客户端产品,例如Web、移动应用和桌面应用等。
|
||||
The core capabilities mainly consist of the following parts:
|
||||
1. Knowledge base capability: Supports private domain knowledge base question-answering capability.
|
||||
2. Large-scale model management capability: Provides a large model operating environment based on FastChat.
|
||||
3. Unified data vector storage and indexing: Provides a uniform way to store and index various data types.
|
||||
4. Connection module: Used to connect different modules and data sources to achieve data flow and interaction.
|
||||
5. Agent and plugins: Provides Agent and plugin mechanisms, allowing users to customize and enhance the system's behavior.
|
||||
6. Prompt generation and optimization: Automatically generates high-quality prompts and optimizes them to improve system response efficiency.
|
||||
7. Multi-platform product interface: Supports various client products, such as web, mobile applications, and desktop applications.
|
||||
|
||||
下面对每个模块也做一些简要的介绍:
|
||||
Below is a brief introduction to each module:
|
||||
|
||||
### 知识库能力
|
||||
知识库作为当前用户需求最大的场景,我们原生支持知识库的构建与处理。同时在本项目当中,也提供了多种知识库的管理策略。 如:
|
||||
1. 默认内置知识库
|
||||
2. 自定义新增知识库
|
||||
3. 通过插件能力自抓取构建知识库等多种使用场景。
|
||||
|
||||
用户只需要整理好知识文档,即可用我们现有的能力构建大模型所需要的知识库能力。
|
||||
### Knowledge base capability
|
||||
|
||||
### 大模型管理能力
|
||||
在底层大模型接入中,设计了开放的接口,支持对接多种大模型。同时对于接入模型的效果,我们有非常严格的把控与评审机制。对大模型能力上与ChatGPT对比,在准确率上需要满足85%以上的能力对齐。我们用更高的标准筛选模型,是期望在用户使用过程中,可以省去前面繁琐的测试评估环节。
|
||||
As the knowledge base is currently the most significant user demand scenario, we natively support the construction and processing of knowledge bases. At the same time, we also provide multiple knowledge base management strategies in this project, such as:
|
||||
1. Default built-in knowledge base
|
||||
2. Custom addition of knowledge bases
|
||||
3. Various usage scenarios such as constructing knowledge bases through plugin capabilities and web crawling. Users only need to organize the knowledge documents, and they can use our existing capabilities to build the knowledge base required for the large model.
|
||||
|
||||
### 统一的数据向量化存储与索引
|
||||
为了方便对知识向量化之后的管理,我们内置了多种向量存储引擎,从基于内存的Chroma到分布式的Milvus, 可以根据自己的场景需求,选择不同的存储引擎,整个知识向量存储是AI能力增强的基石,向量作为人与大语言模型交互的中间语言,在本项目中的作用非常重要。
|
||||
### LLMs Management
|
||||
|
||||
### 连接模块
|
||||
为了能够更方便的与用户的私有环境进行交互,项目设计了连接模块,连接模块可以支持连接到数据库、Excel、知识库等等多种环境当中,实现信息与数据交互。
|
||||
In the underlying large model integration, we have designed an open interface that supports integration with various large models. At the same time, we have a very strict control and evaluation mechanism for the effectiveness of the integrated models. In terms of accuracy, the integrated models need to align with the capability of ChatGPT at a level of 85% or higher. We use higher standards to select models, hoping to save users the cumbersome testing and evaluation process in the process of use.
|
||||
|
||||
### Agent与插件
|
||||
Agent与插件能力是大模型能否自动化的核心,在本的项目中,原生支持插件模式,大模型可以自动化完成目标。 同时为了充分发挥社区的优势,本项目中所用的插件原生支持Auto-GPT插件生态,即Auto-GPT的插件可以直接在我们的项目中运行。
|
||||
### Vector storage and indexing
|
||||
|
||||
### Prompt自动生成与优化
|
||||
Prompt是与大模型交互过程中非常重要的部分,一定程度上Prompt决定了大模型生成答案的质量与准确性,在本的项目中,我们会根据用户输入与使用场景,自动优化对应的Prompt,让用户使用大语言模型变得更简单、更高效。
|
||||
In order to facilitate the management of knowledge after vectorization, we have built-in multiple vector storage engines, from memory-based Chroma to distributed Milvus. Users can choose different storage engines according to their own scenario needs. The storage of knowledge vectors is the cornerstone of AI capability enhancement. As the intermediate language for interaction between humans and large language models, vectors play a very important role in this project.
|
||||
|
||||
### 多端产品界面
|
||||
TODO: 在终端展示上,我们将提供多端产品界面。包括PC、手机、命令行、Slack等多种模式。
|
||||
### Connections
|
||||
|
||||
In order to interact more conveniently with users' private environments, the project has designed a connection module, which can support connection to databases, Excel, knowledge bases, and other environments to achieve information and data exchange.
|
||||
|
||||
## 安装教程
|
||||
### 1.硬件说明
|
||||
因为我们的项目在效果上具备ChatGPT 85%以上的能力,因此对硬件有一定的要求。 但总体来说,我们在消费级的显卡上即可完成项目的部署使用,具体部署的硬件说明如下:
|
||||
| GPU型号 | 显存大小 | 性能 |
|
||||
| ------- | -------- | ------------------------------------------ |
|
||||
| RTX4090 | 24G | 可以流畅的进行对话推理,无卡顿 |
|
||||
| RTX3090 | 24G | 可以流畅进行对话推理,有卡顿感,但好于V100 |
|
||||
| V100 | 16G | 可以进行对话推理,有明显卡顿 |
|
||||
### 2.DB-GPT安装
|
||||
### Agent and Plugin
|
||||
|
||||
本项目依赖一个本地的 MySQL 数据库服务,你需要本地安装,推荐直接使用 Docker 安装。
|
||||
The ability of Agent and Plugin is the core of whether large models can be automated. In this project, we natively support the plugin mode, and large models can automatically achieve their goals. At the same time, in order to give full play to the advantages of the community, the plugins used in this project natively support the Auto-GPT plugin ecology, that is, Auto-GPT plugins can directly run in our project.
|
||||
|
||||
### Prompt Automatic Generation and Optimization
|
||||
|
||||
Prompt is a very important part of the interaction between the large model and the user, and to a certain extent, it determines the quality and accuracy of the answer generated by the large model. In this project, we will automatically optimize the corresponding prompt according to user input and usage scenarios, making it easier and more efficient for users to use large language models.
|
||||
|
||||
### Multi-Platform Product Interface
|
||||
|
||||
TODO: In terms of terminal display, we will provide a multi-platform product interface, including PC, mobile phone, command line, Slack and other platforms.
|
||||
|
||||
## Deployment
|
||||
|
||||
### 1. Hardware Requirements
|
||||
As our project has the ability to achieve ChatGPT performance of over 85%, there are certain hardware requirements. However, overall, the project can be deployed and used on consumer-grade graphics cards. The specific hardware requirements for deployment are as follows:
|
||||
|
||||
| GPU | VRAM Size | Performance |
|
||||
| --------- | --------- | ------------------------------------------- |
|
||||
| RTX 4090 | 24 GB | Smooth conversation inference |
|
||||
| RTX 3090 | 24 GB | Smooth conversation inference, better than V100 |
|
||||
| V100 | 16 GB | Conversation inference possible, noticeable stutter |
|
||||
|
||||
### 2. Install
|
||||
|
||||
This project relies on a local MySQL database service, which you need to install locally. We recommend using Docker for installation.
|
||||
|
||||
```bash
|
||||
$ docker run --name=mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=aa12345678 -dit mysql:latest
|
||||
```
|
||||
docker run --name=mysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=aa12345678 -dit mysql:latest
|
||||
```
|
||||
向量数据库我们默认使用的是Chroma内存数据库,所以无需特殊安装,如果有需要连接其他的同学,可以按照我们的教程进行安装配置。整个DB-GPT的安装过程,我们使用的是miniconda3的虚拟环境。创建虚拟环境,并安装python依赖包
|
||||
|
||||
We use [Chroma embedding database](https://github.com/chroma-core/chroma) as the default for our vector database, so there is no need for special installation. If you choose to connect to other databases, you can follow our tutorial for installation and configuration.
|
||||
For the entire installation process of DB-GPT, we use the miniconda3 virtual environment. Create a virtual environment and install the Python dependencies.
|
||||
```
|
||||
python>=3.10
|
||||
conda create -n dbgpt_env python=3.10
|
||||
conda activate dbgpt_env
|
||||
pip install -r requirements.txt
|
||||
|
||||
```
|
||||
或者也可以使用命令:
|
||||
```
|
||||
cd DB-GPT
|
||||
conda env create -f environment.yml
|
||||
```
|
||||
另外需要设置一下python包路径, 避免出现运行时找不到包
|
||||
```
|
||||
echo "/root/workspace/DB-GPT" > /root/miniconda3/env/dbgpt_env/lib/python3.10/site-packages/dbgpt.pth
|
||||
```
|
||||
|
||||
### 3. 运行大模型
|
||||
### 3. Run
|
||||
You can refer to this document to obtain the Vicuna weights: [Vicuna](https://github.com/lm-sys/FastChat/blob/main/README.md#model-weights) .
|
||||
|
||||
关于基础模型, 可以根据[Vicuna](https://github.com/lm-sys/FastChat/blob/main/README.md#model-weights)合成教程进行合成。
|
||||
如果此步有困难的同学,也可以直接使用[此链接](https://huggingface.co/Tribbiani/vicuna-7b)上的模型进行替代。
|
||||
If you have difficulty with this step, you can also directly use the model from [this link](https://huggingface.co/Tribbiani/vicuna-7b) as a replacement.
|
||||
|
||||
运行模型服务
|
||||
```
|
||||
cd pilot/server
|
||||
python llmserver.py
|
||||
1. Run server
|
||||
```bash
|
||||
$ python pilot/server/llmserver.py
|
||||
```
|
||||
|
||||
运行 gradio webui
|
||||
Run gradio webui
|
||||
|
||||
```bash
|
||||
$ python webserver.py
|
||||
$ python pilot/server/webserver.py
|
||||
```
|
||||
注意: 在启动Webserver之前, 需要修改pilot/configs/model_config.py 文件中的VICUNA_MODEL_SERVER = "http://127.0.0.1:8000", 将地址设置为你的服务器地址。
|
||||
Notice: the webserver need to connect llmserver, so you need change the .env file. change the MODEL_SERVER = "http://127.0.0.1:8000" to your address. It's very important.
|
||||
|
||||
## 使用说明
|
||||
## Usage Instructions
|
||||
We provide a user interface for Gradio, which allows you to use DB-GPT through our user interface. Additionally, we have prepared several reference articles (written in Chinese) that introduce the code and principles related to our project.
|
||||
- [LLM Practical In Action Series (1) — Combined Langchain-Vicuna Application Practical](https://medium.com/@cfqcsunny/llm-practical-in-action-series-1-combined-langchain-vicuna-application-practical-701cd0413c9f)
|
||||
|
||||
我们提供了Gradio的用户界面,可以通过我们的用户界面使用DB-GPT, 同时关于我们项目相关的一些代码跟原理介绍,我们也准备了以下几篇参考文章。
|
||||
1. [大模型实战系列(1) —— 强强联合Langchain-Vicuna应用实战](https://zhuanlan.zhihu.com/p/628750042)
|
||||
2. [大模型实战系列(2) —— DB-GPT 阿里云部署指南](https://zhuanlan.zhihu.com/p/629467580)
|
||||
3. [大模型实战系列(3) —— DB-GPT插件模型原理与使用](https://zhuanlan.zhihu.com/p/629623125)
|
||||
## Acknowledgement
|
||||
|
||||
## 感谢
|
||||
|
||||
项目取得的成果,需要感谢技术社区,尤其以下项目。
|
||||
|
||||
- [FastChat](https://github.com/lm-sys/FastChat) 提供 chat 服务
|
||||
- [vicuna-13b](https://huggingface.co/Tribbiani/vicuna-13b) 作为基础模型
|
||||
- [langchain](https://github.com/hwchase17/langchain) 工具链
|
||||
- [Auto-GPT](https://github.com/Significant-Gravitas/Auto-GPT) 通用的插件模版
|
||||
- [Hugging Face](https://huggingface.co/) 大模型管理
|
||||
- [Chroma](https://github.com/chroma-core/chroma) 向量存储
|
||||
- [Milvus](https://milvus.io/) 分布式向量存储
|
||||
- [ChatGLM](https://github.com/THUDM/ChatGLM-6B) 基础模型
|
||||
- [llama-index](https://github.com/jerryjliu/llama_index) 基于现有知识库进行[In-Context Learning](https://arxiv.org/abs/2301.00234)来对其进行数据库相关知识的增强。
|
||||
The achievements of this project are thanks to the technical community, especially the following projects:
|
||||
- [FastChat](https://github.com/lm-sys/FastChat) for providing chat services
|
||||
- [vicuna-13b](https://lmsys.org/blog/2023-03-30-vicuna/) as the base model
|
||||
- [langchain](https://langchain.readthedocs.io/) tool chain
|
||||
- [Auto-GPT](https://github.com/Significant-Gravitas/Auto-GPT) universal plugin template
|
||||
- [Hugging Face](https://huggingface.co/) for big model management
|
||||
- [Chroma](https://github.com/chroma-core/chroma) for vector storage
|
||||
- [Milvus](https://milvus.io/) for distributed vector storage
|
||||
- [ChatGLM](https://github.com/THUDM/ChatGLM-6B) as the base model
|
||||
- [llama_index](https://github.com/jerryjliu/llama_index) for enhancing database-related knowledge using [in-context learning](https://arxiv.org/abs/2301.00234) based on existing knowledge bases.
|
||||
|
||||
<!-- GITCONTRIBUTOR_START -->
|
||||
|
||||
@ -213,12 +200,9 @@ This project follows the git-contributor [spec](https://github.com/xudafeng/git-
|
||||
|
||||
<!-- GITCONTRIBUTOR_END -->
|
||||
|
||||
这是一个用于数据库的复杂且创新的工具, 我们的项目也在紧急的开发当中, 会陆续发布一些新的feature。如在使用当中有任何具体问题, 优先在项目下提issue, 如有需要, 请联系如下微信,我会尽力提供帮助,同时也非常欢迎大家参与到项目建设中。
|
||||
|
||||
<p align="center">
|
||||
<img src="./assets/DB_GPT_wechat.png" width="320px" />
|
||||
</p>
|
||||
|
||||
## Licence
|
||||
|
||||
The MIT License (MIT)
|
||||
|
||||
## Contact Information
|
||||
We are working on building a community, if you have any ideas about building the community, feel free to contact us. [Discord](https://discord.com/invite/twmZk3vv)
|
||||
|
@ -1,68 +0,0 @@
|
||||
name: db_pgt
|
||||
channels:
|
||||
- pytorch
|
||||
- defaults
|
||||
- anaconda
|
||||
dependencies:
|
||||
- python=3.10
|
||||
- cudatoolkit
|
||||
- pip
|
||||
- pytorch-mutex=1.0=cuda
|
||||
- pip:
|
||||
- pytorch
|
||||
- accelerate==0.16.0
|
||||
- aiohttp==3.8.4
|
||||
- aiosignal==1.3.1
|
||||
- async-timeout==4.0.2
|
||||
- attrs==22.2.0
|
||||
- bitsandbytes==0.37.0
|
||||
- cchardet==2.1.7
|
||||
- chardet==5.1.0
|
||||
- contourpy==1.0.7
|
||||
- cycler==0.11.0
|
||||
- filelock==3.9.0
|
||||
- fonttools==4.38.0
|
||||
- frozenlist==1.3.3
|
||||
- huggingface-hub==0.13.4
|
||||
- importlib-resources==5.12.0
|
||||
- kiwisolver==1.4.4
|
||||
- matplotlib==3.7.0
|
||||
- multidict==6.0.4
|
||||
- packaging==23.0
|
||||
- psutil==5.9.4
|
||||
- pycocotools==2.0.6
|
||||
- pyparsing==3.0.9
|
||||
- python-dateutil==2.8.2
|
||||
- pyyaml==6.0
|
||||
- regex==2022.10.31
|
||||
- tokenizers==0.13.2
|
||||
- tqdm==4.64.1
|
||||
- transformers==4.28.0
|
||||
- timm==0.6.13
|
||||
- spacy==3.5.1
|
||||
- webdataset==0.2.48
|
||||
- scikit-learn==1.2.2
|
||||
- scipy==1.10.1
|
||||
- yarl==1.8.2
|
||||
- zipp==3.14.0
|
||||
- omegaconf==2.3.0
|
||||
- opencv-python==4.7.0.72
|
||||
- iopath==0.1.10
|
||||
- tenacity==8.2.2
|
||||
- peft
|
||||
- pycocoevalcap
|
||||
- sentence-transformers
|
||||
- umap-learn
|
||||
- notebook
|
||||
- gradio==3.23
|
||||
- gradio-client==0.0.8
|
||||
- wandb
|
||||
- llama-index==0.5.27
|
||||
- pymysql
|
||||
- unstructured==0.6.3
|
||||
- pytesseract==0.3.10
|
||||
- markdown2
|
||||
- chromadb
|
||||
- colorama
|
||||
- playsound
|
||||
- distro
|
@ -7,12 +7,15 @@ import time
|
||||
import uuid
|
||||
from urllib.parse import urljoin
|
||||
import gradio as gr
|
||||
from pilot.configs.model_config import *
|
||||
from pilot.configs.config import Config
|
||||
from pilot.conversation import conv_qa_prompt_template, conv_templates
|
||||
from langchain.prompts import PromptTemplate
|
||||
|
||||
|
||||
vicuna_stream_path = "generate_stream"
|
||||
|
||||
CFG = Config()
|
||||
|
||||
def generate(query):
|
||||
|
||||
template_name = "conv_one_shot"
|
||||
@ -41,7 +44,7 @@ def generate(query):
|
||||
}
|
||||
|
||||
response = requests.post(
|
||||
url=urljoin(VICUNA_MODEL_SERVER, vicuna_stream_path), data=json.dumps(params)
|
||||
url=urljoin(CFG.MODEL_SERVER, vicuna_stream_path), data=json.dumps(params)
|
||||
)
|
||||
|
||||
skip_echo_len = len(params["prompt"]) + 1 - params["prompt"].count("</s>") * 3
|
||||
@ -54,7 +57,7 @@ def generate(query):
|
||||
yield(output)
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(LLM_MODEL)
|
||||
print(CFG.LLM_MODEL)
|
||||
with gr.Blocks() as demo:
|
||||
gr.Markdown("数据库SQL生成助手")
|
||||
with gr.Tab("SQL生成"):
|
||||
|
@ -1,7 +1,6 @@
|
||||
from pilot.source_embedding import (SourceEmbedding, register)
|
||||
|
||||
|
||||
__all__ = [
|
||||
"SourceEmbedding",
|
||||
"register"
|
||||
]
|
||||
]
|
||||
|
@ -2,24 +2,23 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
import nltk
|
||||
from typing import List
|
||||
|
||||
from auto_gpt_plugin_template import AutoGPTPluginTemplate
|
||||
from pilot.singleton import Singleton
|
||||
|
||||
|
||||
class Config(metaclass=Singleton):
|
||||
"""Configuration class to store the state of bools for different scripts access"""
|
||||
def __init__(self) -> None:
|
||||
"""Initialize the Config class"""
|
||||
|
||||
# TODO change model_config there
|
||||
|
||||
self.debug_mode = False
|
||||
self.skip_reprompt = False
|
||||
|
||||
self.temperature = float(os.getenv("TEMPERATURE", 0.7))
|
||||
|
||||
# TODO change model_config there
|
||||
|
||||
self.execute_local_commands = (
|
||||
os.getenv("EXECUTE_LOCAL_COMMANDS", "False") == "True"
|
||||
)
|
||||
@ -46,17 +45,12 @@ class Config(metaclass=Singleton):
|
||||
self.milvus_collection = os.getenv("MILVUS_COLLECTION", "dbgpt")
|
||||
self.milvus_secure = os.getenv("MILVUS_SECURE") == "True"
|
||||
|
||||
|
||||
self.authorise_key = os.getenv("AUTHORISE_COMMAND_KEY", "y")
|
||||
self.exit_key = os.getenv("EXIT_KEY", "n")
|
||||
self.image_provider = bool(os.getenv("IMAGE_PROVIDER", True))
|
||||
self.image_provider = os.getenv("IMAGE_PROVIDER", True)
|
||||
self.image_size = int(os.getenv("IMAGE_SIZE", 256))
|
||||
|
||||
self.plugins_dir = os.getenv("PLUGINS_DIR", "../../plugins")
|
||||
self.plugins: List[AutoGPTPluginTemplate] = []
|
||||
self.plugins_openai = []
|
||||
|
||||
self.command_registry = []
|
||||
|
||||
self.huggingface_api_token = os.getenv("HUGGINGFACE_API_TOKEN")
|
||||
self.image_provider = os.getenv("IMAGE_PROVIDER")
|
||||
self.image_size = int(os.getenv("IMAGE_SIZE", 256))
|
||||
@ -68,6 +62,10 @@ class Config(metaclass=Singleton):
|
||||
)
|
||||
self.speak_mode = False
|
||||
|
||||
|
||||
### Related configuration of built-in commands
|
||||
self.command_registry = []
|
||||
|
||||
disabled_command_categories = os.getenv("DISABLED_COMMAND_CATEGORIES")
|
||||
if disabled_command_categories:
|
||||
self.disabled_command_categories = disabled_command_categories.split(",")
|
||||
@ -78,6 +76,12 @@ class Config(metaclass=Singleton):
|
||||
os.getenv("EXECUTE_LOCAL_COMMANDS", "False") == "True"
|
||||
)
|
||||
|
||||
|
||||
### The associated configuration parameters of the plug-in control the loading and use of the plug-in
|
||||
self.plugins_dir = os.getenv("PLUGINS_DIR", "../../plugins")
|
||||
self.plugins: List[AutoGPTPluginTemplate] = []
|
||||
self.plugins_openai = []
|
||||
|
||||
plugins_allowlist = os.getenv("ALLOWLISTED_PLUGINS")
|
||||
if plugins_allowlist:
|
||||
self.plugins_allowlist = plugins_allowlist.split(",")
|
||||
@ -89,7 +93,21 @@ class Config(metaclass=Singleton):
|
||||
self.plugins_denylist = plugins_denylist.split(",")
|
||||
else:
|
||||
self.plugins_denylist = []
|
||||
|
||||
|
||||
|
||||
### Local database connection configuration
|
||||
self.LOCAL_DB_HOST = os.getenv("LOCAL_DB_HOST", "127.0.0.1")
|
||||
self.LOCAL_DB_PORT = int(os.getenv("LOCAL_DB_PORT", 3306))
|
||||
self.LOCAL_DB_USER = os.getenv("LOCAL_DB_USER", "root")
|
||||
self.LOCAL_DB_PASSWORD = os.getenv("LOCAL_DB_PASSWORD", "aa123456")
|
||||
|
||||
### LLM Model Service Configuration
|
||||
self.LLM_MODEL = os.getenv("LLM_MODEL", "vicuna-13b")
|
||||
self.LIMIT_MODEL_CONCURRENCY = int(os.getenv("LIMIT_MODEL_CONCURRENCY", 5))
|
||||
self.MAX_POSITION_EMBEDDINGS = int(os.getenv("MAX_POSITION_EMBEDDINGS", 4096))
|
||||
self.MODEL_SERVER = os.getenv("MODEL_SERVER", "http://121.41.167.183:8000")
|
||||
self.ISLOAD_8BIT = os.getenv("ISLOAD_8BIT", "True") == "True"
|
||||
|
||||
def set_debug_mode(self, value: bool) -> None:
|
||||
"""Set the debug mode value"""
|
||||
self.debug_mode = value
|
||||
|
@ -1,4 +1,4 @@
|
||||
#!/usr/bin/env python3
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding:utf-8 -*-
|
||||
|
||||
import torch
|
||||
|
@ -4,8 +4,16 @@
|
||||
import dataclasses
|
||||
from enum import auto, Enum
|
||||
from typing import List, Any
|
||||
from pilot.configs.model_config import DB_SETTINGS
|
||||
from pilot.configs.config import Config
|
||||
|
||||
CFG = Config()
|
||||
|
||||
DB_SETTINGS = {
|
||||
"user": CFG.LOCAL_DB_USER,
|
||||
"password": CFG.LOCAL_DB_PASSWORD,
|
||||
"host": CFG.LOCAL_DB_HOST,
|
||||
"port": CFG.LOCAL_DB_PORT
|
||||
}
|
||||
|
||||
class SeparatorStyle(Enum):
|
||||
SINGLE = auto()
|
||||
@ -91,7 +99,7 @@ class Conversation:
|
||||
def gen_sqlgen_conversation(dbname):
|
||||
from pilot.connections.mysql import MySQLOperator
|
||||
mo = MySQLOperator(
|
||||
**DB_SETTINGS
|
||||
**(DB_SETTINGS)
|
||||
)
|
||||
|
||||
message = ""
|
||||
@ -99,7 +107,7 @@ def gen_sqlgen_conversation(dbname):
|
||||
schemas = mo.get_schema(dbname)
|
||||
for s in schemas:
|
||||
message += s["schema_info"] + ";"
|
||||
return f"数据库{dbname}的Schema信息如下: {message}\n"
|
||||
return f"Database {dbname} Schema information as follows: {message}\n"
|
||||
|
||||
|
||||
conv_one_shot = Conversation(
|
||||
@ -162,7 +170,7 @@ auto_dbgpt_one_shot = Conversation(
|
||||
|
||||
|
||||
Schema:
|
||||
数据库gpt-user的Schema信息如下: users(city,create_time,email,last_login_time,phone,user_name);
|
||||
Database gpt-user Schema information as follows: users(city,create_time,email,last_login_time,phone,user_name);
|
||||
|
||||
|
||||
Commands:
|
||||
|
@ -2,21 +2,19 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import torch
|
||||
import warnings
|
||||
from pilot.singleton import Singleton
|
||||
|
||||
from transformers import (
|
||||
AutoTokenizer,
|
||||
AutoModelForCausalLM,
|
||||
AutoModel
|
||||
)
|
||||
|
||||
from pilot.model.compression import compress_module
|
||||
from pilot.model.adapter import get_llm_model_adapter
|
||||
|
||||
|
||||
class ModelLoader(metaclass=Singleton):
|
||||
"""Model loader is a class for model load
|
||||
|
||||
Args: model_path
|
||||
|
||||
|
||||
TODO: multi model support.
|
||||
"""
|
||||
|
||||
kwargs = {}
|
||||
@ -31,9 +29,11 @@ class ModelLoader(metaclass=Singleton):
|
||||
"device_map": "auto",
|
||||
}
|
||||
|
||||
# TODO multi gpu support
|
||||
def loader(self, num_gpus, load_8bit=False, debug=False):
|
||||
if self.device == "cpu":
|
||||
kwargs = {}
|
||||
|
||||
elif self.device == "cuda":
|
||||
kwargs = {"torch_dtype": torch.float16}
|
||||
if num_gpus == "auto":
|
||||
@ -46,18 +46,20 @@ class ModelLoader(metaclass=Singleton):
|
||||
"max_memory": {i: "13GiB" for i in range(num_gpus)},
|
||||
})
|
||||
else:
|
||||
# Todo Support mps for practise
|
||||
raise ValueError(f"Invalid device: {self.device}")
|
||||
|
||||
if "chatglm" in self.model_path:
|
||||
tokenizer = AutoTokenizer.from_pretrained(self.model_path, trust_remote_code=True)
|
||||
model = AutoModel.from_pretrained(self.model_path, trust_remote_code=True).half().cuda()
|
||||
else:
|
||||
tokenizer = AutoTokenizer.from_pretrained(self.model_path, use_fast=False)
|
||||
model = AutoModelForCausalLM.from_pretrained(self.model_path,
|
||||
low_cpu_mem_usage=True, **kwargs)
|
||||
|
||||
llm_adapter = get_llm_model_adapter(self.model_path)
|
||||
model, tokenizer = llm_adapter.loader(self.model_path, kwargs)
|
||||
|
||||
if load_8bit:
|
||||
compress_module(model, self.device)
|
||||
if num_gpus != 1:
|
||||
warnings.warn(
|
||||
"8-bit quantization is not supported for multi-gpu inference"
|
||||
)
|
||||
else:
|
||||
compress_module(model, self.device)
|
||||
|
||||
if (self.device == "cuda" and num_gpus == 1):
|
||||
model.to(self.device)
|
||||
|
@ -8,8 +8,9 @@ from langchain.embeddings.base import Embeddings
|
||||
from pydantic import BaseModel
|
||||
from typing import Any, Mapping, Optional, List
|
||||
from langchain.llms.base import LLM
|
||||
from pilot.configs.model_config import *
|
||||
from pilot.configs.config import Config
|
||||
|
||||
CFG = Config()
|
||||
class VicunaLLM(LLM):
|
||||
|
||||
vicuna_generate_path = "generate_stream"
|
||||
@ -22,7 +23,7 @@ class VicunaLLM(LLM):
|
||||
"stop": stop
|
||||
}
|
||||
response = requests.post(
|
||||
url=urljoin(VICUNA_MODEL_SERVER, self.vicuna_generate_path),
|
||||
url=urljoin(CFG.MODEL_SERVER, self.vicuna_generate_path),
|
||||
data=json.dumps(params),
|
||||
)
|
||||
|
||||
@ -51,7 +52,7 @@ class VicunaEmbeddingLLM(BaseModel, Embeddings):
|
||||
print("Sending prompt ", p)
|
||||
|
||||
response = requests.post(
|
||||
url=urljoin(VICUNA_MODEL_SERVER, self.vicuna_embedding_path),
|
||||
url=urljoin(CFG.MODEL_SERVER, self.vicuna_embedding_path),
|
||||
json={
|
||||
"prompt": p
|
||||
}
|
||||
|
@ -17,7 +17,7 @@ from pilot.logs import logger
|
||||
|
||||
def inspect_zip_for_modules(zip_path: str, debug: bool = False) -> list[str]:
|
||||
"""
|
||||
加载zip文件的插件,完全兼容Auto_gpt_plugin
|
||||
Loader zip plugin file. Native support Auto_gpt_plugin
|
||||
|
||||
Args:
|
||||
zip_path (str): Path to the zipfile.
|
||||
|
@ -42,7 +42,7 @@ class AutoModePrompt:
|
||||
prompt_generator: Optional[PromptGenerator] = None
|
||||
)-> str:
|
||||
"""
|
||||
基于用户输入的后续对话信息构建完整的prompt信息
|
||||
Build complete prompt information based on subsequent dialogue information entered by the user
|
||||
Args:
|
||||
self:
|
||||
prompt_generator:
|
||||
@ -69,7 +69,7 @@ class AutoModePrompt:
|
||||
if not self.ai_goals :
|
||||
self.ai_goals = user_input
|
||||
for i, goal in enumerate(self.ai_goals):
|
||||
full_prompt += f"{i+1}.根据提供的Schema信息, {goal}\n"
|
||||
full_prompt += f"{i+1}.According to the provided Schema information, {goal}\n"
|
||||
# if last_auto_return == None:
|
||||
# full_prompt += f"{cfg.last_plugin_return}\n\n"
|
||||
# else:
|
||||
@ -88,7 +88,7 @@ class AutoModePrompt:
|
||||
prompt_generator: Optional[PromptGenerator] = None
|
||||
) -> str:
|
||||
"""
|
||||
基于用户输入的初始对话信息构建完整的prompt信息
|
||||
Build complete prompt information based on the initial dialogue information entered by the user
|
||||
Args:
|
||||
self:
|
||||
prompt_generator:
|
||||
@ -128,7 +128,7 @@ class AutoModePrompt:
|
||||
if not self.ai_goals :
|
||||
self.ai_goals = fisrt_message
|
||||
for i, goal in enumerate(self.ai_goals):
|
||||
full_prompt += f"{i+1}.根据提供的Schema信息,{goal}\n"
|
||||
full_prompt += f"{i+1}.According to the provided Schema information,{goal}\n"
|
||||
if db_schemes:
|
||||
full_prompt += f"\nSchema:\n\n"
|
||||
full_prompt += f"{db_schemes}"
|
||||
|
@ -17,14 +17,17 @@ from peft import (
|
||||
import torch
|
||||
from datasets import load_dataset
|
||||
import pandas as pd
|
||||
from pilot.configs.config import Config
|
||||
|
||||
|
||||
from pilot.configs.model_config import DATA_DIR, LLM_MODEL, LLM_MODEL_CONFIG
|
||||
from pilot.configs.model_config import DATA_DIR, LLM_MODEL_CONFIG
|
||||
device = "cuda" if torch.cuda.is_available() else "cpu"
|
||||
CUTOFF_LEN = 50
|
||||
|
||||
df = pd.read_csv(os.path.join(DATA_DIR, "BTC_Tweets_Updated.csv"))
|
||||
|
||||
CFG = Config()
|
||||
|
||||
def sentiment_score_to_name(score: float):
|
||||
if score > 0:
|
||||
return "Positive"
|
||||
@ -49,7 +52,7 @@ with open(os.path.join(DATA_DIR, "alpaca-bitcoin-sentiment-dataset.json"), "w")
|
||||
data = load_dataset("json", data_files=os.path.join(DATA_DIR, "alpaca-bitcoin-sentiment-dataset.json"))
|
||||
print(data["train"])
|
||||
|
||||
BASE_MODEL = LLM_MODEL_CONFIG[LLM_MODEL]
|
||||
BASE_MODEL = LLM_MODEL_CONFIG[CFG.LLM_MODEL]
|
||||
model = LlamaForCausalLM.from_pretrained(
|
||||
BASE_MODEL,
|
||||
torch_dtype=torch.float16,
|
||||
|
@ -1,24 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
import uvicorn
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from typing import Optional, List
|
||||
from fastapi import FastAPI, Request, BackgroundTasks
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pilot.model.inference import generate_stream
|
||||
from pydantic import BaseModel
|
||||
|
||||
global_counter = 0
|
||||
model_semaphore = None
|
||||
|
||||
ROOT_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.append(ROOT_PATH)
|
||||
|
||||
from pilot.model.inference import generate_stream
|
||||
from pilot.model.inference import generate_output, get_embeddings
|
||||
|
||||
from pilot.model.loader import ModelLoader
|
||||
from pilot.configs.model_config import *
|
||||
|
||||
model_path = LLM_MODEL_CONFIG[LLM_MODEL]
|
||||
from pilot.configs.config import Config
|
||||
|
||||
|
||||
global_counter = 0
|
||||
model_semaphore = None
|
||||
CFG = Config()
|
||||
model_path = LLM_MODEL_CONFIG[CFG.LLM_MODEL]
|
||||
|
||||
ml = ModelLoader(model_path=model_path)
|
||||
model, tokenizer = ml.loader(num_gpus=1, load_8bit=ISLOAD_8BIT, debug=ISDEBUG)
|
||||
@ -60,7 +68,7 @@ def generate_stream_gate(params):
|
||||
tokenizer,
|
||||
params,
|
||||
DEVICE,
|
||||
MAX_POSITION_EMBEDDINGS,
|
||||
CFG.MAX_POSITION_EMBEDDINGS,
|
||||
):
|
||||
print("output: ", output)
|
||||
ret = {
|
||||
@ -84,7 +92,7 @@ async def api_generate_stream(request: Request):
|
||||
print(model, tokenizer, params, DEVICE)
|
||||
|
||||
if model_semaphore is None:
|
||||
model_semaphore = asyncio.Semaphore(LIMIT_MODEL_CONCURRENCY)
|
||||
model_semaphore = asyncio.Semaphore(CFG.LIMIT_MODEL_CONCURRENCY)
|
||||
await model_semaphore.acquire()
|
||||
|
||||
generator = generate_stream_gate(params)
|
||||
|
@ -6,6 +6,7 @@ import os
|
||||
import shutil
|
||||
import uuid
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import gradio as gr
|
||||
import datetime
|
||||
@ -14,13 +15,17 @@ from urllib.parse import urljoin
|
||||
|
||||
from langchain import PromptTemplate
|
||||
|
||||
from pilot.configs.model_config import DB_SETTINGS, KNOWLEDGE_UPLOAD_ROOT_PATH, LLM_MODEL_CONFIG
|
||||
|
||||
ROOT_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.append(ROOT_PATH)
|
||||
|
||||
from pilot.configs.model_config import KNOWLEDGE_UPLOAD_ROOT_PATH, LLM_MODEL_CONFIG
|
||||
from pilot.server.vectordb_qa import KnownLedgeBaseQA
|
||||
from pilot.connections.mysql import MySQLOperator
|
||||
from pilot.source_embedding.knowledge_embedding import KnowledgeEmbedding
|
||||
from pilot.vector_store.extract_tovec import get_vector_storelist, load_knownledge_from_doc, knownledge_tovec_st
|
||||
|
||||
from pilot.configs.model_config import LOGDIR, VICUNA_MODEL_SERVER, LLM_MODEL, DATASETS_DIR
|
||||
from pilot.configs.model_config import LOGDIR, DATASETS_DIR
|
||||
|
||||
from pilot.plugins import scan_plugins
|
||||
from pilot.configs.config import Config
|
||||
@ -30,6 +35,8 @@ from pilot.prompts.generator import PromptGenerator
|
||||
|
||||
from pilot.commands.exception_not_commands import NotCommands
|
||||
|
||||
|
||||
|
||||
from pilot.conversation import (
|
||||
default_conversation,
|
||||
conv_templates,
|
||||
@ -67,7 +74,15 @@ priority = {
|
||||
"vicuna-13b": "aaa"
|
||||
}
|
||||
|
||||
# 加载插件
|
||||
CFG= Config()
|
||||
|
||||
DB_SETTINGS = {
|
||||
"user": CFG.LOCAL_DB_USER,
|
||||
"password": CFG.LOCAL_DB_PASSWORD,
|
||||
"host": CFG.LOCAL_DB_HOST,
|
||||
"port": CFG.LOCAL_DB_PORT
|
||||
}
|
||||
def get_simlar(q):
|
||||
docsearch = knownledge_tovec_st(os.path.join(DATASETS_DIR, "plan.md"))
|
||||
docs = docsearch.similarity_search_with_score(q, k=1)
|
||||
@ -178,7 +193,7 @@ def http_bot(state, mode, sql_mode, db_selector, temperature, max_new_tokens, re
|
||||
print("是否是AUTO-GPT模式.", autogpt)
|
||||
|
||||
start_tstamp = time.time()
|
||||
model_name = LLM_MODEL
|
||||
model_name = CFG.LLM_MODEL
|
||||
|
||||
dbname = db_selector
|
||||
# TODO 这里的请求需要拼接现有知识库, 使得其根据现有知识库作答, 所以prompt需要继续优化
|
||||
@ -282,7 +297,7 @@ def http_bot(state, mode, sql_mode, db_selector, temperature, max_new_tokens, re
|
||||
logger.info(f"Requert: \n{payload}")
|
||||
|
||||
if sql_mode == conversation_sql_mode["auto_execute_ai_response"]:
|
||||
response = requests.post(urljoin(VICUNA_MODEL_SERVER, "generate"),
|
||||
response = requests.post(urljoin(CFG.MODEL_SERVER, "generate"),
|
||||
headers=headers, json=payload, timeout=120)
|
||||
|
||||
print(response.json())
|
||||
@ -330,7 +345,7 @@ def http_bot(state, mode, sql_mode, db_selector, temperature, max_new_tokens, re
|
||||
|
||||
try:
|
||||
# Stream output
|
||||
response = requests.post(urljoin(VICUNA_MODEL_SERVER, "generate_stream"),
|
||||
response = requests.post(urljoin(CFG.MODEL_SERVER, "generate_stream"),
|
||||
headers=headers, json=payload, stream=True, timeout=20)
|
||||
for chunk in response.iter_lines(decode_unicode=False, delimiter=b"\0"):
|
||||
if chunk:
|
||||
@ -606,12 +621,11 @@ if __name__ == "__main__":
|
||||
|
||||
args = parser.parse_args()
|
||||
logger.info(f"args: {args}")
|
||||
|
||||
# dbs = get_database_list()
|
||||
|
||||
# 加载插件
|
||||
# 配置初始化
|
||||
cfg = Config()
|
||||
|
||||
dbs = get_database_list()
|
||||
|
||||
cfg.set_plugins(scan_plugins(cfg, cfg.debug_mode))
|
||||
|
||||
# 加载插件可执行命令
|
||||
|
@ -40,8 +40,8 @@ def knownledge_tovec_st(filename):
|
||||
|
||||
|
||||
def load_knownledge_from_doc():
|
||||
"""从数据集当中加载知识
|
||||
# TODO 如果向量存储已经存在, 则无需初始化
|
||||
"""Loader Knownledge from current datasets
|
||||
# TODO if the vector store is exists, just use it.
|
||||
"""
|
||||
|
||||
if not os.path.exists(DATASETS_DIR):
|
||||
|
@ -40,15 +40,15 @@ class KnownLedge2Vector:
|
||||
|
||||
def init_vector_store(self):
|
||||
persist_dir = os.path.join(VECTORE_PATH, ".vectordb")
|
||||
print("向量数据库持久化地址: ", persist_dir)
|
||||
print("Vector store Persist address is: ", persist_dir)
|
||||
if os.path.exists(persist_dir):
|
||||
# 从本地持久化文件中Load
|
||||
print("从本地向量加载数据...")
|
||||
# Loader from local file.
|
||||
print("Loader data from local persist vector file...")
|
||||
vector_store = Chroma(persist_directory=persist_dir, embedding_function=self.embeddings)
|
||||
# vector_store.add_documents(documents=documents)
|
||||
else:
|
||||
documents = self.load_knownlege()
|
||||
# 重新初始化
|
||||
# reinit
|
||||
vector_store = Chroma.from_documents(documents=documents,
|
||||
embedding=self.embeddings,
|
||||
persist_directory=persist_dir)
|
||||
@ -61,17 +61,17 @@ class KnownLedge2Vector:
|
||||
for file in files:
|
||||
filename = os.path.join(root, file)
|
||||
docs = self._load_file(filename)
|
||||
# 更新metadata数据
|
||||
# update metadata.
|
||||
new_docs = []
|
||||
for doc in docs:
|
||||
doc.metadata = {"source": doc.metadata["source"].replace(DATASETS_DIR, "")}
|
||||
print("文档2向量初始化中, 请稍等...", doc.metadata)
|
||||
print("Documents to vector running, please wait...", doc.metadata)
|
||||
new_docs.append(doc)
|
||||
docments += new_docs
|
||||
return docments
|
||||
|
||||
def _load_file(self, filename):
|
||||
# 加载文件
|
||||
# Loader file
|
||||
if filename.lower().endswith(".pdf"):
|
||||
loader = UnstructuredFileLoader(filename)
|
||||
text_splitor = CharacterTextSplitter()
|
||||
|
@ -57,6 +57,9 @@ pymdown-extensions
|
||||
mkdocs
|
||||
requests
|
||||
gTTS==2.3.1
|
||||
langchain
|
||||
nltk
|
||||
python-dotenv==1.0.0
|
||||
|
||||
# Testing dependencies
|
||||
pytest
|
||||
|
Loading…
Reference in New Issue
Block a user