-
Notifications
You must be signed in to change notification settings - Fork 49
/
flask4multicache_demo.py
190 lines (159 loc) · 7.31 KB
/
flask4multicache_demo.py
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
# -*- coding: utf-8 -*-
import time
from flask import Flask, request
import logging
import json
from concurrent.futures import ThreadPoolExecutor
from modelcache_mm import cache
from modelcache_mm.adapter import adapter
from modelcache_mm.manager import CacheBase, VectorBase, get_data_manager
from modelcache_mm.similarity_evaluation.distance import SearchDistanceEvaluation
# from modelcache.processor.pre import query_multi_splicing
# from modelcache.processor.pre import insert_multi_splicing
# from modelcache.utils.model_filter import model_blacklist_filter
# from modelcache.embedding import Data2VecAudio
from modelcache_mm.processor.pre import mm_insert_dict
from modelcache_mm.processor.pre import mm_query_dict
from modelcache_mm.embedding import Clip2Vec
# 创建一个Flask实例
app = Flask(__name__)
def response_text(cache_resp):
return cache_resp['data']
def save_query_info(result, model, query, delta_time_log):
cache.data_manager.save_query_resp(result, model=model, query=json.dumps(query, ensure_ascii=False),
delta_time=delta_time_log)
def response_hitquery(cache_resp):
return cache_resp['hitQuery']
# data2vec = Data2VecAudio()
# data_manager = get_data_manager(CacheBase("sqlite"), VectorBase("faiss", dimension=data2vec.dimension))
image_dimension = 512
text_dimension = 512
clip2vec = Clip2Vec()
data_manager = get_data_manager(CacheBase("sqlite"), VectorBase("faiss",
mm_dimension=image_dimension+text_dimension,
i_dimension=image_dimension,
t_dimension=text_dimension))
cache.init(
embedding_func=clip2vec.to_embeddings,
data_manager=data_manager,
similarity_evaluation=SearchDistanceEvaluation(),
insert_pre_embedding_func=mm_insert_dict,
query_pre_embedding_func=mm_query_dict,
)
# cache.set_openai_key()
global executor
executor = ThreadPoolExecutor(max_workers=6)
@app.route('/welcome')
def first_flask(): # 视图函数
return 'hello, llms_cache!'
@app.route('/llms_cache', methods=['GET', 'POST'])
def user_backend():
try:
if request.method == 'POST':
request_data = request.json
elif request.method == 'GET':
request_data = request.args
param_dict = json.loads(request_data)
except Exception as e:
result = {"errorCode": 301, "errorDesc": str(e), "cacheHit": False, "delta_time": 0, "hit_query": '',
"answer": ''}
cache.data_manager.save_query_resp(result, model='', query='', delta_time=0)
return json.dumps(result)
# param parsing
try:
request_type = param_dict.get("request_type")
scope = param_dict.get("scope")
if scope is not None:
model = scope.get('model')
model = model.replace('-', '_')
model = model.replace('.', '_')
if request_type in ['query', 'insert']:
if request_type == 'query':
query = param_dict.get("query")
elif request_type == 'insert':
chat_info = param_dict.get("chat_info")
query = chat_info[-1]['query']
if request_type is None or request_type not in ['query', 'remove', 'insert', 'register']:
result = {"errorCode": 102,
"errorDesc": "type exception, should one of ['query', 'insert', 'remove', 'register']",
"cacheHit": False, "delta_time": 0, "hit_query": '', "answer": ''}
cache.data_manager.save_query_resp(result, model=model, query='', delta_time=0)
return json.dumps(result)
except Exception as e:
result = {"errorCode": 103, "errorDesc": str(e), "cacheHit": False, "delta_time": 0, "hit_query": '',
"answer": ''}
return json.dumps(result)
if request_type == 'query':
try:
start_time = time.time()
response = adapter.ChatCompletion.create_query(
scope={"model": model},
query=query,
)
delta_time = '{}s'.format(round(time.time() - start_time, 2))
if response is None:
result = {"errorCode": 0, "errorDesc": '', "cacheHit": False, "delta_time": delta_time,
"hit_query": '', "answer": ''}
elif isinstance(response, dict):
answer = response_text(response)
hit_query = response_hitquery(response)
result = {"errorCode": 0, "errorDesc": '', "cacheHit": True, "delta_time": delta_time,
"hit_query": hit_query, "answer": answer}
else:
result = {"errorCode": 201, "errorDesc": response, "cacheHit": False, "delta_time": delta_time,
"hit_query": '', "answer": ''}
delta_time_log = round(time.time() - start_time, 3)
future = executor.submit(save_query_info, result, model, query, delta_time_log)
except Exception as e:
raise e
return json.dumps(result, ensure_ascii=False)
if request_type == 'insert':
try:
start_time = time.time()
try:
response = adapter.ChatCompletion.create_insert(
model=model,
chat_info=chat_info,
)
except Exception as e:
raise e
if response == 'success':
result = {"errorCode": 0, "errorDesc": "", "writeStatus": "success"}
else:
result = {"errorCode": 301, "errorDesc": response, "writeStatus": "exception"}
insert_time = round(time.time() - start_time, 2)
return json.dumps(result, ensure_ascii=False)
except Exception as e:
raise e
if request_type == 'remove':
remove_type = param_dict.get("remove_type")
id_list = param_dict.get("id_list", [])
response = adapter.ChatCompletion.create_remove(
model=model,
remove_type=remove_type,
id_list=id_list
)
if not isinstance(response, dict):
result = {"errorCode": 401, "errorDesc": "", "response": response, "removeStatus": "exception"}
return json.dumps(result)
state = response.get('status')
# if response == 'success':
if state == 'success':
result = {"errorCode": 0, "errorDesc": "", "response": response, "writeStatus": "success"}
else:
result = {"errorCode": 402, "errorDesc": "", "response": response, "writeStatus": "exception"}
return json.dumps(result)
if request_type == 'register':
type = param_dict.get("type")
response = adapter.ChatCompletion.create_register(
model=model,
type=type
)
if response in ['create_success', 'already_exists']:
result = {"errorCode": 0, "errorDesc": "", "response": response, "writeStatus": "success"}
else:
result = {"errorCode": 502, "errorDesc": "", "response": response, "writeStatus": "exception"}
return json.dumps(result)
if __name__ == '__main__':
# app.run(host='0.0.0.0', port=5000, debug=True)
app.run(host='0.0.0.0', port=5000)