Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

init_data.py 7.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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 logging
  17. import base64
  18. import json
  19. import os
  20. import time
  21. import uuid
  22. from copy import deepcopy
  23. from api.db import LLMType, UserTenantRole
  24. from api.db.db_models import init_database_tables as init_web_db, LLMFactories, LLM, TenantLLM
  25. from api.db.services import UserService
  26. from api.db.services.canvas_service import CanvasTemplateService
  27. from api.db.services.document_service import DocumentService
  28. from api.db.services.knowledgebase_service import KnowledgebaseService
  29. from api.db.services.tenant_llm_service import LLMFactoriesService, TenantLLMService
  30. from api.db.services.llm_service import LLMService, LLMBundle, get_init_tenant_llm
  31. from api.db.services.user_service import TenantService, UserTenantService
  32. from api import settings
  33. from api.utils.file_utils import get_project_base_directory
  34. def encode_to_base64(input_string):
  35. base64_encoded = base64.b64encode(input_string.encode('utf-8'))
  36. return base64_encoded.decode('utf-8')
  37. def init_superuser():
  38. user_info = {
  39. "id": uuid.uuid1().hex,
  40. "password": encode_to_base64("admin"),
  41. "nickname": "admin",
  42. "is_superuser": True,
  43. "email": "admin@ragflow.io",
  44. "creator": "system",
  45. "status": "1",
  46. }
  47. tenant = {
  48. "id": user_info["id"],
  49. "name": user_info["nickname"] + "‘s Kingdom",
  50. "llm_id": settings.CHAT_MDL,
  51. "embd_id": settings.EMBEDDING_MDL,
  52. "asr_id": settings.ASR_MDL,
  53. "parser_ids": settings.PARSERS,
  54. "img2txt_id": settings.IMAGE2TEXT_MDL
  55. }
  56. usr_tenant = {
  57. "tenant_id": user_info["id"],
  58. "user_id": user_info["id"],
  59. "invited_by": user_info["id"],
  60. "role": UserTenantRole.OWNER
  61. }
  62. tenant_llm = get_init_tenant_llm(user_info["id"])
  63. if not UserService.save(**user_info):
  64. logging.error("can't init admin.")
  65. return
  66. TenantService.insert(**tenant)
  67. UserTenantService.insert(**usr_tenant)
  68. TenantLLMService.insert_many(tenant_llm)
  69. logging.info(
  70. "Super user initialized. email: admin@ragflow.io, password: admin. Changing the password after login is strongly recommended.")
  71. chat_mdl = LLMBundle(tenant["id"], LLMType.CHAT, tenant["llm_id"])
  72. msg = chat_mdl.chat(system="", history=[
  73. {"role": "user", "content": "Hello!"}], gen_conf={})
  74. if msg.find("ERROR: ") == 0:
  75. logging.error(
  76. "'{}' doesn't work. {}".format(
  77. tenant["llm_id"],
  78. msg))
  79. embd_mdl = LLMBundle(tenant["id"], LLMType.EMBEDDING, tenant["embd_id"])
  80. v, c = embd_mdl.encode(["Hello!"])
  81. if c == 0:
  82. logging.error(
  83. "'{}' doesn't work!".format(
  84. tenant["embd_id"]))
  85. def init_llm_factory():
  86. try:
  87. LLMService.filter_delete([(LLM.fid == "MiniMax" or LLM.fid == "Minimax")])
  88. LLMService.filter_delete([(LLM.fid == "cohere")])
  89. LLMFactoriesService.filter_delete([LLMFactories.name == "cohere"])
  90. except Exception:
  91. pass
  92. factory_llm_infos = settings.FACTORY_LLM_INFOS
  93. for factory_llm_info in factory_llm_infos:
  94. info = deepcopy(factory_llm_info)
  95. llm_infos = info.pop("llm")
  96. try:
  97. LLMFactoriesService.save(**info)
  98. except Exception:
  99. pass
  100. LLMService.filter_delete([LLM.fid == factory_llm_info["name"]])
  101. for llm_info in llm_infos:
  102. llm_info["fid"] = factory_llm_info["name"]
  103. try:
  104. LLMService.save(**llm_info)
  105. except Exception:
  106. pass
  107. LLMFactoriesService.filter_delete([(LLMFactories.name == "Local") | (LLMFactories.name == "novita.ai")])
  108. LLMService.filter_delete([LLM.fid == "Local"])
  109. LLMService.filter_delete([LLM.llm_name == "qwen-vl-max"])
  110. LLMService.filter_delete([LLM.fid == "Moonshot", LLM.llm_name == "flag-embedding"])
  111. TenantLLMService.filter_delete([TenantLLM.llm_factory == "Moonshot", TenantLLM.llm_name == "flag-embedding"])
  112. LLMFactoriesService.filter_delete([LLMFactoriesService.model.name == "QAnything"])
  113. LLMService.filter_delete([LLMService.model.fid == "QAnything"])
  114. TenantLLMService.filter_update([TenantLLMService.model.llm_factory == "QAnything"], {"llm_factory": "Youdao"})
  115. TenantLLMService.filter_update([TenantLLMService.model.llm_factory == "cohere"], {"llm_factory": "Cohere"})
  116. TenantService.filter_update([1 == 1], {
  117. "parser_ids": "naive:General,qa:Q&A,resume:Resume,manual:Manual,table:Table,paper:Paper,book:Book,laws:Laws,presentation:Presentation,picture:Picture,one:One,audio:Audio,email:Email,tag:Tag"})
  118. ## insert openai two embedding models to the current openai user.
  119. # print("Start to insert 2 OpenAI embedding models...")
  120. tenant_ids = set([row["tenant_id"] for row in TenantLLMService.get_openai_models()])
  121. for tid in tenant_ids:
  122. for row in TenantLLMService.query(llm_factory="OpenAI", tenant_id=tid):
  123. row = row.to_dict()
  124. row["model_type"] = LLMType.EMBEDDING.value
  125. row["llm_name"] = "text-embedding-3-small"
  126. row["used_tokens"] = 0
  127. try:
  128. TenantLLMService.save(**row)
  129. row = deepcopy(row)
  130. row["llm_name"] = "text-embedding-3-large"
  131. TenantLLMService.save(**row)
  132. except Exception:
  133. pass
  134. break
  135. for kb_id in KnowledgebaseService.get_all_ids():
  136. KnowledgebaseService.update_document_number_in_init(kb_id=kb_id, doc_num=DocumentService.get_kb_doc_count(kb_id))
  137. def add_graph_templates():
  138. dir = os.path.join(get_project_base_directory(), "agent", "templates")
  139. CanvasTemplateService.filter_delete([1 == 1])
  140. if not os.path.exists(dir):
  141. logging.warning("Missing agent templates!")
  142. return
  143. for fnm in os.listdir(dir):
  144. try:
  145. cnvs = json.load(open(os.path.join(dir, fnm), "r",encoding="utf-8"))
  146. try:
  147. CanvasTemplateService.save(**cnvs)
  148. except Exception:
  149. CanvasTemplateService.update_by_id(cnvs["id"], cnvs)
  150. except Exception:
  151. logging.exception("Add agent templates error: ")
  152. def init_web_data():
  153. start_time = time.time()
  154. init_llm_factory()
  155. # if not UserService.get_all().count():
  156. # init_superuser()
  157. add_graph_templates()
  158. logging.info("init web data success:{}".format(time.time() - start_time))
  159. if __name__ == '__main__':
  160. init_web_db()
  161. init_web_data()