您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

knowledgebase_service.py 7.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. from api.db import StatusEnum, TenantPermission
  17. from api.db.db_models import Knowledgebase, DB, Tenant, User, UserTenant,Document
  18. from api.db.services.common_service import CommonService
  19. class KnowledgebaseService(CommonService):
  20. model = Knowledgebase
  21. @classmethod
  22. @DB.connection_context()
  23. def list_documents_by_ids(cls,kb_ids):
  24. doc_ids=cls.model.select(Document.id.alias("document_id")).join(Document,on=(cls.model.id == Document.kb_id)).where(
  25. cls.model.id.in_(kb_ids)
  26. )
  27. doc_ids =list(doc_ids.dicts())
  28. doc_ids = [doc["document_id"] for doc in doc_ids]
  29. return doc_ids
  30. @classmethod
  31. @DB.connection_context()
  32. def get_by_tenant_ids(cls, joined_tenant_ids, user_id,
  33. page_number, items_per_page, orderby, desc):
  34. fields = [
  35. cls.model.id,
  36. cls.model.avatar,
  37. cls.model.name,
  38. cls.model.language,
  39. cls.model.description,
  40. cls.model.permission,
  41. cls.model.doc_num,
  42. cls.model.token_num,
  43. cls.model.chunk_num,
  44. cls.model.parser_id,
  45. cls.model.embd_id,
  46. User.nickname,
  47. User.avatar.alias('tenant_avatar'),
  48. cls.model.update_time
  49. ]
  50. kbs = cls.model.select(*fields).join(User, on=(cls.model.tenant_id == User.id)).where(
  51. ((cls.model.tenant_id.in_(joined_tenant_ids) & (cls.model.permission ==
  52. TenantPermission.TEAM.value)) | (
  53. cls.model.tenant_id == user_id))
  54. & (cls.model.status == StatusEnum.VALID.value)
  55. )
  56. if desc:
  57. kbs = kbs.order_by(cls.model.getter_by(orderby).desc())
  58. else:
  59. kbs = kbs.order_by(cls.model.getter_by(orderby).asc())
  60. kbs = kbs.paginate(page_number, items_per_page)
  61. return list(kbs.dicts())
  62. @classmethod
  63. @DB.connection_context()
  64. def get_kb_ids(cls, tenant_id):
  65. fields = [
  66. cls.model.id,
  67. ]
  68. kbs = cls.model.select(*fields).where(cls.model.tenant_id == tenant_id)
  69. kb_ids = [kb.id for kb in kbs]
  70. return kb_ids
  71. @classmethod
  72. @DB.connection_context()
  73. def get_detail(cls, kb_id):
  74. fields = [
  75. cls.model.id,
  76. # Tenant.embd_id,
  77. cls.model.embd_id,
  78. cls.model.avatar,
  79. cls.model.name,
  80. cls.model.language,
  81. cls.model.description,
  82. cls.model.permission,
  83. cls.model.doc_num,
  84. cls.model.token_num,
  85. cls.model.chunk_num,
  86. cls.model.parser_id,
  87. cls.model.parser_config]
  88. kbs = cls.model.select(*fields).join(Tenant, on=(
  89. (Tenant.id == cls.model.tenant_id) & (Tenant.status == StatusEnum.VALID.value))).where(
  90. (cls.model.id == kb_id),
  91. (cls.model.status == StatusEnum.VALID.value)
  92. )
  93. if not kbs:
  94. return
  95. d = kbs[0].to_dict()
  96. # d["embd_id"] = kbs[0].tenant.embd_id
  97. return d
  98. @classmethod
  99. @DB.connection_context()
  100. def update_parser_config(cls, id, config):
  101. e, m = cls.get_by_id(id)
  102. if not e:
  103. raise LookupError(f"knowledgebase({id}) not found.")
  104. def dfs_update(old, new):
  105. for k, v in new.items():
  106. if k not in old:
  107. old[k] = v
  108. continue
  109. if isinstance(v, dict):
  110. assert isinstance(old[k], dict)
  111. dfs_update(old[k], v)
  112. elif isinstance(v, list):
  113. assert isinstance(old[k], list)
  114. old[k] = list(set(old[k] + v))
  115. else:
  116. old[k] = v
  117. dfs_update(m.parser_config, config)
  118. cls.update_by_id(id, {"parser_config": m.parser_config})
  119. @classmethod
  120. @DB.connection_context()
  121. def get_field_map(cls, ids):
  122. conf = {}
  123. for k in cls.get_by_ids(ids):
  124. if k.parser_config and "field_map" in k.parser_config:
  125. conf.update(k.parser_config["field_map"])
  126. return conf
  127. @classmethod
  128. @DB.connection_context()
  129. def get_by_name(cls, kb_name, tenant_id):
  130. kb = cls.model.select().where(
  131. (cls.model.name == kb_name)
  132. & (cls.model.tenant_id == tenant_id)
  133. & (cls.model.status == StatusEnum.VALID.value)
  134. )
  135. if kb:
  136. return True, kb[0]
  137. return False, None
  138. @classmethod
  139. @DB.connection_context()
  140. def get_all_ids(cls):
  141. return [m["id"] for m in cls.model.select(cls.model.id).dicts()]
  142. @classmethod
  143. @DB.connection_context()
  144. def get_list(cls, joined_tenant_ids, user_id,
  145. page_number, items_per_page, orderby, desc, id, name):
  146. kbs = cls.model.select()
  147. if id:
  148. kbs = kbs.where(cls.model.id == id)
  149. if name:
  150. kbs = kbs.where(cls.model.name == name)
  151. kbs = kbs.where(
  152. ((cls.model.tenant_id.in_(joined_tenant_ids) & (cls.model.permission ==
  153. TenantPermission.TEAM.value)) | (
  154. cls.model.tenant_id == user_id))
  155. & (cls.model.status == StatusEnum.VALID.value)
  156. )
  157. if desc:
  158. kbs = kbs.order_by(cls.model.getter_by(orderby).desc())
  159. else:
  160. kbs = kbs.order_by(cls.model.getter_by(orderby).asc())
  161. kbs = kbs.paginate(page_number, items_per_page)
  162. return list(kbs.dicts())
  163. @classmethod
  164. @DB.connection_context()
  165. def accessible(cls, kb_id, user_id):
  166. docs = cls.model.select(
  167. cls.model.id).join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  168. ).where(cls.model.id == kb_id, UserTenant.user_id == user_id).paginate(0, 1)
  169. docs = docs.dicts()
  170. if not docs:
  171. return False
  172. return True
  173. @classmethod
  174. @DB.connection_context()
  175. def get_kb_by_id(cls, kb_id, user_id):
  176. kbs = cls.model.select().join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  177. ).where(cls.model.id == kb_id, UserTenant.user_id == user_id).paginate(0, 1)
  178. kbs = kbs.dicts()
  179. return list(kbs)
  180. @classmethod
  181. @DB.connection_context()
  182. def get_kb_by_name(cls, kb_name, user_id):
  183. kbs = cls.model.select().join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  184. ).where(cls.model.name == kb_name, UserTenant.user_id == user_id).paginate(0, 1)
  185. kbs = kbs.dicts()
  186. return list(kbs)
  187. @classmethod
  188. @DB.connection_context()
  189. def accessible4deletion(cls, kb_id, user_id):
  190. docs = cls.model.select(
  191. cls.model.id).where(cls.model.id == kb_id, cls.model.created_by == user_id).paginate(0, 1)
  192. docs = docs.dicts()
  193. if not docs:
  194. return False
  195. return True