You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

db_models.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. #
  2. # Copyright 2024 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import inspect
  17. import os
  18. import sys
  19. import typing
  20. import operator
  21. from functools import wraps
  22. from itsdangerous.url_safe import URLSafeTimedSerializer as Serializer
  23. from flask_login import UserMixin
  24. from playhouse.migrate import MySQLMigrator, migrate
  25. from peewee import (
  26. BigIntegerField, BooleanField, CharField,
  27. CompositeKey, IntegerField, TextField, FloatField, DateTimeField,
  28. Field, Model, Metadata
  29. )
  30. from playhouse.pool import PooledMySQLDatabase
  31. from api.db import SerializedType, ParserType
  32. from api.settings import DATABASE, stat_logger, SECRET_KEY
  33. from api.utils.log_utils import getLogger
  34. from api import utils
  35. LOGGER = getLogger()
  36. def singleton(cls, *args, **kw):
  37. instances = {}
  38. def _singleton():
  39. key = str(cls) + str(os.getpid())
  40. if key not in instances:
  41. instances[key] = cls(*args, **kw)
  42. return instances[key]
  43. return _singleton
  44. CONTINUOUS_FIELD_TYPE = {IntegerField, FloatField, DateTimeField}
  45. AUTO_DATE_TIMESTAMP_FIELD_PREFIX = {
  46. "create",
  47. "start",
  48. "end",
  49. "update",
  50. "read_access",
  51. "write_access"}
  52. class LongTextField(TextField):
  53. field_type = 'LONGTEXT'
  54. class JSONField(LongTextField):
  55. default_value = {}
  56. def __init__(self, object_hook=None, object_pairs_hook=None, **kwargs):
  57. self._object_hook = object_hook
  58. self._object_pairs_hook = object_pairs_hook
  59. super().__init__(**kwargs)
  60. def db_value(self, value):
  61. if value is None:
  62. value = self.default_value
  63. return utils.json_dumps(value)
  64. def python_value(self, value):
  65. if not value:
  66. return self.default_value
  67. return utils.json_loads(
  68. value, object_hook=self._object_hook, object_pairs_hook=self._object_pairs_hook)
  69. class ListField(JSONField):
  70. default_value = []
  71. class SerializedField(LongTextField):
  72. def __init__(self, serialized_type=SerializedType.PICKLE,
  73. object_hook=None, object_pairs_hook=None, **kwargs):
  74. self._serialized_type = serialized_type
  75. self._object_hook = object_hook
  76. self._object_pairs_hook = object_pairs_hook
  77. super().__init__(**kwargs)
  78. def db_value(self, value):
  79. if self._serialized_type == SerializedType.PICKLE:
  80. return utils.serialize_b64(value, to_str=True)
  81. elif self._serialized_type == SerializedType.JSON:
  82. if value is None:
  83. return None
  84. return utils.json_dumps(value, with_type=True)
  85. else:
  86. raise ValueError(
  87. f"the serialized type {self._serialized_type} is not supported")
  88. def python_value(self, value):
  89. if self._serialized_type == SerializedType.PICKLE:
  90. return utils.deserialize_b64(value)
  91. elif self._serialized_type == SerializedType.JSON:
  92. if value is None:
  93. return {}
  94. return utils.json_loads(
  95. value, object_hook=self._object_hook, object_pairs_hook=self._object_pairs_hook)
  96. else:
  97. raise ValueError(
  98. f"the serialized type {self._serialized_type} is not supported")
  99. def is_continuous_field(cls: typing.Type) -> bool:
  100. if cls in CONTINUOUS_FIELD_TYPE:
  101. return True
  102. for p in cls.__bases__:
  103. if p in CONTINUOUS_FIELD_TYPE:
  104. return True
  105. elif p != Field and p != object:
  106. if is_continuous_field(p):
  107. return True
  108. else:
  109. return False
  110. def auto_date_timestamp_field():
  111. return {f"{f}_time" for f in AUTO_DATE_TIMESTAMP_FIELD_PREFIX}
  112. def auto_date_timestamp_db_field():
  113. return {f"f_{f}_time" for f in AUTO_DATE_TIMESTAMP_FIELD_PREFIX}
  114. def remove_field_name_prefix(field_name):
  115. return field_name[2:] if field_name.startswith('f_') else field_name
  116. class BaseModel(Model):
  117. create_time = BigIntegerField(null=True)
  118. create_date = DateTimeField(null=True)
  119. update_time = BigIntegerField(null=True)
  120. update_date = DateTimeField(null=True)
  121. def to_json(self):
  122. # This function is obsolete
  123. return self.to_dict()
  124. def to_dict(self):
  125. return self.__dict__['__data__']
  126. def to_human_model_dict(self, only_primary_with: list = None):
  127. model_dict = self.__dict__['__data__']
  128. if not only_primary_with:
  129. return {remove_field_name_prefix(
  130. k): v for k, v in model_dict.items()}
  131. human_model_dict = {}
  132. for k in self._meta.primary_key.field_names:
  133. human_model_dict[remove_field_name_prefix(k)] = model_dict[k]
  134. for k in only_primary_with:
  135. human_model_dict[k] = model_dict[f'f_{k}']
  136. return human_model_dict
  137. @property
  138. def meta(self) -> Metadata:
  139. return self._meta
  140. @classmethod
  141. def get_primary_keys_name(cls):
  142. return cls._meta.primary_key.field_names if isinstance(cls._meta.primary_key, CompositeKey) else [
  143. cls._meta.primary_key.name]
  144. @classmethod
  145. def getter_by(cls, attr):
  146. return operator.attrgetter(attr)(cls)
  147. @classmethod
  148. def query(cls, reverse=None, order_by=None, **kwargs):
  149. filters = []
  150. for f_n, f_v in kwargs.items():
  151. attr_name = '%s' % f_n
  152. if not hasattr(cls, attr_name) or f_v is None:
  153. continue
  154. if type(f_v) in {list, set}:
  155. f_v = list(f_v)
  156. if is_continuous_field(type(getattr(cls, attr_name))):
  157. if len(f_v) == 2:
  158. for i, v in enumerate(f_v):
  159. if isinstance(
  160. v, str) and f_n in auto_date_timestamp_field():
  161. # time type: %Y-%m-%d %H:%M:%S
  162. f_v[i] = utils.date_string_to_timestamp(v)
  163. lt_value = f_v[0]
  164. gt_value = f_v[1]
  165. if lt_value is not None and gt_value is not None:
  166. filters.append(
  167. cls.getter_by(attr_name).between(
  168. lt_value, gt_value))
  169. elif lt_value is not None:
  170. filters.append(
  171. operator.attrgetter(attr_name)(cls) >= lt_value)
  172. elif gt_value is not None:
  173. filters.append(
  174. operator.attrgetter(attr_name)(cls) <= gt_value)
  175. else:
  176. filters.append(operator.attrgetter(attr_name)(cls) << f_v)
  177. else:
  178. filters.append(operator.attrgetter(attr_name)(cls) == f_v)
  179. if filters:
  180. query_records = cls.select().where(*filters)
  181. if reverse is not None:
  182. if not order_by or not hasattr(cls, f"{order_by}"):
  183. order_by = "create_time"
  184. if reverse is True:
  185. query_records = query_records.order_by(
  186. cls.getter_by(f"{order_by}").desc())
  187. elif reverse is False:
  188. query_records = query_records.order_by(
  189. cls.getter_by(f"{order_by}").asc())
  190. return [query_record for query_record in query_records]
  191. else:
  192. return []
  193. @classmethod
  194. def insert(cls, __data=None, **insert):
  195. if isinstance(__data, dict) and __data:
  196. __data[cls._meta.combined["create_time"]
  197. ] = utils.current_timestamp()
  198. if insert:
  199. insert["create_time"] = utils.current_timestamp()
  200. return super().insert(__data, **insert)
  201. # update and insert will call this method
  202. @classmethod
  203. def _normalize_data(cls, data, kwargs):
  204. normalized = super()._normalize_data(data, kwargs)
  205. if not normalized:
  206. return {}
  207. normalized[cls._meta.combined["update_time"]
  208. ] = utils.current_timestamp()
  209. for f_n in AUTO_DATE_TIMESTAMP_FIELD_PREFIX:
  210. if {f"{f_n}_time", f"{f_n}_date"}.issubset(cls._meta.combined.keys()) and \
  211. cls._meta.combined[f"{f_n}_time"] in normalized and \
  212. normalized[cls._meta.combined[f"{f_n}_time"]] is not None:
  213. normalized[cls._meta.combined[f"{f_n}_date"]] = utils.timestamp_to_date(
  214. normalized[cls._meta.combined[f"{f_n}_time"]])
  215. return normalized
  216. class JsonSerializedField(SerializedField):
  217. def __init__(self, object_hook=utils.from_dict_hook,
  218. object_pairs_hook=None, **kwargs):
  219. super(JsonSerializedField, self).__init__(serialized_type=SerializedType.JSON, object_hook=object_hook,
  220. object_pairs_hook=object_pairs_hook, **kwargs)
  221. @singleton
  222. class BaseDataBase:
  223. def __init__(self):
  224. database_config = DATABASE.copy()
  225. db_name = database_config.pop("name")
  226. self.database_connection = PooledMySQLDatabase(
  227. db_name, **database_config)
  228. stat_logger.info('init mysql database on cluster mode successfully')
  229. class DatabaseLock:
  230. def __init__(self, lock_name, timeout=10, db=None):
  231. self.lock_name = lock_name
  232. self.timeout = int(timeout)
  233. self.db = db if db else DB
  234. def lock(self):
  235. # SQL parameters only support %s format placeholders
  236. cursor = self.db.execute_sql(
  237. "SELECT GET_LOCK(%s, %s)", (self.lock_name, self.timeout))
  238. ret = cursor.fetchone()
  239. if ret[0] == 0:
  240. raise Exception(f'acquire mysql lock {self.lock_name} timeout')
  241. elif ret[0] == 1:
  242. return True
  243. else:
  244. raise Exception(f'failed to acquire lock {self.lock_name}')
  245. def unlock(self):
  246. cursor = self.db.execute_sql(
  247. "SELECT RELEASE_LOCK(%s)", (self.lock_name,))
  248. ret = cursor.fetchone()
  249. if ret[0] == 0:
  250. raise Exception(
  251. f'mysql lock {self.lock_name} was not established by this thread')
  252. elif ret[0] == 1:
  253. return True
  254. else:
  255. raise Exception(f'mysql lock {self.lock_name} does not exist')
  256. def __enter__(self):
  257. if isinstance(self.db, PooledMySQLDatabase):
  258. self.lock()
  259. return self
  260. def __exit__(self, exc_type, exc_val, exc_tb):
  261. if isinstance(self.db, PooledMySQLDatabase):
  262. self.unlock()
  263. def __call__(self, func):
  264. @wraps(func)
  265. def magic(*args, **kwargs):
  266. with self:
  267. return func(*args, **kwargs)
  268. return magic
  269. DB = BaseDataBase().database_connection
  270. DB.lock = DatabaseLock
  271. def close_connection():
  272. try:
  273. if DB:
  274. DB.close()
  275. except Exception as e:
  276. LOGGER.exception(e)
  277. class DataBaseModel(BaseModel):
  278. class Meta:
  279. database = DB
  280. @DB.connection_context()
  281. def init_database_tables(alter_fields=[]):
  282. members = inspect.getmembers(sys.modules[__name__], inspect.isclass)
  283. table_objs = []
  284. create_failed_list = []
  285. for name, obj in members:
  286. if obj != DataBaseModel and issubclass(obj, DataBaseModel):
  287. table_objs.append(obj)
  288. LOGGER.info(f"start create table {obj.__name__}")
  289. try:
  290. obj.create_table()
  291. LOGGER.info(f"create table success: {obj.__name__}")
  292. except Exception as e:
  293. LOGGER.exception(e)
  294. create_failed_list.append(obj.__name__)
  295. if create_failed_list:
  296. LOGGER.info(f"create tables failed: {create_failed_list}")
  297. raise Exception(f"create tables failed: {create_failed_list}")
  298. migrate_db()
  299. def fill_db_model_object(model_object, human_model_dict):
  300. for k, v in human_model_dict.items():
  301. attr_name = '%s' % k
  302. if hasattr(model_object.__class__, attr_name):
  303. setattr(model_object, attr_name, v)
  304. return model_object
  305. class User(DataBaseModel, UserMixin):
  306. id = CharField(max_length=32, primary_key=True)
  307. access_token = CharField(max_length=255, null=True)
  308. nickname = CharField(max_length=100, null=False, help_text="nicky name")
  309. password = CharField(max_length=255, null=True, help_text="password")
  310. email = CharField(
  311. max_length=255,
  312. null=False,
  313. help_text="email",
  314. index=True)
  315. avatar = TextField(null=True, help_text="avatar base64 string")
  316. language = CharField(
  317. max_length=32,
  318. null=True,
  319. help_text="English|Chinese",
  320. default="Chinese" if "zh_CN" in os.getenv("LANG", "") else "English")
  321. color_schema = CharField(
  322. max_length=32,
  323. null=True,
  324. help_text="Bright|Dark",
  325. default="Bright")
  326. timezone = CharField(
  327. max_length=64,
  328. null=True,
  329. help_text="Timezone",
  330. default="UTC+8\tAsia/Shanghai")
  331. last_login_time = DateTimeField(null=True)
  332. is_authenticated = CharField(max_length=1, null=False, default="1")
  333. is_active = CharField(max_length=1, null=False, default="1")
  334. is_anonymous = CharField(max_length=1, null=False, default="0")
  335. login_channel = CharField(null=True, help_text="from which user login")
  336. status = CharField(
  337. max_length=1,
  338. null=True,
  339. help_text="is it validate(0: wasted,1: validate)",
  340. default="1")
  341. is_superuser = BooleanField(null=True, help_text="is root", default=False)
  342. def __str__(self):
  343. return self.email
  344. def get_id(self):
  345. jwt = Serializer(secret_key=SECRET_KEY)
  346. return jwt.dumps(str(self.access_token))
  347. class Meta:
  348. db_table = "user"
  349. class Tenant(DataBaseModel):
  350. id = CharField(max_length=32, primary_key=True)
  351. name = CharField(max_length=100, null=True, help_text="Tenant name")
  352. public_key = CharField(max_length=255, null=True)
  353. llm_id = CharField(max_length=128, null=False, help_text="default llm ID")
  354. embd_id = CharField(
  355. max_length=128,
  356. null=False,
  357. help_text="default embedding model ID")
  358. asr_id = CharField(
  359. max_length=128,
  360. null=False,
  361. help_text="default ASR model ID")
  362. img2txt_id = CharField(
  363. max_length=128,
  364. null=False,
  365. help_text="default image to text model ID")
  366. parser_ids = CharField(
  367. max_length=256,
  368. null=False,
  369. help_text="document processors")
  370. credit = IntegerField(default=512)
  371. status = CharField(
  372. max_length=1,
  373. null=True,
  374. help_text="is it validate(0: wasted,1: validate)",
  375. default="1")
  376. class Meta:
  377. db_table = "tenant"
  378. class UserTenant(DataBaseModel):
  379. id = CharField(max_length=32, primary_key=True)
  380. user_id = CharField(max_length=32, null=False)
  381. tenant_id = CharField(max_length=32, null=False)
  382. role = CharField(max_length=32, null=False, help_text="UserTenantRole")
  383. invited_by = CharField(max_length=32, null=False)
  384. status = CharField(
  385. max_length=1,
  386. null=True,
  387. help_text="is it validate(0: wasted,1: validate)",
  388. default="1")
  389. class Meta:
  390. db_table = "user_tenant"
  391. class InvitationCode(DataBaseModel):
  392. id = CharField(max_length=32, primary_key=True)
  393. code = CharField(max_length=32, null=False)
  394. visit_time = DateTimeField(null=True)
  395. user_id = CharField(max_length=32, null=True)
  396. tenant_id = CharField(max_length=32, null=True)
  397. status = CharField(
  398. max_length=1,
  399. null=True,
  400. help_text="is it validate(0: wasted,1: validate)",
  401. default="1")
  402. class Meta:
  403. db_table = "invitation_code"
  404. class LLMFactories(DataBaseModel):
  405. name = CharField(
  406. max_length=128,
  407. null=False,
  408. help_text="LLM factory name",
  409. primary_key=True)
  410. logo = TextField(null=True, help_text="llm logo base64")
  411. tags = CharField(
  412. max_length=255,
  413. null=False,
  414. help_text="LLM, Text Embedding, Image2Text, ASR")
  415. status = CharField(
  416. max_length=1,
  417. null=True,
  418. help_text="is it validate(0: wasted,1: validate)",
  419. default="1")
  420. def __str__(self):
  421. return self.name
  422. class Meta:
  423. db_table = "llm_factories"
  424. class LLM(DataBaseModel):
  425. # LLMs dictionary
  426. llm_name = CharField(
  427. max_length=128,
  428. null=False,
  429. help_text="LLM name",
  430. index=True,
  431. primary_key=True)
  432. model_type = CharField(
  433. max_length=128,
  434. null=False,
  435. help_text="LLM, Text Embedding, Image2Text, ASR")
  436. fid = CharField(max_length=128, null=False, help_text="LLM factory id")
  437. max_tokens = IntegerField(default=0)
  438. tags = CharField(
  439. max_length=255,
  440. null=False,
  441. help_text="LLM, Text Embedding, Image2Text, Chat, 32k...")
  442. status = CharField(
  443. max_length=1,
  444. null=True,
  445. help_text="is it validate(0: wasted,1: validate)",
  446. default="1")
  447. def __str__(self):
  448. return self.llm_name
  449. class Meta:
  450. db_table = "llm"
  451. class TenantLLM(DataBaseModel):
  452. tenant_id = CharField(max_length=32, null=False)
  453. llm_factory = CharField(
  454. max_length=128,
  455. null=False,
  456. help_text="LLM factory name")
  457. model_type = CharField(
  458. max_length=128,
  459. null=True,
  460. help_text="LLM, Text Embedding, Image2Text, ASR")
  461. llm_name = CharField(
  462. max_length=128,
  463. null=True,
  464. help_text="LLM name",
  465. default="")
  466. api_key = CharField(max_length=255, null=True, help_text="API KEY")
  467. api_base = CharField(max_length=255, null=True, help_text="API Base")
  468. used_tokens = IntegerField(default=0)
  469. def __str__(self):
  470. return self.llm_name
  471. class Meta:
  472. db_table = "tenant_llm"
  473. primary_key = CompositeKey('tenant_id', 'llm_factory', 'llm_name')
  474. class Knowledgebase(DataBaseModel):
  475. id = CharField(max_length=32, primary_key=True)
  476. avatar = TextField(null=True, help_text="avatar base64 string")
  477. tenant_id = CharField(max_length=32, null=False)
  478. name = CharField(
  479. max_length=128,
  480. null=False,
  481. help_text="KB name",
  482. index=True)
  483. language = CharField(
  484. max_length=32,
  485. null=True,
  486. default="Chinese" if "zh_CN" in os.getenv("LANG", "") else "English",
  487. help_text="English|Chinese")
  488. description = TextField(null=True, help_text="KB description")
  489. embd_id = CharField(
  490. max_length=128,
  491. null=False,
  492. help_text="default embedding model ID")
  493. permission = CharField(
  494. max_length=16,
  495. null=False,
  496. help_text="me|team",
  497. default="me")
  498. created_by = CharField(max_length=32, null=False)
  499. doc_num = IntegerField(default=0)
  500. token_num = IntegerField(default=0)
  501. chunk_num = IntegerField(default=0)
  502. similarity_threshold = FloatField(default=0.2)
  503. vector_similarity_weight = FloatField(default=0.3)
  504. parser_id = CharField(
  505. max_length=32,
  506. null=False,
  507. help_text="default parser ID",
  508. default=ParserType.NAIVE.value)
  509. parser_config = JSONField(null=False, default={"pages": [[1, 1000000]]})
  510. status = CharField(
  511. max_length=1,
  512. null=True,
  513. help_text="is it validate(0: wasted,1: validate)",
  514. default="1")
  515. def __str__(self):
  516. return self.name
  517. class Meta:
  518. db_table = "knowledgebase"
  519. class Document(DataBaseModel):
  520. id = CharField(max_length=32, primary_key=True)
  521. thumbnail = TextField(null=True, help_text="thumbnail base64 string")
  522. kb_id = CharField(max_length=256, null=False, index=True)
  523. parser_id = CharField(
  524. max_length=32,
  525. null=False,
  526. help_text="default parser ID")
  527. parser_config = JSONField(null=False, default={"pages": [[1, 1000000]]})
  528. source_type = CharField(
  529. max_length=128,
  530. null=False,
  531. default="local",
  532. help_text="where dose this document come from")
  533. type = CharField(max_length=32, null=False, help_text="file extension")
  534. created_by = CharField(
  535. max_length=32,
  536. null=False,
  537. help_text="who created it")
  538. name = CharField(
  539. max_length=255,
  540. null=True,
  541. help_text="file name",
  542. index=True)
  543. location = CharField(
  544. max_length=255,
  545. null=True,
  546. help_text="where dose it store")
  547. size = IntegerField(default=0)
  548. token_num = IntegerField(default=0)
  549. chunk_num = IntegerField(default=0)
  550. progress = FloatField(default=0)
  551. progress_msg = TextField(
  552. null=True,
  553. help_text="process message",
  554. default="")
  555. process_begin_at = DateTimeField(null=True)
  556. process_duation = FloatField(default=0)
  557. run = CharField(
  558. max_length=1,
  559. null=True,
  560. help_text="start to run processing or cancel.(1: run it; 2: cancel)",
  561. default="0")
  562. status = CharField(
  563. max_length=1,
  564. null=True,
  565. help_text="is it validate(0: wasted,1: validate)",
  566. default="1")
  567. class Meta:
  568. db_table = "document"
  569. class File(DataBaseModel):
  570. id = CharField(
  571. max_length=32,
  572. primary_key=True,
  573. )
  574. parent_id = CharField(
  575. max_length=32,
  576. null=False,
  577. help_text="parent folder id",
  578. index=True)
  579. tenant_id = CharField(
  580. max_length=32,
  581. null=False,
  582. help_text="tenant id",
  583. index=True)
  584. created_by = CharField(
  585. max_length=32,
  586. null=False,
  587. help_text="who created it")
  588. name = CharField(
  589. max_length=255,
  590. null=False,
  591. help_text="file name or folder name",
  592. index=True)
  593. location = CharField(
  594. max_length=255,
  595. null=True,
  596. help_text="where dose it store")
  597. size = IntegerField(default=0)
  598. type = CharField(max_length=32, null=False, help_text="file extension")
  599. source_type = CharField(
  600. max_length=128,
  601. null=False,
  602. default="",
  603. help_text="where dose this document come from")
  604. class Meta:
  605. db_table = "file"
  606. class File2Document(DataBaseModel):
  607. id = CharField(
  608. max_length=32,
  609. primary_key=True,
  610. )
  611. file_id = CharField(
  612. max_length=32,
  613. null=True,
  614. help_text="file id",
  615. index=True)
  616. document_id = CharField(
  617. max_length=32,
  618. null=True,
  619. help_text="document id",
  620. index=True)
  621. class Meta:
  622. db_table = "file2document"
  623. class Task(DataBaseModel):
  624. id = CharField(max_length=32, primary_key=True)
  625. doc_id = CharField(max_length=32, null=False, index=True)
  626. from_page = IntegerField(default=0)
  627. to_page = IntegerField(default=-1)
  628. begin_at = DateTimeField(null=True)
  629. process_duation = FloatField(default=0)
  630. progress = FloatField(default=0)
  631. progress_msg = TextField(
  632. null=True,
  633. help_text="process message",
  634. default="")
  635. class Dialog(DataBaseModel):
  636. id = CharField(max_length=32, primary_key=True)
  637. tenant_id = CharField(max_length=32, null=False)
  638. name = CharField(
  639. max_length=255,
  640. null=True,
  641. help_text="dialog application name")
  642. description = TextField(null=True, help_text="Dialog description")
  643. icon = TextField(null=True, help_text="icon base64 string")
  644. language = CharField(
  645. max_length=32,
  646. null=True,
  647. default="Chinese" if "zh_CN" in os.getenv("LANG", "") else "English",
  648. help_text="English|Chinese")
  649. llm_id = CharField(max_length=128, null=False, help_text="default llm ID")
  650. llm_setting = JSONField(null=False, default={"temperature": 0.1, "top_p": 0.3, "frequency_penalty": 0.7,
  651. "presence_penalty": 0.4, "max_tokens": 512})
  652. prompt_type = CharField(
  653. max_length=16,
  654. null=False,
  655. default="simple",
  656. help_text="simple|advanced")
  657. prompt_config = JSONField(null=False, default={"system": "", "prologue": "您好,我是您的助手小樱,长得可爱又善良,can I help you?",
  658. "parameters": [], "empty_response": "Sorry! 知识库中未找到相关内容!"})
  659. similarity_threshold = FloatField(default=0.2)
  660. vector_similarity_weight = FloatField(default=0.3)
  661. top_n = IntegerField(default=6)
  662. do_refer = CharField(
  663. max_length=1,
  664. null=False,
  665. help_text="it needs to insert reference index into answer or not",
  666. default="1")
  667. kb_ids = JSONField(null=False, default=[])
  668. status = CharField(
  669. max_length=1,
  670. null=True,
  671. help_text="is it validate(0: wasted,1: validate)",
  672. default="1")
  673. class Meta:
  674. db_table = "dialog"
  675. class Conversation(DataBaseModel):
  676. id = CharField(max_length=32, primary_key=True)
  677. dialog_id = CharField(max_length=32, null=False, index=True)
  678. name = CharField(max_length=255, null=True, help_text="converastion name")
  679. message = JSONField(null=True)
  680. reference = JSONField(null=True, default=[])
  681. class Meta:
  682. db_table = "conversation"
  683. class APIToken(DataBaseModel):
  684. tenant_id = CharField(max_length=32, null=False)
  685. token = CharField(max_length=255, null=False)
  686. dialog_id = CharField(max_length=32, null=False, index=True)
  687. class Meta:
  688. db_table = "api_token"
  689. primary_key = CompositeKey('tenant_id', 'token')
  690. class API4Conversation(DataBaseModel):
  691. id = CharField(max_length=32, primary_key=True)
  692. dialog_id = CharField(max_length=32, null=False, index=True)
  693. user_id = CharField(max_length=255, null=False, help_text="user_id")
  694. message = JSONField(null=True)
  695. reference = JSONField(null=True, default=[])
  696. tokens = IntegerField(default=0)
  697. duration = FloatField(default=0)
  698. round = IntegerField(default=0)
  699. thumb_up = IntegerField(default=0)
  700. class Meta:
  701. db_table = "api_4_conversation"
  702. def migrate_db():
  703. try:
  704. with DB.transaction():
  705. migrator = MySQLMigrator(DB)
  706. migrate(
  707. migrator.add_column('file', 'source_type', CharField(max_length=128, null=False, default="", help_text="where dose this document come from"))
  708. )
  709. except Exception as e:
  710. pass