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.

init_data.py 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 json
  17. import os
  18. import time
  19. import uuid
  20. from copy import deepcopy
  21. from api.db import LLMType, UserTenantRole
  22. from api.db.db_models import init_database_tables as init_web_db, LLMFactories, LLM, TenantLLM
  23. from api.db.services import UserService
  24. from api.db.services.canvas_service import CanvasTemplateService
  25. from api.db.services.document_service import DocumentService
  26. from api.db.services.knowledgebase_service import KnowledgebaseService
  27. from api.db.services.llm_service import LLMFactoriesService, LLMService, TenantLLMService, LLMBundle
  28. from api.db.services.user_service import TenantService, UserTenantService
  29. from api.settings import CHAT_MDL, EMBEDDING_MDL, ASR_MDL, IMAGE2TEXT_MDL, PARSERS, LLM_FACTORY, API_KEY, LLM_BASE_URL
  30. from api.utils.file_utils import get_project_base_directory
  31. def init_superuser():
  32. user_info = {
  33. "id": uuid.uuid1().hex,
  34. "password": "admin",
  35. "nickname": "admin",
  36. "is_superuser": True,
  37. "email": "admin@ragflow.io",
  38. "creator": "system",
  39. "status": "1",
  40. }
  41. tenant = {
  42. "id": user_info["id"],
  43. "name": user_info["nickname"] + "‘s Kingdom",
  44. "llm_id": CHAT_MDL,
  45. "embd_id": EMBEDDING_MDL,
  46. "asr_id": ASR_MDL,
  47. "parser_ids": PARSERS,
  48. "img2txt_id": IMAGE2TEXT_MDL
  49. }
  50. usr_tenant = {
  51. "tenant_id": user_info["id"],
  52. "user_id": user_info["id"],
  53. "invited_by": user_info["id"],
  54. "role": UserTenantRole.OWNER
  55. }
  56. tenant_llm = []
  57. for llm in LLMService.query(fid=LLM_FACTORY):
  58. tenant_llm.append(
  59. {"tenant_id": user_info["id"], "llm_factory": LLM_FACTORY, "llm_name": llm.llm_name, "model_type": llm.model_type,
  60. "api_key": API_KEY, "api_base": LLM_BASE_URL})
  61. if not UserService.save(**user_info):
  62. print("\033[93m【ERROR】\033[0mcan't init admin.")
  63. return
  64. TenantService.insert(**tenant)
  65. UserTenantService.insert(**usr_tenant)
  66. TenantLLMService.insert_many(tenant_llm)
  67. print(
  68. "【INFO】Super user initialized. \033[93memail: admin@ragflow.io, password: admin\033[0m. Changing the password after logining is strongly recomanded.")
  69. chat_mdl = LLMBundle(tenant["id"], LLMType.CHAT, tenant["llm_id"])
  70. msg = chat_mdl.chat(system="", history=[
  71. {"role": "user", "content": "Hello!"}], gen_conf={})
  72. if msg.find("ERROR: ") == 0:
  73. print(
  74. "\33[91m【ERROR】\33[0m: ",
  75. "'{}' dosen't work. {}".format(
  76. tenant["llm_id"],
  77. msg))
  78. embd_mdl = LLMBundle(tenant["id"], LLMType.EMBEDDING, tenant["embd_id"])
  79. v, c = embd_mdl.encode(["Hello!"])
  80. if c == 0:
  81. print(
  82. "\33[91m【ERROR】\33[0m:",
  83. " '{}' dosen'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. except Exception as e:
  89. pass
  90. factory_llm_infos = json.load(
  91. open(
  92. os.path.join(get_project_base_directory(), "conf", "llm_factories.json"),
  93. "r",
  94. )
  95. )
  96. for factory_llm_info in factory_llm_infos["factory_llm_infos"]:
  97. llm_infos = factory_llm_info.pop("llm")
  98. try:
  99. LLMFactoriesService.save(**factory_llm_info)
  100. except Exception as e:
  101. pass
  102. for llm_info in llm_infos:
  103. llm_info["fid"] = factory_llm_info["name"]
  104. try:
  105. LLMService.save(**llm_info)
  106. except Exception as e:
  107. pass
  108. LLMFactoriesService.filter_delete([LLMFactories.name == "Local"])
  109. LLMService.filter_delete([LLM.fid == "Local"])
  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. TenantService.filter_update([1 == 1], {
  116. "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,knowledge_graph:Knowledge Graph"})
  117. ## insert openai two embedding models to the current openai user.
  118. print("Start to insert 2 OpenAI embedding models...")
  119. tenant_ids = set([row["tenant_id"] for row in TenantLLMService.get_openai_models()])
  120. for tid in tenant_ids:
  121. for row in TenantLLMService.query(llm_factory="OpenAI", tenant_id=tid):
  122. row = row.to_dict()
  123. row["model_type"] = LLMType.EMBEDDING.value
  124. row["llm_name"] = "text-embedding-3-small"
  125. row["used_tokens"] = 0
  126. try:
  127. TenantLLMService.save(**row)
  128. row = deepcopy(row)
  129. row["llm_name"] = "text-embedding-3-large"
  130. TenantLLMService.save(**row)
  131. except Exception as e:
  132. pass
  133. break
  134. for kb_id in KnowledgebaseService.get_all_ids():
  135. KnowledgebaseService.update_by_id(kb_id, {"doc_num": DocumentService.get_kb_doc_count(kb_id)})
  136. """
  137. drop table llm;
  138. drop table llm_factories;
  139. update tenant set 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,knowledge_graph:Knowledge Graph';
  140. alter table knowledgebase modify avatar longtext;
  141. alter table user modify avatar longtext;
  142. alter table dialog modify icon longtext;
  143. """
  144. def add_graph_templates():
  145. dir = os.path.join(get_project_base_directory(), "agent", "templates")
  146. for fnm in os.listdir(dir):
  147. try:
  148. cnvs = json.load(open(os.path.join(dir, fnm), "r"))
  149. try:
  150. CanvasTemplateService.save(**cnvs)
  151. except:
  152. CanvasTemplateService.update_by_id(cnvs["id"], cnvs)
  153. except Exception as e:
  154. print("Add graph templates error: ", e)
  155. print("------------", flush=True)
  156. def init_web_data():
  157. start_time = time.time()
  158. init_llm_factory()
  159. if not UserService.get_all().count():
  160. init_superuser()
  161. add_graph_templates()
  162. print("init web data success:{}".format(time.time() - start_time))
  163. if __name__ == '__main__':
  164. init_web_db()
  165. init_web_data()