Sales_FastApi.py
15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import argparse
import hashlib
import importlib
import logging
import json
import os
import shutil
from datetime import datetime
from typing import Dict, List, Optional
# import nltk
import pydantic
import uvicorn
from uvicorn import Server
from fastapi import (Body, Depends, FastAPI, File, Form, HTTPException, Query,
Request, UploadFile, WebSocket, WebSocketDisconnect)
from fastapi.middleware.cors import CORSMiddleware
from fastapi.security import OAuth2PasswordBearer
from pydantic import BaseModel
from starlette.responses import RedirectResponse
from typing_extensions import Annotated
# from configs.model_config import (VS_ROOT_PATH, UPLOAD_ROOT_PATH, EMBEDDING_DEVICE,
# EMBEDDING_MODEL, LLM_MODEL, NLTK_DATA_PATH,
# VECTOR_SEARCH_TOP_K, LLM_HISTORY_LEN, OPEN_CROSS_DOMAIN)
from utilities.helper import LLMHelper
from uvicorn.config import Config
logger = logging.getLogger()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def verify_sign(token:str):
if token != "m_token":
raise HTTPException(status_code=400, detail="token is invalid")
# 组装签名方法
def assembling_sign():
appKey = "48e5e13229b82c1b4e6e8c96151f0637";
secret = "c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b";
current_time = datetime.now()
time_str = current_time.strftime('%Y-%m-%d %H:%M:%S')
params = {
"v": "1.0.0",
"method": "org.ore.api.example",
"appKey": appKey,
"format": "json",
"time": time_str
}
sign(params, None, secret)
def sign(param_values: Dict[str, str], ignore_param_names: List[str], secret: str) -> str:
try:
param_names = list(param_values.keys())
if ignore_param_names:
for param_name in ignore_param_names:
param_names.remove(param_name)
param_names.sort()
sb = []
sb.append(secret)
for param_name in param_names:
sb.append(param_name)
sb.append(param_values[param_name])
sb.append(secret)
sha1_digest = get_sha1_digest(''.join(sb))
return byte2hex(sha1_digest)
except Exception as e:
return None
def get_sha1_digest(data: str) -> bytes:
sha1_hash = hashlib.sha1()
sha1_hash.update(data.encode('utf-8'))
return sha1_hash.digest()
def byte2hex(bytes_data: bytes) -> str:
return ''.join('{:02X}'.format(b) for b in bytes_data)
class BaseResponse(BaseModel):
code: int = pydantic.Field(200, description="HTTP status code")
msg: str = pydantic.Field("success", description="HTTP status message")
class Config:
schema_extra = {
"example": {
"code": 200,
"msg": "success",
}
}
class ChatMessage(BaseModel):
question: str = pydantic.Field(..., description="Question text")
response: str = pydantic.Field(..., description="Response text")
history: str = pydantic.Field(..., description="History text")
source_documents: str = pydantic.Field(
..., description="List of source documents and their scores"
)
class Config:
schema_extra = {
"example": {
"question": "工伤保险如何办理?",
"response": "根据已知信息,可以总结如下:\n\n1. 参保单位为员工缴纳工伤保险费,以保障员工在发生工伤时能够获得相应的待遇。\n2. 不同地区的工伤保险缴费规定可能有所不同,需要向当地社保部门咨询以了解具体的缴费标准和规定。\n3. 工伤从业人员及其近亲属需要申请工伤认定,确认享受的待遇资格,并按时缴纳工伤保险费。\n4. 工伤保险待遇包括工伤医疗、康复、辅助器具配置费用、伤残待遇、工亡待遇、一次性工亡补助金等。\n5. 工伤保险待遇领取资格认证包括长期待遇领取人员认证和一次性待遇领取人员认证。\n6. 工伤保险基金支付的待遇项目包括工伤医疗待遇、康复待遇、辅助器具配置费用、一次性工亡补助金、丧葬补助金等。",
"history": [
[
"工伤保险是什么?",
"工伤保险是指用人单位按照国家规定,为本单位的职工和用人单位的其他人员,缴纳工伤保险费,由保险机构按照国家规定的标准,给予工伤保险待遇的社会保险制度。",
]
],
"source_documents": [
"出处 [1] 广州市单位从业的特定人员参加工伤保险办事指引.docx:\n\n\t( 一) 从业单位 (组织) 按“自愿参保”原则, 为未建 立劳动关系的特定从业人员单项参加工伤保险 、缴纳工伤保 险费。",
"出处 [2] ...",
"出处 [3] ...",
],
}
}
# 非流式Https接口
async def chat(
question: str = Body(..., description="Question", example="工伤保险是什么?"),
history: str = Body(..., description="history", example="历史?"),
# history: List[List[str]] = Body(
# [],
# description="History of previous questions and answers",
# example=[
# [
# "工伤保险是什么?",
# "工伤保险是指用人单位按照国家规定,为本单位的职工和用人单位的其他人员,缴纳工伤保险费,由保险机构按照国家规定的标准,给予工伤保险待遇的社会保险制度。",
# ]
# ],
# ),
# token: str = Depends(assembling_sign),
):
# for resp, history in local_doc_qa.llm._call(
# prompt=question, history=history, streaming=True
# ):
# pass
# llm_helper = LLMHelper()
# if len(question.strip()) != 0:
# question, result, _, sources = llm_helper.get_semantic_answer_lang_chain(question, "")
# else:
# return ChatMessage(question="",response="很抱歉,无法回答您的问题",history="",source_documents="",)
# return ChatMessage(
# question=question,
# response=result,
# history="",
# source_documents=sources,
# )
llm_helper = LLMHelper()
if len(question.strip()) != 0:
question, result, _, sources = llm_helper.get_semantic_answer_lang_chain(
question, history
)
else:
return ChatMessage(
question="",
response="很抱歉,无法回答您的问题",
history=history,
source_documents="",
)
return ChatMessage(
question=question,
response=result,
history=history,
source_documents=sources,
)
# 流式WebSocket接口
async def websocket_endpoint(ws: WebSocket, client_id: str):
await ws.accept()
print(f"已连接{client_id}")
logger.info(f"已连接{client_id}")
try:
while True:
# 接收客户端websocket发送过来的信息
data = await ws.receive_text()
print(f"{client_id}:收到消息:", data)
logger.info(f"{client_id}:收到消息:" + data)
json_dict = json.loads(data)
print(f"接受到的字符串{json_dict}")
logger.info(f"接受到的字符串{json_dict}")
type = json_dict.get("type", "chat")
question = json_dict.get("question", "")
history_str = json_dict.get("history", "empty")
history = []
if history_str != "empty":
print(f"接受到的历史记录{history_str}")
logger.info(f"接受到的历史记录{history_str}")
history_data = json.loads(history_str)
for item in history_data:
history.append((item.split("::")[0], item.split("::")[1]))
resp0 = ""
# for response, history in model.stream_chat(tokenizer, data, [], max_length= 2048,top_p= 0.7, temperature= 0.95):
# [f"{client_id}", f"{client_id}", f"{client_id}", f"{client_id}", f"{client_id}", f"{client_id}",
# f"{client_id}", f"{client_id}", f"{client_id}"]: #
# for response in predict(data, [], max_length=2048, top_p=0.7,temperature=0.95):
# for response, history in local_doc_qa.llm._call(
# prompt=json_dict["question"], history=history, streaming=True
# ):
# print(f"{client_id}:response:", response)
# res = response.replace(resp0, "")
# resp0 = response
# await ws.send_text(res)
# await ws.send_text("<rdfast stop>") # 自定义结束符
llm_helper = LLMHelper()
if len(question.strip()) != 0:
# 客户端接受的消息 如果标识结束 则进行结束总结
if type == "summarize":
print("summarize")
logger.info("summarize")
# 进行总结逻辑 增加总结提示语
# question, result = llm_helper.get_chat_GPT4_turbo_chain_stream(
# question, history
# )
# await ws.send_text(result)
# await ws.send_text("<rdfast stop>") # 自定义结束符
for result in llm_helper.get_chat_GPT4_turbo_chain_summarize_direct(
question, history
):
print(f"{client_id}:response:", result)
logger.info(f"{client_id}:response:" + result)
await ws.send_text(result)
await ws.send_text("<rdfast stop>") # 自定义结束符
elif type == "sparring":
print("sparring")
logger.info("sparring")
# 进行对练逻辑
for result in llm_helper.get_chat_GPT4_turbo_chain_sparring_direct(
question, history
):
print(f"{client_id}:response:", result)
logger.info(f"{client_id}:response:" + result)
await ws.send_text(result)
await ws.send_text("<rdfast stop>") # 自定义结束符
else:
print("chat")
logger.info("chat")
question, result, _, sources = (
llm_helper.get_semantic_answer_lang_chain(question, history)
)
logger.info(f"{client_id}:response:" + result)
await ws.send_text(result)
await ws.send_text("<rdfast stop>") # 自定义结束符
else:
return ChatMessage(
question="",
response="很抱歉,无法回答您的问题",
history=history,
source_documents="",
)
# return ChatMessage(
# question=question,
# response=result,
# history=history,
# source_documents=sources,
# )
# for response, history in local_doc_qa.llm._call(
# prompt=json_dict["question"], history=history, streaming=True
# ):
# print(f"{client_id}:response:", response)
# res = response.replace(resp0, "")
# resp0 = response
# await ws.send_text(res)
# await ws.send_text("<rdfast stop>") # 自定义结束符
except WebSocketDisconnect:
print(f"{client_id}:连接已断开")
except WebSocketDisconnect:
print(f"{client_id}:连接已断开")
async def websocket_endpoint_01(ws: WebSocket, client_id: str):
await ws.accept()
print(f'已连接{client_id}')
logger.info(f'已连接{client_id}')
try:
while True:
# 接收客户端websocket发送过来的信息
data = await ws.receive_text()
print(f'{client_id}:收到消息:', data)
logger.info(f"{client_id}:收到消息:" + data)
resp0 = ''
# for response, history in model.stream_chat(tokenizer, data, [], max_length= 2048,top_p= 0.7, temperature= 0.95):
# [f"{client_id}", f"{client_id}", f"{client_id}", f"{client_id}", f"{client_id}", f"{client_id}",
# f"{client_id}", f"{client_id}", f"{client_id}"]: #
# for response in predict(data, [], max_length=2048, top_p=0.7,temperature=0.95):
for response in "测试流式输出,测试流式输出,测试流式输出。over":
print(f'{client_id}:response:', response)
logger.info(f"{client_id}:response:", response)
res = response.replace(resp0, '')
resp0 = response
await ws.send_text(res)
await ws.send_text('<rdfast stop>') # 自定义结束符
except WebSocketDisconnect:
print(f'{client_id}:连接已断开')
async def document():
return RedirectResponse(url="/docs")
def api_start(host, port):
global app
global local_doc_qa
app = FastAPI(dependencies=[Depends(verify_sign)])
app = FastAPI()
# app.add_middleware(CORSMiddleware,allow_methods=[verify_sign])
# Add CORS middleware to allow all origins
# 在config.py中设置OPEN_DOMAIN=True,允许跨域
# set OPEN_DOMAIN=True in config.py to allow cross-domain
if True:
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# app.websocket("/local_doc_qa/stream-chat/{knowledge_base_id}")(stream_chat)
app.get("/", response_model=BaseResponse)(document)
app.post("/router/scrm.api.knowledge.gptchat/1.0.0", response_model=ChatMessage)(chat)
# app.post("/local_doc_qa/upload_file", response_model=BaseResponse)(upload_file)
# app.post("/local_doc_qa/upload_files", response_model=BaseResponse)(upload_files)
# app.post("/local_doc_qa/local_doc_chat", response_model=ChatMessage)(local_doc_chat)
# app.get("/local_doc_qa/list_files", response_model=ListDocsResponse)(list_docs)
# app.delete("/local_doc_qa/delete_file", response_model=BaseResponse)(delete_docs)
app.websocket("/ws/{client_id}")(websocket_endpoint)
# 测试WS连接代码
app.websocket("/ws1/{client_id}")(websocket_endpoint_01)
# config = uvicorn.Config(app, host=host, port=port, workers=8)
# uvicorn.run(config)
# 设置workers 根据机器的CPU核心数,分配给FastAPI的进程数
uvicorn_config = uvicorn.Config(
app=app,
host=host,
port=port,
workers=4,
)
Server(uvicorn_config).run()
# uvicorn.run(app, host=host, port=port, workers=8)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
# parser.add_argument("--host", type=str, default="192.168.3.191")
# parser.add_argument("--host", type=str, default="127.0.0.1")
parser.add_argument("--host", type=str, default="0.0.0.0")
parser.add_argument("--port", type=int, default=7864)
args = parser.parse_args()
api_start(args.host, args.port)
# build_middleware_stack = verify_sign(request="192.168.1.124/chat")