Merge pull request #78 from SmartFlowAI/dev

Dev
This commit is contained in:
xzw 2024-03-16 18:41:25 +08:00 committed by GitHub
commit 660e36b952
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 163 additions and 0 deletions

View File

@ -225,6 +225,7 @@ git clone https://github.com/SmartFlowAI/EmoLLM.git
该项目签署了 MIT 授权许可,详情请参阅 [LICENSE](https://github.com/SmartFlowAI/EmoLLM/blob/main/LICENSE)
### 引用
如果本项目对您的工作有所帮助,请使用以下格式引用:
@ -276,6 +277,7 @@ git clone https://github.com/SmartFlowAI/EmoLLM.git
[OpenXLab_App-url]: https://openxlab.org.cn/apps/detail/Farewell1/EmoLLMV2.0
[OpenXLab_Model-url]: https://openxlab.org.cn/models/detail/ajupyter/EmoLLM_internlm2_7b_full
## 交流群
- 如果失效请移步Issue区

85
deploy/api-file.py Normal file
View File

@ -0,0 +1,85 @@
from fastapi import FastAPI, Request
from transformers import AutoTokenizer, AutoModelForCausalLM, GenerationConfig
import uvicorn
import json
import datetime
import torch
# 设置设备参数
DEVICE = "cuda" # 使用CUDA
DEVICE_ID = "0" # CUDA设备ID如果未设置则为空
CUDA_DEVICE = f"{DEVICE}:{DEVICE_ID}" if DEVICE_ID else DEVICE # 组合CUDA设备信息
# 加载模型
from transformers.utils import logging
from openxlab.model import download
logger = logging.get_logger(__name__)
# 可修改
download(model_repo='ajupyter/EmoLLM_aiwei',
output='model')
# 清理GPU内存函数
def torch_gc():
if torch.cuda.is_available(): # 检查是否可用CUDA
with torch.cuda.device(CUDA_DEVICE): # 指定CUDA设备
torch.cuda.empty_cache() # 清空CUDA缓存
torch.cuda.ipc_collect() # 收集CUDA内存碎片
# 创建FastAPI应用
app = FastAPI()
# 处理POST请求的端点
@app.post("/")
async def create_item(request: Request):
global model, tokenizer # 声明全局变量以便在函数内部使用模型和分词器
json_post_raw = await request.json() # 获取POST请求的JSON数据
json_post = json.dumps(json_post_raw) # 将JSON数据转换为字符串
json_post_list = json.loads(json_post) # 将字符串转换为Python对象
prompt = json_post_list.get('prompt') # 获取请求中的提示
history = json_post_list.get('history') # 获取请求中的历史记录
max_length = json_post_list.get('max_length') # 获取请求中的最大长度
top_p = json_post_list.get('top_p') # 获取请求中的top_p参数
temperature = json_post_list.get('temperature') # 获取请求中的温度参数
# 调用模型进行对话生成
response, history = model.chat(
tokenizer,
prompt,
history=history,
max_length=max_length if max_length else 2048, # 如果未提供最大长度默认使用2048
top_p=top_p if top_p else 0.7, # 如果未提供top_p参数默认使用0.7
temperature=temperature if temperature else 0.95 # 如果未提供温度参数默认使用0.95
)
now = datetime.datetime.now() # 获取当前时间
time = now.strftime("%Y-%m-%d %H:%M:%S") # 格式化时间为字符串
# 构建响应JSON
answer = {
"response": response,
"history": history,
"status": 200,
"time": time
}
# 构建日志信息
log = "[" + time + "] " + '", prompt:"' + prompt + '", response:"' + repr(response) + '"'
print(log) # 打印日志
torch_gc() # 执行GPU内存清理
return answer # 返回响应
# 主函数入口
if __name__ == '__main__':
# 加载预训练的分词器和模型
tokenizer = AutoTokenizer.from_pretrained("model", trust_remote_code=True)
model = (
AutoModelForCausalLM.from_pretrained("model", device_map="auto", trust_remote_code=True)
.to(torch.bfloat16)
.cuda()
)
# model = AutoModelForCausalLM.from_pretrained("model", device_map="auto", trust_remote_code=True).eval()
model.generation_config = GenerationConfig(max_length=2048, top_p=0.7, temperature=0.95) # 可指定
model.eval() # 设置模型为评估模式
# 启动FastAPI应用
# 用6006端口可以将autodl的端口映射到本地从而在本地使用api
uvicorn.run(app, host='127.0.0.1', port=6006, workers=1) # 在指定端口和主机上启动应用

View File

@ -0,0 +1,76 @@
# EmoLLM RAG
## **模块目的**
根据用户的问题,检索对应信息以增强回答的专业性, 使EmoLLM的回答更加专业可靠。检索内容包括但不限于以下几点
- 心理学相关理论
- 心理学方法论
- 经典案例
- 客户背景知识
## **数据集**
- 经过清洗的QA对: 每一个QA对作为一个样本进行 embedding
- 经过筛选的TXT文本
- 直接对TXT文本生成embedding (基于token长度进行切分)
- 过滤目录等无关信息后对TXT文本生成embedding (基于token长度进行切分)
- 过滤目录等无关信息后, 对TXT进行语意切分生成embedding
- 按照目录结构对TXT进行拆分构架层级关系生成embedding
数据集合构建的详情,请参考 [qa_generation_README](https://github.com/SmartFlowAI/EmoLLM/blob/ccfa75c493c4685e84073dfbc53c50c09a2988e3/scripts/qa_generation/README.md)
## **相关组件**
### [BCEmbedding](https://github.com/netease-youdao/BCEmbedding?tab=readme-ov-file)
- [bce-embedding-base_v1](https://hf-mirror.com/maidalun1020/bce-embedding-base_v1): embedding 模型,用于构建 vector DB
- [bce-reranker-base_v1](https://hf-mirror.com/maidalun1020/bce-reranker-base_v1): rerank 模型,用于对检索回来的文章段落重排
### [Langchain](https://python.langchain.com/docs/get_started)
LangChain 是一个开源框架用于构建基于大型语言模型LLM的应用程序。LangChain 提供各种工具和抽象,以提高模型生成的信息的定制性、准确性和相关性。
### [FAISS](https://faiss.ai/)
Faiss是一个用于高效相似性搜索和密集向量聚类的库。它包含的算法可以搜索任意大小的向量集。由于langchain已经整合过FAISS因此本项目中不在基于原生文档开发[FAISS in Langchain](https://python.langchain.com/docs/integrations/vectorstores/faiss)
### [RAGAS](https://github.com/explodinggradients/ragas)
RAG的经典评估框架通过以下三个方面进行评估:
- Faithfulness: 给出的答案应该是以给定上下文为基础生成的。
- Answer Relevance: 生成的答案应该可以解决提出的实际问题。
- Context Relevance: 检索回来的信息应该是高度集中的,尽量少的包含不相关信息。
后续增加了更多的评判指标例如context recall 等
## **方案细节**
### RAG具体流程
- 根据数据集构建vector DB
- 对用户输入的问题进行embedding
- 基于embedding结果在向量数据库中进行检索
- 对召回数据重排序
- 依据用户问题和召回数据生成最后的结果
**Noted**: 当用户选择使用RAG时才会进行上述流程
### 后续增强
- 将RAGAS评判结果加入到生成流程中。例如当生成结果无法解决用户问题时需要重新生成
- 增加web检索以处理vector DB中无法检索到对应信息的问题
- 增加多路检索以增加召回率。即根据用户输入生成多个类似的query进行检索