Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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. from peewee import fn
  20. class KnowledgebaseService(CommonService):
  21. model = Knowledgebase
  22. @classmethod
  23. @DB.connection_context()
  24. def is_parsed_done(cls, kb_id):
  25. """
  26. Check if all documents in the knowledge base have completed parsing
  27. Args:
  28. kb_id: Knowledge base ID
  29. Returns:
  30. If all documents are parsed successfully, returns (True, None)
  31. If any document is not fully parsed, returns (False, error_message)
  32. """
  33. from api.db import TaskStatus
  34. from api.db.services.document_service import DocumentService
  35. # Get knowledge base information
  36. kbs = cls.query(id=kb_id)
  37. if not kbs:
  38. return False, "Knowledge base not found"
  39. kb = kbs[0]
  40. # Get all documents in the knowledge base
  41. docs, _ = DocumentService.get_by_kb_id(kb_id, 1, 1000, "create_time", True, "")
  42. # Check parsing status of each document
  43. for doc in docs:
  44. # If document is being parsed, don't allow chat creation
  45. if doc['run'] == TaskStatus.RUNNING.value or doc['run'] == TaskStatus.CANCEL.value or doc['run'] == TaskStatus.FAIL.value:
  46. return False, f"Document '{doc['name']}' in dataset '{kb.name}' is still being parsed. Please wait until all documents are parsed before starting a chat."
  47. # If document is not yet parsed and has no chunks, don't allow chat creation
  48. if doc['run'] == TaskStatus.UNSTART.value and doc['chunk_num'] == 0:
  49. return False, f"Document '{doc['name']}' in dataset '{kb.name}' has not been parsed yet. Please parse all documents before starting a chat."
  50. return True, None
  51. @classmethod
  52. @DB.connection_context()
  53. def list_documents_by_ids(cls,kb_ids):
  54. doc_ids=cls.model.select(Document.id.alias("document_id")).join(Document,on=(cls.model.id == Document.kb_id)).where(
  55. cls.model.id.in_(kb_ids)
  56. )
  57. doc_ids =list(doc_ids.dicts())
  58. doc_ids = [doc["document_id"] for doc in doc_ids]
  59. return doc_ids
  60. @classmethod
  61. @DB.connection_context()
  62. def get_by_tenant_ids(cls, joined_tenant_ids, user_id,
  63. page_number, items_per_page,
  64. orderby, desc, keywords,
  65. parser_id=None
  66. ):
  67. fields = [
  68. cls.model.id,
  69. cls.model.avatar,
  70. cls.model.name,
  71. cls.model.language,
  72. cls.model.description,
  73. cls.model.permission,
  74. cls.model.doc_num,
  75. cls.model.token_num,
  76. cls.model.chunk_num,
  77. cls.model.parser_id,
  78. cls.model.embd_id,
  79. User.nickname,
  80. User.avatar.alias('tenant_avatar'),
  81. cls.model.update_time
  82. ]
  83. if keywords:
  84. kbs = cls.model.select(*fields).join(User, on=(cls.model.tenant_id == User.id)).where(
  85. ((cls.model.tenant_id.in_(joined_tenant_ids) & (cls.model.permission ==
  86. TenantPermission.TEAM.value)) | (
  87. cls.model.tenant_id == user_id))
  88. & (cls.model.status == StatusEnum.VALID.value),
  89. (fn.LOWER(cls.model.name).contains(keywords.lower()))
  90. )
  91. else:
  92. kbs = cls.model.select(*fields).join(User, on=(cls.model.tenant_id == User.id)).where(
  93. ((cls.model.tenant_id.in_(joined_tenant_ids) & (cls.model.permission ==
  94. TenantPermission.TEAM.value)) | (
  95. cls.model.tenant_id == user_id))
  96. & (cls.model.status == StatusEnum.VALID.value)
  97. )
  98. if parser_id:
  99. kbs = kbs.where(cls.model.parser_id == parser_id)
  100. if desc:
  101. kbs = kbs.order_by(cls.model.getter_by(orderby).desc())
  102. else:
  103. kbs = kbs.order_by(cls.model.getter_by(orderby).asc())
  104. count = kbs.count()
  105. kbs = kbs.paginate(page_number, items_per_page)
  106. return list(kbs.dicts()), count
  107. @classmethod
  108. @DB.connection_context()
  109. def get_kb_ids(cls, tenant_id):
  110. fields = [
  111. cls.model.id,
  112. ]
  113. kbs = cls.model.select(*fields).where(cls.model.tenant_id == tenant_id)
  114. kb_ids = [kb.id for kb in kbs]
  115. return kb_ids
  116. @classmethod
  117. @DB.connection_context()
  118. def get_detail(cls, kb_id):
  119. fields = [
  120. cls.model.id,
  121. # Tenant.embd_id,
  122. cls.model.embd_id,
  123. cls.model.avatar,
  124. cls.model.name,
  125. cls.model.language,
  126. cls.model.description,
  127. cls.model.permission,
  128. cls.model.doc_num,
  129. cls.model.token_num,
  130. cls.model.chunk_num,
  131. cls.model.parser_id,
  132. cls.model.parser_config,
  133. cls.model.pagerank]
  134. kbs = cls.model.select(*fields).join(Tenant, on=(
  135. (Tenant.id == cls.model.tenant_id) & (Tenant.status == StatusEnum.VALID.value))).where(
  136. (cls.model.id == kb_id),
  137. (cls.model.status == StatusEnum.VALID.value)
  138. )
  139. if not kbs:
  140. return
  141. d = kbs[0].to_dict()
  142. # d["embd_id"] = kbs[0].tenant.embd_id
  143. return d
  144. @classmethod
  145. @DB.connection_context()
  146. def update_parser_config(cls, id, config):
  147. e, m = cls.get_by_id(id)
  148. if not e:
  149. raise LookupError(f"knowledgebase({id}) not found.")
  150. def dfs_update(old, new):
  151. for k, v in new.items():
  152. if k not in old:
  153. old[k] = v
  154. continue
  155. if isinstance(v, dict):
  156. assert isinstance(old[k], dict)
  157. dfs_update(old[k], v)
  158. elif isinstance(v, list):
  159. assert isinstance(old[k], list)
  160. old[k] = list(set(old[k] + v))
  161. else:
  162. old[k] = v
  163. dfs_update(m.parser_config, config)
  164. cls.update_by_id(id, {"parser_config": m.parser_config})
  165. @classmethod
  166. @DB.connection_context()
  167. def get_field_map(cls, ids):
  168. conf = {}
  169. for k in cls.get_by_ids(ids):
  170. if k.parser_config and "field_map" in k.parser_config:
  171. conf.update(k.parser_config["field_map"])
  172. return conf
  173. @classmethod
  174. @DB.connection_context()
  175. def get_by_name(cls, kb_name, tenant_id):
  176. kb = cls.model.select().where(
  177. (cls.model.name == kb_name)
  178. & (cls.model.tenant_id == tenant_id)
  179. & (cls.model.status == StatusEnum.VALID.value)
  180. )
  181. if kb:
  182. return True, kb[0]
  183. return False, None
  184. @classmethod
  185. @DB.connection_context()
  186. def get_all_ids(cls):
  187. return [m["id"] for m in cls.model.select(cls.model.id).dicts()]
  188. @classmethod
  189. @DB.connection_context()
  190. def get_list(cls, joined_tenant_ids, user_id,
  191. page_number, items_per_page, orderby, desc, id, name):
  192. kbs = cls.model.select()
  193. if id:
  194. kbs = kbs.where(cls.model.id == id)
  195. if name:
  196. kbs = kbs.where(cls.model.name == name)
  197. kbs = kbs.where(
  198. ((cls.model.tenant_id.in_(joined_tenant_ids) & (cls.model.permission ==
  199. TenantPermission.TEAM.value)) | (
  200. cls.model.tenant_id == user_id))
  201. & (cls.model.status == StatusEnum.VALID.value)
  202. )
  203. if desc:
  204. kbs = kbs.order_by(cls.model.getter_by(orderby).desc())
  205. else:
  206. kbs = kbs.order_by(cls.model.getter_by(orderby).asc())
  207. kbs = kbs.paginate(page_number, items_per_page)
  208. return list(kbs.dicts())
  209. @classmethod
  210. @DB.connection_context()
  211. def accessible(cls, kb_id, user_id):
  212. docs = cls.model.select(
  213. cls.model.id).join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  214. ).where(cls.model.id == kb_id, UserTenant.user_id == user_id).paginate(0, 1)
  215. docs = docs.dicts()
  216. if not docs:
  217. return False
  218. return True
  219. @classmethod
  220. @DB.connection_context()
  221. def get_kb_by_id(cls, kb_id, user_id):
  222. kbs = cls.model.select().join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  223. ).where(cls.model.id == kb_id, UserTenant.user_id == user_id).paginate(0, 1)
  224. kbs = kbs.dicts()
  225. return list(kbs)
  226. @classmethod
  227. @DB.connection_context()
  228. def get_kb_by_name(cls, kb_name, user_id):
  229. kbs = cls.model.select().join(UserTenant, on=(UserTenant.tenant_id == Knowledgebase.tenant_id)
  230. ).where(cls.model.name == kb_name, UserTenant.user_id == user_id).paginate(0, 1)
  231. kbs = kbs.dicts()
  232. return list(kbs)
  233. @classmethod
  234. @DB.connection_context()
  235. def accessible4deletion(cls, kb_id, user_id):
  236. docs = cls.model.select(
  237. cls.model.id).where(cls.model.id == kb_id, cls.model.created_by == user_id).paginate(0, 1)
  238. docs = docs.dicts()
  239. if not docs:
  240. return False
  241. return True