cacheai 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cacheai/__init__.py +48 -0
- cacheai/cache_operation.py +391 -0
- cacheai/client.py +264 -0
- cacheai/exceptions.py +67 -0
- cacheai/resources/__init__.py +5 -0
- cacheai/resources/chat.py +114 -0
- cacheai/types.py +120 -0
- cacheai/version.py +4 -0
- cacheai-0.1.0.dist-info/METADATA +317 -0
- cacheai-0.1.0.dist-info/RECORD +12 -0
- cacheai-0.1.0.dist-info/WHEEL +5 -0
- cacheai-0.1.0.dist-info/top_level.txt +1 -0
cacheai/__init__.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""CacheAI Python API."""
|
|
2
|
+
|
|
3
|
+
from cacheai.version import __version__
|
|
4
|
+
from cacheai.client import Client
|
|
5
|
+
from cacheai.exceptions import (
|
|
6
|
+
CacheAIError,
|
|
7
|
+
AuthenticationError,
|
|
8
|
+
PermissionDeniedError,
|
|
9
|
+
NotFoundError,
|
|
10
|
+
RateLimitError,
|
|
11
|
+
APIError,
|
|
12
|
+
TimeoutError,
|
|
13
|
+
ConnectionError,
|
|
14
|
+
ValidationError,
|
|
15
|
+
)
|
|
16
|
+
from cacheai.types import (
|
|
17
|
+
ChatCompletion,
|
|
18
|
+
ChatCompletionChunk,
|
|
19
|
+
ChatMessage,
|
|
20
|
+
Completion,
|
|
21
|
+
Model,
|
|
22
|
+
ModelList,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
# Note: CacheDB-related modules (db, manager, utils) are managed in GitLab
|
|
26
|
+
# but not included in the public GitHub/PyPI release
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
"__version__",
|
|
30
|
+
"Client",
|
|
31
|
+
# Exceptions
|
|
32
|
+
"CacheAIError",
|
|
33
|
+
"AuthenticationError",
|
|
34
|
+
"PermissionDeniedError",
|
|
35
|
+
"NotFoundError",
|
|
36
|
+
"RateLimitError",
|
|
37
|
+
"APIError",
|
|
38
|
+
"TimeoutError",
|
|
39
|
+
"ConnectionError",
|
|
40
|
+
"ValidationError",
|
|
41
|
+
# Types
|
|
42
|
+
"ChatCompletion",
|
|
43
|
+
"ChatCompletionChunk",
|
|
44
|
+
"ChatMessage",
|
|
45
|
+
"Completion",
|
|
46
|
+
"Model",
|
|
47
|
+
"ModelList",
|
|
48
|
+
]
|
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
import argparse
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
import os
|
|
5
|
+
import numpy as np
|
|
6
|
+
|
|
7
|
+
import cv2
|
|
8
|
+
import matplotlib.pyplot as plt
|
|
9
|
+
import math
|
|
10
|
+
import time
|
|
11
|
+
|
|
12
|
+
from PIL import Image, ImageDraw, ImageFont
|
|
13
|
+
import ggutils.s3_access as s3_access
|
|
14
|
+
|
|
15
|
+
import smalltrain as st
|
|
16
|
+
from smalltrain.model.operation import Operation
|
|
17
|
+
from smalltrain.utils.tf_util import SavedModel
|
|
18
|
+
|
|
19
|
+
from cacheai.utils import image_util
|
|
20
|
+
from cacheai.db import CacheDB
|
|
21
|
+
from cacheai.manager.cache_manager import CacheManager
|
|
22
|
+
from cacheai.utils import hash_util
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class CacheAIOperation(Operation):
|
|
26
|
+
'''Operation class as hyper parameter of train or prediction operation
|
|
27
|
+
Arguments:
|
|
28
|
+
params: A dictionary that maps hyper parameter keys and values
|
|
29
|
+
debug_mode: Boolean, if `True` then running with debug mode.
|
|
30
|
+
'''
|
|
31
|
+
|
|
32
|
+
def __init__(self, hparams=None, setting_file_path=None):
|
|
33
|
+
super().__init__(hparams, setting_file_path)
|
|
34
|
+
print('CacheAIOperation init hparams_dict: {}'.format(self.hparams_dict))
|
|
35
|
+
|
|
36
|
+
self.debug_mode = True
|
|
37
|
+
self.prediction_mode = False
|
|
38
|
+
|
|
39
|
+
self.label_character_dict = image_util.get_label_character_dict()
|
|
40
|
+
# print('label_character_dict: {}'.format(self.label_character_dict))
|
|
41
|
+
self.character_label_dict = {v: k for k, v in self.label_character_dict.items()}
|
|
42
|
+
|
|
43
|
+
self.model_id = 'SCR'
|
|
44
|
+
self.cache_input_layer_name = self.hparams_dict.get('cache_input_layer_name')
|
|
45
|
+
# self.cache_output_layer_name = 'model/fc/output_middle_layer'
|
|
46
|
+
self.cache_output_layer_name = 'model/output'
|
|
47
|
+
print('CacheAIOperation init cache_input_layer_name: {}'.format(self.cache_input_layer_name))
|
|
48
|
+
|
|
49
|
+
def test(self, img_file_path):
|
|
50
|
+
# TODO test with splitted models
|
|
51
|
+
return
|
|
52
|
+
|
|
53
|
+
test_img = cv2.imread(img_file_path)
|
|
54
|
+
print('test_img: {}'.format(test_img))
|
|
55
|
+
output = self.predict(input=test_img)
|
|
56
|
+
label = np.argmax(output)
|
|
57
|
+
detected_character = self.label_character_dict.get(label)
|
|
58
|
+
print('detected_character: {}'.format(detected_character))
|
|
59
|
+
|
|
60
|
+
def predict(self, input):
|
|
61
|
+
saved_model_dir_path = self.hparams_dict.get('saved_model_dir_path')
|
|
62
|
+
if saved_model_dir_path:
|
|
63
|
+
print('predict by saved model')
|
|
64
|
+
output = self.saved_model.predict_single_data(input)
|
|
65
|
+
else:
|
|
66
|
+
print('predict by restored model')
|
|
67
|
+
output = self.model.predict_single_data(input)
|
|
68
|
+
print('Predicted output: {}'.format(output))
|
|
69
|
+
return output
|
|
70
|
+
|
|
71
|
+
def create_cache_manager(self):
|
|
72
|
+
manager = CacheManager(model_ins=self.model, model_id=self.model_id,
|
|
73
|
+
cache_input_layer_name=self.cache_input_layer_name,
|
|
74
|
+
cache_output_layer_name=self.cache_output_layer_name)
|
|
75
|
+
print('get_cache_size: {}'.format(manager.get_cache_size()))
|
|
76
|
+
self.manager = manager
|
|
77
|
+
return manager
|
|
78
|
+
|
|
79
|
+
def test_generate_text_matrix_image(self, target_character='日', rotate_angle=5):
|
|
80
|
+
img, text_matrix, whole_img = image_util.generate_text_matrix_image(character=target_character,
|
|
81
|
+
rotate_angle=rotate_angle)
|
|
82
|
+
print('generate_text_matrix_image: {}, target_character: {}'.format(text_matrix, target_character))
|
|
83
|
+
|
|
84
|
+
def bench(self, iterr=None, with_cache=False, target_character_list=['日'], manager=None):
|
|
85
|
+
|
|
86
|
+
manager = manager or self.create_cache_manager()
|
|
87
|
+
|
|
88
|
+
input_hash_dict = {}
|
|
89
|
+
cache_dict = {}
|
|
90
|
+
|
|
91
|
+
sources = 2 ** 8
|
|
92
|
+
|
|
93
|
+
total_cnt = 0
|
|
94
|
+
accurate_cnt = 0
|
|
95
|
+
|
|
96
|
+
# Check character_label_dict
|
|
97
|
+
for target_character in target_character_list:
|
|
98
|
+
_label = self.character_label_dict.get(target_character)
|
|
99
|
+
print('target_character: {}, _label: {}'.format(target_character, _label))
|
|
100
|
+
|
|
101
|
+
print('iterr: {}'.format(iterr))
|
|
102
|
+
if iterr is None:
|
|
103
|
+
# rotate_angle_list = list(range(-3, 3))
|
|
104
|
+
# rotate_angle_list = [0] * 10
|
|
105
|
+
# width_list = list(range(31, 34))
|
|
106
|
+
# width_list = [32] * 3
|
|
107
|
+
rotate_angle_list = [0]
|
|
108
|
+
|
|
109
|
+
width_list = list(range(31, 34))
|
|
110
|
+
# tx_list = list(range(-3, 3))
|
|
111
|
+
# ty_list = list(range(-3, 3))
|
|
112
|
+
tx_list = list(range(-1, 1))
|
|
113
|
+
ty_list = list(range(-1, 1))
|
|
114
|
+
tx_list = list(range(-2, 2))
|
|
115
|
+
ty_list = list(range(-2, 2))
|
|
116
|
+
|
|
117
|
+
_debug_mode = False
|
|
118
|
+
if _debug_mode:
|
|
119
|
+
tx_list = [0]
|
|
120
|
+
ty_list = [0]
|
|
121
|
+
rotate_angle_list = [0]
|
|
122
|
+
|
|
123
|
+
iterr = len(width_list) * len(tx_list) * len(ty_list) * len(rotate_angle_list) * len(target_character_list)
|
|
124
|
+
|
|
125
|
+
else:
|
|
126
|
+
rotate_angle_list = list(range(-5, 5))
|
|
127
|
+
width_list = [32] * int(iterr / len(rotate_angle_list))
|
|
128
|
+
tx_list = [0]
|
|
129
|
+
ty_list = [0] * 32
|
|
130
|
+
iterr = len(width_list) * len(tx_list) * len(ty_list) * len(rotate_angle_list) * len(target_character_list)
|
|
131
|
+
print(len(width_list))
|
|
132
|
+
print('iterr set: {}'.format(iterr))
|
|
133
|
+
|
|
134
|
+
if not with_cache:
|
|
135
|
+
# Export fc last layer
|
|
136
|
+
target_character = target_character_list[0]
|
|
137
|
+
img, _, _ = image_util.generate_text_matrix_image(character=target_character, width=width_list[0],
|
|
138
|
+
tx=0, ty=0, rotate_angle=0.0)
|
|
139
|
+
_input_batch = [np.asarray(img)]
|
|
140
|
+
W_fc_last_values = manager.model_ins.sess.run(
|
|
141
|
+
manager.W_fc_last,
|
|
142
|
+
feed_dict={manager.model_ins.x: _input_batch,
|
|
143
|
+
manager.model_ins.is_train: False,
|
|
144
|
+
manager.model_ins.keep_prob: 1}
|
|
145
|
+
)
|
|
146
|
+
print('W_fc_last_values.shape: {}'.format(W_fc_last_values.shape))
|
|
147
|
+
_export_path = './W_fc_last_values.csv'
|
|
148
|
+
np.savetxt(_export_path, W_fc_last_values, delimiter=",")
|
|
149
|
+
_label = self.character_label_dict.get(target_character)
|
|
150
|
+
_export_path = './W_fc_last_values_c{}.csv'.format(_label)
|
|
151
|
+
np.savetxt(_export_path, W_fc_last_values[:, _label], delimiter=",")
|
|
152
|
+
W_fc_last_values_label = W_fc_last_values[:, _label]
|
|
153
|
+
W_fc_last_values_sorted = W_fc_last_values[:, _label].copy()
|
|
154
|
+
W_fc_last_index_list = np.argsort(W_fc_last_values_sorted)[::-1]
|
|
155
|
+
W_fc_last_values_sorted = np.asarray([[_index, W_fc_last_values_label[_index]] for _index in W_fc_last_index_list])
|
|
156
|
+
print('W_fc_last_values_sorted.shape: {}'.format(W_fc_last_values_sorted.shape))
|
|
157
|
+
_export_path = './W_fc_last_values_sorted_c{}.csv'.format(_label)
|
|
158
|
+
np.savetxt(_export_path, W_fc_last_values_sorted, delimiter=",")
|
|
159
|
+
|
|
160
|
+
sum_time_generate_text_matrix_image = 0
|
|
161
|
+
sum_time_get_output = 0
|
|
162
|
+
sum_lap_time_get_output = 0
|
|
163
|
+
sum_lap_time_get_output_list = [0] * int(iterr / 100 + 1)
|
|
164
|
+
|
|
165
|
+
start_time = time.time()
|
|
166
|
+
for target_character in target_character_list:
|
|
167
|
+
accurate_output = self.character_label_dict.get(target_character)
|
|
168
|
+
|
|
169
|
+
for width in width_list:
|
|
170
|
+
for tx in tx_list:
|
|
171
|
+
for ty in ty_list:
|
|
172
|
+
for rotate_angle in rotate_angle_list:
|
|
173
|
+
print('width: {}, tx: {}, ty: {}, rotate_angle: {}'.format(
|
|
174
|
+
width, tx, ty, rotate_angle))
|
|
175
|
+
|
|
176
|
+
start_time_generate_text_matrix_image = time.time()
|
|
177
|
+
# img = character_image(character=target_character, width=width, tx=x, ty=y, noise_source=noise_source)
|
|
178
|
+
img, _, _ = image_util.generate_text_matrix_image(character=target_character, width=width,
|
|
179
|
+
tx=tx, ty=ty, rotate_angle=rotate_angle)
|
|
180
|
+
sum_time_generate_text_matrix_image += (time.time() - start_time_generate_text_matrix_image)
|
|
181
|
+
|
|
182
|
+
input_hash = hash_util.to_hash(np.asarray(img).reshape(-1).astype('int8'))
|
|
183
|
+
|
|
184
|
+
output_value = None
|
|
185
|
+
cache_key = None
|
|
186
|
+
info_value = {'input_hash': input_hash, 'output_value': output_value,
|
|
187
|
+
'cache_key': cache_key,
|
|
188
|
+
'cache_input_value': None,
|
|
189
|
+
'character': target_character, 'rotate_angle': rotate_angle, 'width': width}
|
|
190
|
+
|
|
191
|
+
start_time_get_output = time.time()
|
|
192
|
+
if with_cache:
|
|
193
|
+
output_value, cache_key, cache_input_value = manager.get_output_from_cache(np.asarray(img))
|
|
194
|
+
|
|
195
|
+
info_value['cache_key'] = cache_key
|
|
196
|
+
cache_dict[cache_key] = input_hash
|
|
197
|
+
# Store also cache_input_value
|
|
198
|
+
info_value['cache_input_value'] = cache_input_value
|
|
199
|
+
|
|
200
|
+
else:
|
|
201
|
+
_input_batch = [np.asarray(img)]
|
|
202
|
+
|
|
203
|
+
output_value = manager.model_ins.sess.run(
|
|
204
|
+
manager.cache_output_layer,
|
|
205
|
+
feed_dict={manager.model_ins.x: _input_batch,
|
|
206
|
+
manager.model_ins.is_train: False,
|
|
207
|
+
manager.model_ins.keep_prob: 1}
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
_lap_time = (time.time() - start_time_get_output)
|
|
211
|
+
sum_time_get_output += _lap_time
|
|
212
|
+
sum_lap_time_get_output += _lap_time
|
|
213
|
+
|
|
214
|
+
# print('output_value: {}'.format(output_value))
|
|
215
|
+
# output_value = np.asarray(output_value).reshape(-1)[0]
|
|
216
|
+
output_value = output_value[0]
|
|
217
|
+
output_label = np.argmax(output_value, axis=0).astype(np.int)
|
|
218
|
+
output_character = self.label_character_dict.get(output_label)
|
|
219
|
+
|
|
220
|
+
info_value['output_value'] = output_value
|
|
221
|
+
info_value['output_label'] = output_label
|
|
222
|
+
info_value['output_character'] = output_character
|
|
223
|
+
# print('output_value: {}'.format(output_value))
|
|
224
|
+
if output_label == accurate_output:
|
|
225
|
+
accurate_cnt += 1
|
|
226
|
+
input_hash_dict[input_hash] = info_value
|
|
227
|
+
|
|
228
|
+
total_cnt += 1
|
|
229
|
+
if total_cnt % 100 == 0:
|
|
230
|
+
lap_time = time.time() - start_time
|
|
231
|
+
|
|
232
|
+
print(
|
|
233
|
+
'{} % Done, spent {} sec ({} sec/image) \n for generate_text_matrix_image {} sec/image \n for get_output {} sec/image'.format(
|
|
234
|
+
100 * total_cnt / iterr,
|
|
235
|
+
lap_time, lap_time / total_cnt,
|
|
236
|
+
sum_time_generate_text_matrix_image / total_cnt,
|
|
237
|
+
sum_time_get_output / total_cnt))
|
|
238
|
+
print('output_label: {}, output_character: {}, accurate_output: {}'.format(output_label, output_character, accurate_output))
|
|
239
|
+
print('width: {}, tx: {}, ty: {}, rotate_angle: {}'.format(width, tx, ty, rotate_angle))
|
|
240
|
+
print('=' * 20)
|
|
241
|
+
|
|
242
|
+
sum_lap_time_get_output_list[int(total_cnt / 100)] = sum_lap_time_get_output
|
|
243
|
+
sum_lap_time_get_output = 0
|
|
244
|
+
|
|
245
|
+
total_time = time.time() - start_time
|
|
246
|
+
print('{} % Done with total_time: {} sec'.format(100 * total_cnt / iterr, total_time))
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
return input_hash_dict, cache_dict, accurate_cnt, total_cnt, sum_lap_time_get_output_list, total_time, sum_time_get_output
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
MODE_TEST = 'test'
|
|
253
|
+
|
|
254
|
+
# TEST_IMG_FILE_PATH = '/var/data/smalltrain-ocr/single_character/images/t花_c2016_w32_fipaexm-ttf_bNone_i0.jpg'
|
|
255
|
+
TEST_IMG_FILE_PATH = '/var/data/japanese-paper/images/t花_c2116_w32_fipaexg-ttf_b-var-data-japanese-paper-master-background-paper-paper_1-jpg_i0.jpg'
|
|
256
|
+
|
|
257
|
+
def main(exec_param):
|
|
258
|
+
print(exec_param)
|
|
259
|
+
operation = CacheAIOperation(setting_file_path=exec_param['setting_file_path'])
|
|
260
|
+
mode = (exec_param['mode'] or MODE_TEST).lower() # Default mode
|
|
261
|
+
print('exec_param: {}'.format(exec_param))
|
|
262
|
+
operation_id = operation.hparams_dict.get("operation_id") or operation.hparams_dict.get("train_id")
|
|
263
|
+
|
|
264
|
+
if exec_param.get('saved_model_dir_path'):
|
|
265
|
+
operation.auto()
|
|
266
|
+
operation.hparams_dict['saved_model_dir_path'] = exec_param['saved_model_dir_path']
|
|
267
|
+
operation.saved_model = SavedModel(saved_model_dir_path=exec_param['saved_model_dir_path'])
|
|
268
|
+
else:
|
|
269
|
+
operation.auto()
|
|
270
|
+
|
|
271
|
+
if mode == MODE_TEST:
|
|
272
|
+
img_file_path = TEST_IMG_FILE_PATH
|
|
273
|
+
operation.test(img_file_path=img_file_path)
|
|
274
|
+
operation.create_cache_manager()
|
|
275
|
+
operation.test_generate_text_matrix_image()
|
|
276
|
+
|
|
277
|
+
with_cache = (operation.cache_input_layer_name is not None)
|
|
278
|
+
|
|
279
|
+
print("=" * 10)
|
|
280
|
+
print("with_cache: {}".format(with_cache))
|
|
281
|
+
print("=" * 10)
|
|
282
|
+
|
|
283
|
+
target_character_list = ['山', '川']
|
|
284
|
+
target_character_list = ['9', 'あ']
|
|
285
|
+
target_character_list = ['い', 'お']
|
|
286
|
+
target_character_list = ['三', '田']
|
|
287
|
+
target_character_list = ['沖', '縄', 'o', 'x']
|
|
288
|
+
target_character_list = ['1', '2', '3', '4']
|
|
289
|
+
target_character_list = ['0', 'か', 'き', 'く']
|
|
290
|
+
target_character_list = ['け', 'こ']
|
|
291
|
+
target_character_list = ['さ', 'し', 'す', 'せ', 'そ']
|
|
292
|
+
target_character_list = ['擬', '態']
|
|
293
|
+
target_character_list = ['5', '8']
|
|
294
|
+
target_character_list = ['5', '6', '7', '8', '0']
|
|
295
|
+
|
|
296
|
+
export_dir_path = "export/{}".format(operation_id)
|
|
297
|
+
if operation.hparams_dict.get("cache_input_layer_name"):
|
|
298
|
+
_layer_name_lists = [s for s in operation.hparams_dict["cache_input_layer_name"].split("/")
|
|
299
|
+
if s.find("res_block") >= 0]
|
|
300
|
+
if _layer_name_lists:
|
|
301
|
+
export_dir_path = os.path.join(export_dir_path, _layer_name_lists[0])
|
|
302
|
+
|
|
303
|
+
for target_character in target_character_list:
|
|
304
|
+
input_hash_dict, hash_dict, accurate_cnt,\
|
|
305
|
+
total_cnt, sum_lap_time_get_output_list, total_time, sum_time_get_output = operation.bench(
|
|
306
|
+
iterr=None, with_cache=with_cache, target_character_list=[target_character])
|
|
307
|
+
|
|
308
|
+
print("total_time: {}".format(total_time))
|
|
309
|
+
print("sum_time_get_output: {}".format(sum_time_get_output))
|
|
310
|
+
print("accurate_cnt: {}, total_cnt: {}".format(accurate_cnt, total_cnt))
|
|
311
|
+
print("len of input_hash_dict: {}".format(len(input_hash_dict)))
|
|
312
|
+
print("len of hash_dict: {}".format(len(hash_dict)))
|
|
313
|
+
# export cache_input_value in input_hash_dict
|
|
314
|
+
def expor_cache_input_value(input_hash_dict, dir_path="./export"):
|
|
315
|
+
_len_input_hash_dict = len(input_hash_dict)
|
|
316
|
+
_cache_input_value_array = None
|
|
317
|
+
for i, input_hash in enumerate(input_hash_dict.keys()):
|
|
318
|
+
print("export i: {}, input_hash_dict with input_hash: {}".format(i, input_hash))
|
|
319
|
+
info_value = input_hash_dict[input_hash]
|
|
320
|
+
cache_input_value = info_value["cache_input_value"]
|
|
321
|
+
if cache_input_value is None:
|
|
322
|
+
continue
|
|
323
|
+
cache_input_value = np.asarray(cache_input_value)
|
|
324
|
+
cache_input_value = cache_input_value.reshape(-1)
|
|
325
|
+
cache_input_value = cache_input_value.astype(np.uint8)
|
|
326
|
+
|
|
327
|
+
if _cache_input_value_array is None:
|
|
328
|
+
_cache_input_value_array = np.zeros([_len_input_hash_dict, len(cache_input_value)], dtype=np.uint8)
|
|
329
|
+
_cache_input_value_array[i, :] = cache_input_value
|
|
330
|
+
|
|
331
|
+
os.makedirs(dir_path, exist_ok=True)
|
|
332
|
+
_export_path = os.path.join(dir_path, 'cache_input_value_c{}.csv'.format(target_character))
|
|
333
|
+
|
|
334
|
+
np.savetxt(_export_path, _cache_input_value_array, delimiter=",")
|
|
335
|
+
|
|
336
|
+
_max_value = _cache_input_value_array.max()
|
|
337
|
+
_max_value = min(4, _max_value)
|
|
338
|
+
print("_max_value: {}".format(_max_value))
|
|
339
|
+
|
|
340
|
+
_gray_cache_input_value_array = _cache_input_value_array * 255.0 / _max_value
|
|
341
|
+
_img_gray = Image.fromarray(np.uint8(_gray_cache_input_value_array))
|
|
342
|
+
print("_img_gray _max_value: {}".format(_gray_cache_input_value_array))
|
|
343
|
+
_export_path = os.path.join(dir_path, 'cache_input_value_c{}.png'.format(target_character))
|
|
344
|
+
_img_gray.save(_export_path)
|
|
345
|
+
|
|
346
|
+
def expor_output_character(input_hash_dict, dir_path="./export"):
|
|
347
|
+
|
|
348
|
+
_len_input_hash_dict = len(input_hash_dict)
|
|
349
|
+
output_character_list = [input_hash_dict[input_hash].get("output_character") for i, input_hash in enumerate(input_hash_dict.keys())]
|
|
350
|
+
print("target_character: {}, output_character_list: {}".format(target_character, output_character_list))
|
|
351
|
+
_export_array = np.asarray([output_character_list])
|
|
352
|
+
|
|
353
|
+
os.makedirs(dir_path, exist_ok=True)
|
|
354
|
+
_export_path = os.path.join(dir_path, 'output_character_c{}.csv'.format(target_character))
|
|
355
|
+
np.savetxt(_export_path, _export_array, delimiter=",", encoding='utf8', fmt='%s')
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
if input_hash_dict is not None or len(input_hash_dict) > 0:
|
|
359
|
+
expor_cache_input_value(input_hash_dict, dir_path=export_dir_path)
|
|
360
|
+
expor_output_character(input_hash_dict, dir_path=export_dir_path)
|
|
361
|
+
|
|
362
|
+
else:
|
|
363
|
+
raise ValueError('Invalid mode: {}'.format(mode))
|
|
364
|
+
|
|
365
|
+
print('DONE main')
|
|
366
|
+
|
|
367
|
+
'''
|
|
368
|
+
Usage
|
|
369
|
+
OPERATION_ID=SCR_2D_CNN_V2_l49-c64_20220326-1756-PREDICTION
|
|
370
|
+
|
|
371
|
+
cd /var/smalltrain/cache-ai/src/python/
|
|
372
|
+
nohup python cacheai/cache_operation.py --setting_file_path=/var/smalltrain/operation/"$OPERATION_ID".json \
|
|
373
|
+
> /var/smalltrain/logs/$OPERATION_ID.log 2>&1 &
|
|
374
|
+
|
|
375
|
+
'''
|
|
376
|
+
if __name__ == '__main__':
|
|
377
|
+
|
|
378
|
+
parser = argparse.ArgumentParser(description='cache_operation')
|
|
379
|
+
|
|
380
|
+
parser.add_argument('--mode', '-mmd', type=str, default=MODE_TEST,
|
|
381
|
+
help='String, The mode to exec(Default: {})'.format(MODE_TEST))
|
|
382
|
+
parser.add_argument('--setting_file_path', '-sfp', type=str, default=None,
|
|
383
|
+
help='String, The setting file path of JSON String to set parameters')
|
|
384
|
+
|
|
385
|
+
args = parser.parse_args()
|
|
386
|
+
print('args:{}'.format(args))
|
|
387
|
+
|
|
388
|
+
exec_param = vars(args)
|
|
389
|
+
print('init exec_param:{}'.format(args))
|
|
390
|
+
|
|
391
|
+
main(exec_param)
|
cacheai/client.py
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
"""CacheAI Python API client."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from typing import Optional, Dict, Any, Iterator
|
|
5
|
+
import requests
|
|
6
|
+
from requests.adapters import HTTPAdapter
|
|
7
|
+
from urllib3.util.retry import Retry
|
|
8
|
+
|
|
9
|
+
from cacheai.resources import Chat
|
|
10
|
+
from cacheai.exceptions import (
|
|
11
|
+
CacheAIError,
|
|
12
|
+
AuthenticationError,
|
|
13
|
+
PermissionDeniedError,
|
|
14
|
+
NotFoundError,
|
|
15
|
+
RateLimitError,
|
|
16
|
+
APIError,
|
|
17
|
+
TimeoutError,
|
|
18
|
+
ConnectionError,
|
|
19
|
+
ValidationError,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class Client:
|
|
24
|
+
"""
|
|
25
|
+
CacheAI API client.
|
|
26
|
+
|
|
27
|
+
Example:
|
|
28
|
+
```python
|
|
29
|
+
from cacheai import Client
|
|
30
|
+
|
|
31
|
+
client = Client(
|
|
32
|
+
api_key="your-api-key",
|
|
33
|
+
base_url="https://api.cacheai.io/v1"
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
response = client.chat.completions.create(
|
|
37
|
+
model="gpt-3.5-turbo",
|
|
38
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
39
|
+
)
|
|
40
|
+
```
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
*,
|
|
46
|
+
api_key: Optional[str] = None,
|
|
47
|
+
base_url: Optional[str] = None,
|
|
48
|
+
timeout: float = 60.0,
|
|
49
|
+
max_retries: int = 2,
|
|
50
|
+
enable_cache: bool = True,
|
|
51
|
+
backend_provider: Optional[str] = None,
|
|
52
|
+
backend_api_key: Optional[str] = None,
|
|
53
|
+
backend_base_url: Optional[str] = None,
|
|
54
|
+
) -> None:
|
|
55
|
+
"""
|
|
56
|
+
Initialize CacheAI client.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
api_key: CacheAI API key. If not provided, reads from CACHEAI_API_KEY env var
|
|
60
|
+
base_url: Base URL for API. If not provided, reads from CACHEAI_BASE_URL env var
|
|
61
|
+
timeout: Request timeout in seconds
|
|
62
|
+
max_retries: Maximum number of retries for failed requests
|
|
63
|
+
enable_cache: Enable CacheAI semantic caching (default: True)
|
|
64
|
+
backend_provider: Backend LLM provider (openai, anthropic, google, etc.)
|
|
65
|
+
backend_api_key: Backend LLM API key
|
|
66
|
+
backend_base_url: Custom backend endpoint URL
|
|
67
|
+
"""
|
|
68
|
+
self.api_key = api_key or os.getenv("CACHEAI_API_KEY")
|
|
69
|
+
if not self.api_key:
|
|
70
|
+
raise ValueError(
|
|
71
|
+
"API key is required. Provide it via api_key parameter or "
|
|
72
|
+
"CACHEAI_API_KEY environment variable."
|
|
73
|
+
)
|
|
74
|
+
|
|
75
|
+
self.base_url = (
|
|
76
|
+
base_url
|
|
77
|
+
or os.getenv("CACHEAI_BASE_URL")
|
|
78
|
+
or "https://api.cacheai.tech/v1"
|
|
79
|
+
)
|
|
80
|
+
self.base_url = self.base_url.rstrip("/")
|
|
81
|
+
|
|
82
|
+
self.timeout = timeout
|
|
83
|
+
self.max_retries = max_retries
|
|
84
|
+
self.enable_cache = enable_cache
|
|
85
|
+
|
|
86
|
+
# Backend LLM configuration
|
|
87
|
+
self.backend_provider = backend_provider or os.getenv("CACHEAI_BACKEND_PROVIDER")
|
|
88
|
+
self.backend_api_key = backend_api_key or os.getenv("CACHEAI_BACKEND_API_KEY")
|
|
89
|
+
self.backend_base_url = backend_base_url or os.getenv("CACHEAI_BACKEND_BASE_URL")
|
|
90
|
+
|
|
91
|
+
# Setup session with retry strategy
|
|
92
|
+
self._session = requests.Session()
|
|
93
|
+
retry_strategy = Retry(
|
|
94
|
+
total=max_retries,
|
|
95
|
+
backoff_factor=1,
|
|
96
|
+
status_forcelist=[429, 500, 502, 503, 504],
|
|
97
|
+
allowed_methods=["GET", "POST"],
|
|
98
|
+
)
|
|
99
|
+
adapter = HTTPAdapter(max_retries=retry_strategy)
|
|
100
|
+
self._session.mount("http://", adapter)
|
|
101
|
+
self._session.mount("https://", adapter)
|
|
102
|
+
|
|
103
|
+
# Initialize resources
|
|
104
|
+
self.chat = Chat(self)
|
|
105
|
+
|
|
106
|
+
def _get_headers(self, extra_headers: Optional[Dict[str, str]] = None) -> Dict[str, str]:
|
|
107
|
+
"""Build request headers."""
|
|
108
|
+
headers = {
|
|
109
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
110
|
+
"Content-Type": "application/json",
|
|
111
|
+
"User-Agent": "cacheai-python/0.1.0",
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
# Add cache control header
|
|
115
|
+
if not self.enable_cache:
|
|
116
|
+
headers["X-CacheAI-Enable-Cache"] = "false"
|
|
117
|
+
|
|
118
|
+
# Add backend configuration headers
|
|
119
|
+
if self.backend_provider:
|
|
120
|
+
headers["X-CacheAI-Backend-Provider"] = self.backend_provider
|
|
121
|
+
if self.backend_api_key:
|
|
122
|
+
headers["X-CacheAI-Backend-API-Key"] = self.backend_api_key
|
|
123
|
+
if self.backend_base_url:
|
|
124
|
+
headers["X-CacheAI-Backend-Base-URL"] = self.backend_base_url
|
|
125
|
+
|
|
126
|
+
if extra_headers:
|
|
127
|
+
headers.update(extra_headers)
|
|
128
|
+
|
|
129
|
+
return headers
|
|
130
|
+
|
|
131
|
+
def _handle_error_response(self, response: requests.Response) -> None:
|
|
132
|
+
"""Handle error responses and raise appropriate exceptions."""
|
|
133
|
+
status_code = response.status_code
|
|
134
|
+
|
|
135
|
+
try:
|
|
136
|
+
error_data = response.json()
|
|
137
|
+
error_message = error_data.get("error", {}).get("message", response.text)
|
|
138
|
+
except Exception:
|
|
139
|
+
error_message = response.text
|
|
140
|
+
|
|
141
|
+
if status_code == 401:
|
|
142
|
+
raise AuthenticationError(
|
|
143
|
+
error_message,
|
|
144
|
+
status_code=status_code,
|
|
145
|
+
response_body=response.text,
|
|
146
|
+
)
|
|
147
|
+
elif status_code == 403:
|
|
148
|
+
raise PermissionDeniedError(
|
|
149
|
+
error_message,
|
|
150
|
+
status_code=status_code,
|
|
151
|
+
response_body=response.text,
|
|
152
|
+
)
|
|
153
|
+
elif status_code == 404:
|
|
154
|
+
raise NotFoundError(
|
|
155
|
+
error_message,
|
|
156
|
+
status_code=status_code,
|
|
157
|
+
response_body=response.text,
|
|
158
|
+
)
|
|
159
|
+
elif status_code == 429:
|
|
160
|
+
raise RateLimitError(
|
|
161
|
+
error_message,
|
|
162
|
+
status_code=status_code,
|
|
163
|
+
response_body=response.text,
|
|
164
|
+
)
|
|
165
|
+
elif status_code >= 500:
|
|
166
|
+
raise APIError(
|
|
167
|
+
error_message,
|
|
168
|
+
status_code=status_code,
|
|
169
|
+
response_body=response.text,
|
|
170
|
+
)
|
|
171
|
+
else:
|
|
172
|
+
raise CacheAIError(
|
|
173
|
+
error_message,
|
|
174
|
+
status_code=status_code,
|
|
175
|
+
response_body=response.text,
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
def _post(self, path: str, **kwargs: Any) -> Dict[str, Any]:
|
|
179
|
+
"""Make a POST request."""
|
|
180
|
+
url = f"{self.base_url}{path}"
|
|
181
|
+
headers = self._get_headers(kwargs.pop("headers", None))
|
|
182
|
+
|
|
183
|
+
try:
|
|
184
|
+
response = self._session.post(
|
|
185
|
+
url,
|
|
186
|
+
headers=headers,
|
|
187
|
+
timeout=self.timeout,
|
|
188
|
+
**kwargs,
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
if not response.ok:
|
|
192
|
+
self._handle_error_response(response)
|
|
193
|
+
|
|
194
|
+
return response.json()
|
|
195
|
+
|
|
196
|
+
except requests.exceptions.Timeout as e:
|
|
197
|
+
raise TimeoutError(f"Request timed out: {e}")
|
|
198
|
+
except requests.exceptions.ConnectionError as e:
|
|
199
|
+
raise ConnectionError(f"Connection failed: {e}")
|
|
200
|
+
except requests.exceptions.RequestException as e:
|
|
201
|
+
raise CacheAIError(f"Request failed: {e}")
|
|
202
|
+
|
|
203
|
+
def _stream_post(self, path: str, **kwargs: Any) -> Iterator[str]:
|
|
204
|
+
"""Make a streaming POST request."""
|
|
205
|
+
url = f"{self.base_url}{path}"
|
|
206
|
+
headers = self._get_headers(kwargs.pop("headers", None))
|
|
207
|
+
|
|
208
|
+
try:
|
|
209
|
+
response = self._session.post(
|
|
210
|
+
url,
|
|
211
|
+
headers=headers,
|
|
212
|
+
timeout=self.timeout,
|
|
213
|
+
stream=True,
|
|
214
|
+
**kwargs,
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
if not response.ok:
|
|
218
|
+
self._handle_error_response(response)
|
|
219
|
+
|
|
220
|
+
for line in response.iter_lines():
|
|
221
|
+
if line:
|
|
222
|
+
yield line.decode("utf-8")
|
|
223
|
+
|
|
224
|
+
except requests.exceptions.Timeout as e:
|
|
225
|
+
raise TimeoutError(f"Request timed out: {e}")
|
|
226
|
+
except requests.exceptions.ConnectionError as e:
|
|
227
|
+
raise ConnectionError(f"Connection failed: {e}")
|
|
228
|
+
except requests.exceptions.RequestException as e:
|
|
229
|
+
raise CacheAIError(f"Request failed: {e}")
|
|
230
|
+
|
|
231
|
+
def _get(self, path: str, **kwargs: Any) -> Dict[str, Any]:
|
|
232
|
+
"""Make a GET request."""
|
|
233
|
+
url = f"{self.base_url}{path}"
|
|
234
|
+
headers = self._get_headers(kwargs.pop("headers", None))
|
|
235
|
+
|
|
236
|
+
try:
|
|
237
|
+
response = self._session.get(
|
|
238
|
+
url,
|
|
239
|
+
headers=headers,
|
|
240
|
+
timeout=self.timeout,
|
|
241
|
+
**kwargs,
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
if not response.ok:
|
|
245
|
+
self._handle_error_response(response)
|
|
246
|
+
|
|
247
|
+
return response.json()
|
|
248
|
+
|
|
249
|
+
except requests.exceptions.Timeout as e:
|
|
250
|
+
raise TimeoutError(f"Request timed out: {e}")
|
|
251
|
+
except requests.exceptions.ConnectionError as e:
|
|
252
|
+
raise ConnectionError(f"Connection failed: {e}")
|
|
253
|
+
except requests.exceptions.RequestException as e:
|
|
254
|
+
raise CacheAIError(f"Request failed: {e}")
|
|
255
|
+
|
|
256
|
+
def close(self) -> None:
|
|
257
|
+
"""Close the HTTP session."""
|
|
258
|
+
self._session.close()
|
|
259
|
+
|
|
260
|
+
def __enter__(self) -> "Client":
|
|
261
|
+
return self
|
|
262
|
+
|
|
263
|
+
def __exit__(self, *args: Any) -> None:
|
|
264
|
+
self.close()
|
cacheai/exceptions.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""CacheAI Python API exceptions."""
|
|
2
|
+
|
|
3
|
+
from typing import Optional
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class CacheAIError(Exception):
|
|
7
|
+
"""Base exception for all CacheAI errors."""
|
|
8
|
+
|
|
9
|
+
def __init__(
|
|
10
|
+
self,
|
|
11
|
+
message: str,
|
|
12
|
+
*,
|
|
13
|
+
status_code: Optional[int] = None,
|
|
14
|
+
response_body: Optional[str] = None,
|
|
15
|
+
) -> None:
|
|
16
|
+
super().__init__(message)
|
|
17
|
+
self.message = message
|
|
18
|
+
self.status_code = status_code
|
|
19
|
+
self.response_body = response_body
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AuthenticationError(CacheAIError):
|
|
23
|
+
"""Raised when authentication fails (401)."""
|
|
24
|
+
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class PermissionDeniedError(CacheAIError):
|
|
29
|
+
"""Raised when permission is denied (403)."""
|
|
30
|
+
|
|
31
|
+
pass
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class NotFoundError(CacheAIError):
|
|
35
|
+
"""Raised when resource is not found (404)."""
|
|
36
|
+
|
|
37
|
+
pass
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class RateLimitError(CacheAIError):
|
|
41
|
+
"""Raised when rate limit is exceeded (429)."""
|
|
42
|
+
|
|
43
|
+
pass
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class APIError(CacheAIError):
|
|
47
|
+
"""Raised when API returns an error (500+)."""
|
|
48
|
+
|
|
49
|
+
pass
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class TimeoutError(CacheAIError):
|
|
53
|
+
"""Raised when request times out."""
|
|
54
|
+
|
|
55
|
+
pass
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ConnectionError(CacheAIError):
|
|
59
|
+
"""Raised when connection fails."""
|
|
60
|
+
|
|
61
|
+
pass
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class ValidationError(CacheAIError):
|
|
65
|
+
"""Raised when request validation fails."""
|
|
66
|
+
|
|
67
|
+
pass
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""CacheAI Chat Completion API resource."""
|
|
2
|
+
|
|
3
|
+
from typing import List, Optional, Union, Iterator, Dict, Any
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
from cacheai.types import (
|
|
7
|
+
ChatCompletion,
|
|
8
|
+
ChatCompletionChunk,
|
|
9
|
+
ChatMessage,
|
|
10
|
+
)
|
|
11
|
+
from cacheai.exceptions import (
|
|
12
|
+
CacheAIError,
|
|
13
|
+
AuthenticationError,
|
|
14
|
+
APIError,
|
|
15
|
+
ValidationError,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class Completions:
|
|
20
|
+
"""Chat completions resource."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, client: Any) -> None:
|
|
23
|
+
self._client = client
|
|
24
|
+
|
|
25
|
+
def create(
|
|
26
|
+
self,
|
|
27
|
+
*,
|
|
28
|
+
model: str,
|
|
29
|
+
messages: List[Dict[str, str]],
|
|
30
|
+
temperature: Optional[float] = None,
|
|
31
|
+
max_tokens: Optional[int] = None,
|
|
32
|
+
top_p: Optional[float] = None,
|
|
33
|
+
frequency_penalty: Optional[float] = None,
|
|
34
|
+
presence_penalty: Optional[float] = None,
|
|
35
|
+
stop: Optional[Union[str, List[str]]] = None,
|
|
36
|
+
stream: bool = False,
|
|
37
|
+
**kwargs: Any,
|
|
38
|
+
) -> Union[ChatCompletion, Iterator[ChatCompletionChunk]]:
|
|
39
|
+
"""
|
|
40
|
+
Create a chat completion.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
model: ID of the model to use
|
|
44
|
+
messages: List of messages in the conversation
|
|
45
|
+
temperature: Sampling temperature (0-2)
|
|
46
|
+
max_tokens: Maximum number of tokens to generate
|
|
47
|
+
top_p: Nucleus sampling parameter
|
|
48
|
+
frequency_penalty: Frequency penalty (-2.0 to 2.0)
|
|
49
|
+
presence_penalty: Presence penalty (-2.0 to 2.0)
|
|
50
|
+
stop: Up to 4 sequences where the API will stop generating
|
|
51
|
+
stream: Whether to stream back partial progress
|
|
52
|
+
**kwargs: Additional parameters
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
ChatCompletion or Iterator[ChatCompletionChunk] if streaming
|
|
56
|
+
"""
|
|
57
|
+
# Build request payload
|
|
58
|
+
payload = {
|
|
59
|
+
"model": model,
|
|
60
|
+
"messages": messages,
|
|
61
|
+
"stream": stream,
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
# Add optional parameters
|
|
65
|
+
if temperature is not None:
|
|
66
|
+
payload["temperature"] = temperature
|
|
67
|
+
if max_tokens is not None:
|
|
68
|
+
payload["max_tokens"] = max_tokens
|
|
69
|
+
if top_p is not None:
|
|
70
|
+
payload["top_p"] = top_p
|
|
71
|
+
if frequency_penalty is not None:
|
|
72
|
+
payload["frequency_penalty"] = frequency_penalty
|
|
73
|
+
if presence_penalty is not None:
|
|
74
|
+
payload["presence_penalty"] = presence_penalty
|
|
75
|
+
if stop is not None:
|
|
76
|
+
payload["stop"] = stop
|
|
77
|
+
|
|
78
|
+
# Add any additional parameters
|
|
79
|
+
payload.update(kwargs)
|
|
80
|
+
|
|
81
|
+
# Make API request
|
|
82
|
+
if stream:
|
|
83
|
+
return self._stream(payload)
|
|
84
|
+
else:
|
|
85
|
+
response_data = self._client._post("/chat/completions", json=payload)
|
|
86
|
+
return ChatCompletion(**response_data)
|
|
87
|
+
|
|
88
|
+
def _stream(self, payload: Dict[str, Any]) -> Iterator[ChatCompletionChunk]:
|
|
89
|
+
"""Stream chat completion chunks."""
|
|
90
|
+
for line in self._client._stream_post("/chat/completions", json=payload):
|
|
91
|
+
line = line.strip()
|
|
92
|
+
if not line:
|
|
93
|
+
continue
|
|
94
|
+
|
|
95
|
+
# Skip "data: " prefix
|
|
96
|
+
if line.startswith("data: "):
|
|
97
|
+
line = line[6:]
|
|
98
|
+
|
|
99
|
+
# Check for [DONE] marker
|
|
100
|
+
if line == "[DONE]":
|
|
101
|
+
break
|
|
102
|
+
|
|
103
|
+
try:
|
|
104
|
+
chunk_data = json.loads(line)
|
|
105
|
+
yield ChatCompletionChunk(**chunk_data)
|
|
106
|
+
except json.JSONDecodeError:
|
|
107
|
+
continue
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
class Chat:
|
|
111
|
+
"""Chat API resource."""
|
|
112
|
+
|
|
113
|
+
def __init__(self, client: Any) -> None:
|
|
114
|
+
self.completions = Completions(client)
|
cacheai/types.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
"""CacheAI Python API type definitions."""
|
|
2
|
+
|
|
3
|
+
from typing import List, Optional, Union, Literal
|
|
4
|
+
from pydantic import BaseModel, Field
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
# ========================================
|
|
8
|
+
# Chat Completion Types
|
|
9
|
+
# ========================================
|
|
10
|
+
|
|
11
|
+
class ChatMessage(BaseModel):
|
|
12
|
+
"""A message in a chat completion."""
|
|
13
|
+
|
|
14
|
+
role: Literal["system", "user", "assistant", "tool"]
|
|
15
|
+
content: Optional[str] = None
|
|
16
|
+
name: Optional[str] = None
|
|
17
|
+
tool_calls: Optional[List[dict]] = None
|
|
18
|
+
tool_call_id: Optional[str] = None
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ChatCompletionChoice(BaseModel):
|
|
22
|
+
"""A choice in a chat completion response."""
|
|
23
|
+
|
|
24
|
+
index: int
|
|
25
|
+
message: ChatMessage
|
|
26
|
+
finish_reason: Optional[str] = None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class Usage(BaseModel):
|
|
30
|
+
"""Token usage information."""
|
|
31
|
+
|
|
32
|
+
prompt_tokens: int
|
|
33
|
+
completion_tokens: int
|
|
34
|
+
total_tokens: int
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class ChatCompletion(BaseModel):
|
|
38
|
+
"""Chat completion response."""
|
|
39
|
+
|
|
40
|
+
id: str
|
|
41
|
+
object: Literal["chat.completion"] = "chat.completion"
|
|
42
|
+
created: int
|
|
43
|
+
model: str
|
|
44
|
+
choices: List[ChatCompletionChoice]
|
|
45
|
+
usage: Optional[Usage] = None
|
|
46
|
+
system_fingerprint: Optional[str] = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# ========================================
|
|
50
|
+
# Streaming Types
|
|
51
|
+
# ========================================
|
|
52
|
+
|
|
53
|
+
class ChatCompletionChunkDelta(BaseModel):
|
|
54
|
+
"""Delta in a streaming chunk."""
|
|
55
|
+
|
|
56
|
+
role: Optional[str] = None
|
|
57
|
+
content: Optional[str] = None
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class ChatCompletionChunkChoice(BaseModel):
|
|
61
|
+
"""A choice in a streaming chunk."""
|
|
62
|
+
|
|
63
|
+
index: int
|
|
64
|
+
delta: ChatCompletionChunkDelta
|
|
65
|
+
finish_reason: Optional[str] = None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class ChatCompletionChunk(BaseModel):
|
|
69
|
+
"""A chunk in a streaming chat completion."""
|
|
70
|
+
|
|
71
|
+
id: str
|
|
72
|
+
object: Literal["chat.completion.chunk"] = "chat.completion.chunk"
|
|
73
|
+
created: int
|
|
74
|
+
model: str
|
|
75
|
+
choices: List[ChatCompletionChunkChoice]
|
|
76
|
+
system_fingerprint: Optional[str] = None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
# ========================================
|
|
80
|
+
# Completion Types (Legacy)
|
|
81
|
+
# ========================================
|
|
82
|
+
|
|
83
|
+
class CompletionChoice(BaseModel):
|
|
84
|
+
"""A choice in a completion response."""
|
|
85
|
+
|
|
86
|
+
text: str
|
|
87
|
+
index: int
|
|
88
|
+
logprobs: Optional[dict] = None
|
|
89
|
+
finish_reason: Optional[str] = None
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class Completion(BaseModel):
|
|
93
|
+
"""Completion response."""
|
|
94
|
+
|
|
95
|
+
id: str
|
|
96
|
+
object: Literal["text_completion"] = "text_completion"
|
|
97
|
+
created: int
|
|
98
|
+
model: str
|
|
99
|
+
choices: List[CompletionChoice]
|
|
100
|
+
usage: Optional[Usage] = None
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# ========================================
|
|
104
|
+
# Models Types
|
|
105
|
+
# ========================================
|
|
106
|
+
|
|
107
|
+
class Model(BaseModel):
|
|
108
|
+
"""Model information."""
|
|
109
|
+
|
|
110
|
+
id: str
|
|
111
|
+
object: Literal["model"] = "model"
|
|
112
|
+
created: int
|
|
113
|
+
owned_by: str
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class ModelList(BaseModel):
|
|
117
|
+
"""List of models."""
|
|
118
|
+
|
|
119
|
+
object: Literal["list"] = "list"
|
|
120
|
+
data: List[Model]
|
cacheai/version.py
ADDED
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cacheai
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Official Python API for CacheAI - Semantic Caching for Large Language Models
|
|
5
|
+
Author-email: "CacheAI Technologies, Inc." <info@cacheaitechnologies.com>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://www.cacheaitechnologies.com
|
|
8
|
+
Project-URL: Documentation, https://docs.cacheai.tech
|
|
9
|
+
Project-URL: Repository, https://github.com/cacheaitechnologies/cacheai
|
|
10
|
+
Project-URL: Changelog, https://github.com/cacheaitechnologies/cacheai/blob/main/CHANGELOG.md
|
|
11
|
+
Project-URL: Bug Tracker, https://github.com/cacheaitechnologies/cacheai/issues
|
|
12
|
+
Keywords: cacheai,llm,caching,openai,chatgpt,semantic-cache
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
23
|
+
Requires-Python: >=3.10
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
Requires-Dist: requests>=2.28.0
|
|
26
|
+
Requires-Dist: pydantic>=2.0.0
|
|
27
|
+
Requires-Dist: typing-extensions>=4.5.0
|
|
28
|
+
Requires-Dist: urllib3>=1.26.0
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest>=7.0.0; extra == "dev"
|
|
31
|
+
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
|
|
32
|
+
Requires-Dist: mypy>=1.0.0; extra == "dev"
|
|
33
|
+
Requires-Dist: black>=23.0.0; extra == "dev"
|
|
34
|
+
Requires-Dist: ruff>=0.1.0; extra == "dev"
|
|
35
|
+
Requires-Dist: types-requests>=2.28.0; extra == "dev"
|
|
36
|
+
|
|
37
|
+
# CacheAI Python API
|
|
38
|
+
|
|
39
|
+
Official Python API for CacheAI - Semantic Caching for Large Language Models
|
|
40
|
+
|
|
41
|
+
[](https://badge.fury.io/py/cacheai)
|
|
42
|
+
[](https://pypi.org/project/cacheai/)
|
|
43
|
+
[](https://opensource.org/licenses/MIT)
|
|
44
|
+
|
|
45
|
+
## Features
|
|
46
|
+
|
|
47
|
+
- **OpenAI Compatible**: Drop-in replacement for OpenAI Python SDK
|
|
48
|
+
- **Semantic Caching**: Automatic caching of similar queries using advanced semantic similarity
|
|
49
|
+
- **Multiple LLM Backends**: Support for OpenAI, Anthropic, Google AI, and more
|
|
50
|
+
- **Streaming Support**: Full support for streaming responses
|
|
51
|
+
- **Type-Safe**: Complete type hints for better IDE support
|
|
52
|
+
- **Easy Integration**: Minimal code changes required
|
|
53
|
+
|
|
54
|
+
## Installation
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install cacheai
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## Quick Start
|
|
61
|
+
|
|
62
|
+
### Basic Usage
|
|
63
|
+
|
|
64
|
+
```python
|
|
65
|
+
from cacheai import Client
|
|
66
|
+
|
|
67
|
+
# Initialize client
|
|
68
|
+
client = Client(
|
|
69
|
+
api_key="your-cacheai-api-key",
|
|
70
|
+
base_url="https://api.cacheai.tech/v1" # Optional, this is the default
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
# Create a chat completion
|
|
74
|
+
response = client.chat.completions.create(
|
|
75
|
+
model="gpt-3.5-turbo",
|
|
76
|
+
messages=[
|
|
77
|
+
{"role": "user", "content": "Hello, how are you?"}
|
|
78
|
+
]
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
print(response.choices[0].message.content)
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
### With Environment Variables
|
|
85
|
+
|
|
86
|
+
```python
|
|
87
|
+
import os
|
|
88
|
+
from cacheai import Client
|
|
89
|
+
|
|
90
|
+
# Set environment variables
|
|
91
|
+
os.environ["CACHEAI_API_KEY"] = "your-cacheai-api-key"
|
|
92
|
+
os.environ["CACHEAI_BACKEND_PROVIDER"] = "openai"
|
|
93
|
+
os.environ["CACHEAI_BACKEND_API_KEY"] = "your-openai-api-key"
|
|
94
|
+
|
|
95
|
+
# Initialize client (reads from environment)
|
|
96
|
+
client = Client()
|
|
97
|
+
|
|
98
|
+
response = client.chat.completions.create(
|
|
99
|
+
model="gpt-3.5-turbo",
|
|
100
|
+
messages=[{"role": "user", "content": "What is Python?"}]
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
print(response.choices[0].message.content)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
### Streaming
|
|
107
|
+
|
|
108
|
+
```python
|
|
109
|
+
from cacheai import Client
|
|
110
|
+
|
|
111
|
+
client = Client(api_key="your-cacheai-api-key")
|
|
112
|
+
|
|
113
|
+
stream = client.chat.completions.create(
|
|
114
|
+
model="gpt-3.5-turbo",
|
|
115
|
+
messages=[{"role": "user", "content": "Tell me a story"}],
|
|
116
|
+
stream=True
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
for chunk in stream:
|
|
120
|
+
if chunk.choices[0].delta.content:
|
|
121
|
+
print(chunk.choices[0].delta.content, end="", flush=True)
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Configuration
|
|
125
|
+
|
|
126
|
+
### Backend LLM Configuration
|
|
127
|
+
|
|
128
|
+
CacheAI acts as a caching layer in front of your preferred LLM provider. Configure the backend:
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from cacheai import Client
|
|
132
|
+
|
|
133
|
+
client = Client(
|
|
134
|
+
api_key="your-cacheai-api-key",
|
|
135
|
+
backend_provider="openai", # "openai", "anthropic", "google", etc.
|
|
136
|
+
backend_api_key="your-openai-key", # Backend LLM API key
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
# Or use environment variables:
|
|
140
|
+
# CACHEAI_BACKEND_PROVIDER=openai
|
|
141
|
+
# CACHEAI_BACKEND_API_KEY=sk-...
|
|
142
|
+
```
|
|
143
|
+
|
|
144
|
+
### Cache Control
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
from cacheai import Client
|
|
148
|
+
|
|
149
|
+
# Disable caching (for debugging/testing)
|
|
150
|
+
client = Client(
|
|
151
|
+
api_key="your-cacheai-api-key",
|
|
152
|
+
enable_cache=False
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
# Or via environment variable:
|
|
156
|
+
# CACHEAI_ENABLE_CACHE=false
|
|
157
|
+
```
|
|
158
|
+
|
|
159
|
+
## Advanced Usage
|
|
160
|
+
|
|
161
|
+
### Context Manager
|
|
162
|
+
|
|
163
|
+
```python
|
|
164
|
+
from cacheai import Client
|
|
165
|
+
|
|
166
|
+
with Client(api_key="your-api-key") as client:
|
|
167
|
+
response = client.chat.completions.create(
|
|
168
|
+
model="gpt-3.5-turbo",
|
|
169
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
170
|
+
)
|
|
171
|
+
print(response.choices[0].message.content)
|
|
172
|
+
# Connection is automatically closed
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Custom Timeout and Retries
|
|
176
|
+
|
|
177
|
+
```python
|
|
178
|
+
from cacheai import Client
|
|
179
|
+
|
|
180
|
+
client = Client(
|
|
181
|
+
api_key="your-api-key",
|
|
182
|
+
timeout=30.0, # Request timeout in seconds
|
|
183
|
+
max_retries=3 # Maximum retry attempts
|
|
184
|
+
)
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
### Error Handling
|
|
188
|
+
|
|
189
|
+
```python
|
|
190
|
+
from cacheai import Client, CacheAIError, AuthenticationError, RateLimitError
|
|
191
|
+
|
|
192
|
+
client = Client(api_key="your-api-key")
|
|
193
|
+
|
|
194
|
+
try:
|
|
195
|
+
response = client.chat.completions.create(
|
|
196
|
+
model="gpt-3.5-turbo",
|
|
197
|
+
messages=[{"role": "user", "content": "Hello!"}]
|
|
198
|
+
)
|
|
199
|
+
except AuthenticationError as e:
|
|
200
|
+
print(f"Invalid API key: {e}")
|
|
201
|
+
except RateLimitError as e:
|
|
202
|
+
print(f"Rate limit exceeded: {e}")
|
|
203
|
+
except CacheAIError as e:
|
|
204
|
+
print(f"API error: {e}")
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
## API Reference
|
|
208
|
+
|
|
209
|
+
### Client
|
|
210
|
+
|
|
211
|
+
```python
|
|
212
|
+
Client(
|
|
213
|
+
api_key: Optional[str] = None, # CacheAI API key
|
|
214
|
+
base_url: Optional[str] = None, # API base URL
|
|
215
|
+
timeout: float = 60.0, # Request timeout
|
|
216
|
+
max_retries: int = 2, # Max retry attempts
|
|
217
|
+
enable_cache: bool = True, # Enable semantic caching
|
|
218
|
+
backend_provider: Optional[str] = None, # Backend LLM provider
|
|
219
|
+
backend_api_key: Optional[str] = None, # Backend API key
|
|
220
|
+
backend_base_url: Optional[str] = None # Custom backend URL
|
|
221
|
+
)
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
### Chat Completions
|
|
225
|
+
|
|
226
|
+
```python
|
|
227
|
+
client.chat.completions.create(
|
|
228
|
+
model: str, # Model ID
|
|
229
|
+
messages: List[Dict[str, str]], # Conversation messages
|
|
230
|
+
temperature: Optional[float] = None, # Sampling temperature (0-2)
|
|
231
|
+
max_tokens: Optional[int] = None, # Max tokens to generate
|
|
232
|
+
top_p: Optional[float] = None, # Nucleus sampling
|
|
233
|
+
frequency_penalty: Optional[float] = None, # Frequency penalty
|
|
234
|
+
presence_penalty: Optional[float] = None, # Presence penalty
|
|
235
|
+
stop: Optional[Union[str, List[str]]] = None, # Stop sequences
|
|
236
|
+
stream: bool = False # Enable streaming
|
|
237
|
+
) -> ChatCompletion
|
|
238
|
+
```
|
|
239
|
+
|
|
240
|
+
## Environment Variables
|
|
241
|
+
|
|
242
|
+
| Variable | Description | Default |
|
|
243
|
+
|----------|-------------|---------|
|
|
244
|
+
| `CACHEAI_API_KEY` | CacheAI API key | (required) |
|
|
245
|
+
| `CACHEAI_BASE_URL` | API base URL | `https://api.cacheai.tech/v1` |
|
|
246
|
+
| `CACHEAI_ENABLE_CACHE` | Enable semantic caching | `true` |
|
|
247
|
+
| `CACHEAI_BACKEND_PROVIDER` | Backend LLM provider | (optional) |
|
|
248
|
+
| `CACHEAI_BACKEND_API_KEY` | Backend LLM API key | (optional) |
|
|
249
|
+
| `CACHEAI_BACKEND_BASE_URL` | Custom backend URL | (optional) |
|
|
250
|
+
|
|
251
|
+
## Migration from OpenAI
|
|
252
|
+
|
|
253
|
+
CacheAI is designed to be a drop-in replacement for OpenAI:
|
|
254
|
+
|
|
255
|
+
```python
|
|
256
|
+
# Before (OpenAI)
|
|
257
|
+
from openai import OpenAI
|
|
258
|
+
client = OpenAI(api_key="sk-...")
|
|
259
|
+
response = client.chat.completions.create(...)
|
|
260
|
+
|
|
261
|
+
# After (CacheAI)
|
|
262
|
+
from cacheai import Client
|
|
263
|
+
client = Client(api_key="ca-...", backend_provider="openai", backend_api_key="sk-...")
|
|
264
|
+
response = client.chat.completions.create(...)
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
## Examples
|
|
268
|
+
|
|
269
|
+
See the [examples](./examples/) directory for more usage examples:
|
|
270
|
+
|
|
271
|
+
- [Basic Chat](./examples/chat_example.py)
|
|
272
|
+
- [Streaming](./examples/streaming_example.py)
|
|
273
|
+
- [Error Handling](./examples/error_handling.py)
|
|
274
|
+
|
|
275
|
+
## Development
|
|
276
|
+
|
|
277
|
+
### Install Development Dependencies
|
|
278
|
+
|
|
279
|
+
```bash
|
|
280
|
+
pip install -e ".[dev]"
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
### Run Tests
|
|
284
|
+
|
|
285
|
+
```bash
|
|
286
|
+
pytest
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
### Type Checking
|
|
290
|
+
|
|
291
|
+
```bash
|
|
292
|
+
mypy cacheai
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
### Code Formatting
|
|
296
|
+
|
|
297
|
+
```bash
|
|
298
|
+
black cacheai
|
|
299
|
+
ruff cacheai
|
|
300
|
+
```
|
|
301
|
+
|
|
302
|
+
## Support
|
|
303
|
+
|
|
304
|
+
- **Documentation**: [https://docs.cacheai.tech](https://docs.cacheai.tech)
|
|
305
|
+
- **Issues**: [GitHub Issues](https://github.com/cacheaitechnologies/cacheai-python/issues)
|
|
306
|
+
- **Email**: info@cacheaitechnologies.com
|
|
307
|
+
|
|
308
|
+
## License
|
|
309
|
+
|
|
310
|
+
MIT License - see [LICENSE](LICENSE) file for details.
|
|
311
|
+
|
|
312
|
+
## Links
|
|
313
|
+
|
|
314
|
+
- [Homepage](https://www.cacheaitechnologies.com)
|
|
315
|
+
- [Documentation](https://docs.cacheai.tech)
|
|
316
|
+
- [GitHub Repository](https://github.com/cacheaitechnologies/cacheai-python)
|
|
317
|
+
- [PyPI Package](https://pypi.org/project/cacheai/)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
cacheai/__init__.py,sha256=RKpV9taEo7HBpjqPdM0rJilIwxHwBLdtN4ZxTkjvNy0,976
|
|
2
|
+
cacheai/cache_operation.py,sha256=i7ac7ac5SJVfX4oOvwhnEroHsh_Pao9S-2ReWD8DzdM,18971
|
|
3
|
+
cacheai/client.py,sha256=_mk9azrMDFFRVxBtrgmwTyeH3WL52oi4rbSuCdS_vhg,8661
|
|
4
|
+
cacheai/exceptions.py,sha256=XtidjJ3FHTWQNC8uylzpsj20EfcUMAkBUOWXWlnzo0c,1236
|
|
5
|
+
cacheai/types.py,sha256=4861R6MbWc7N_Bj8nLinuTHNin00XdPcZrCgP5fd24Y,2751
|
|
6
|
+
cacheai/version.py,sha256=NiixAmVESLFRrzpEAMHhm7EzqPVrlXlilO6QpLNqgvc,134
|
|
7
|
+
cacheai/resources/__init__.py,sha256=ikTQXA2vvYSPMejSrNaxRROAT8DvbkQACRftoJIc5hY,90
|
|
8
|
+
cacheai/resources/chat.py,sha256=RL0abJd-FHfyGBTN36d-fG-Svd41f1Yy8OJaHCIQkt8,3531
|
|
9
|
+
cacheai-0.1.0.dist-info/METADATA,sha256=PBkhoI2nzwQyHzc9OhjTMndEwF0No4B3IbAAQYkdddk,8848
|
|
10
|
+
cacheai-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
11
|
+
cacheai-0.1.0.dist-info/top_level.txt,sha256=vv-IS0OScOaUtFy_qd5ARdYLXaBAswgLhzOkHYaU7tI,8
|
|
12
|
+
cacheai-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
cacheai
|