Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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