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.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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.llm_service import LLMFactoriesService, LLMService, TenantLLMService, LLMBundle
  30. from api.db.services.user_service import TenantService, UserTenantService
  31. from api import settings
  32. from api.utils.file_utils import get_project_base_directory
  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": settings.CHAT_MDL,
  50. "embd_id": settings.EMBEDDING_MDL,
  51. "asr_id": settings.ASR_MDL,
  52. "parser_ids": settings.PARSERS,
  53. "img2txt_id": settings.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=settings.LLM_FACTORY):
  63. tenant_llm.append(
  64. {"tenant_id": user_info["id"], "llm_factory": settings.LLM_FACTORY, "llm_name": llm.llm_name,
  65. "model_type": llm.model_type,
  66. "api_key": settings.API_KEY, "api_base": settings.LLM_BASE_URL})
  67. if not UserService.save(**user_info):
  68. logging.error("can't init admin.")
  69. return
  70. TenantService.insert(**tenant)
  71. UserTenantService.insert(**usr_tenant)
  72. TenantLLMService.insert_many(tenant_llm)
  73. logging.info(
  74. "Super user initialized. email: admin@ragflow.io, password: admin. Changing the password after login is strongly recommended.")
  75. chat_mdl = LLMBundle(tenant["id"], LLMType.CHAT, tenant["llm_id"])
  76. msg = chat_mdl.chat(system="", history=[
  77. {"role": "user", "content": "Hello!"}], gen_conf={})
  78. if msg.find("ERROR: ") == 0:
  79. logging.error(
  80. "'{}' dosen't work. {}".format(
  81. tenant["llm_id"],
  82. msg))
  83. embd_mdl = LLMBundle(tenant["id"], LLMType.EMBEDDING, tenant["embd_id"])
  84. v, c = embd_mdl.encode(["Hello!"])
  85. if c == 0:
  86. logging.error(
  87. "'{}' dosen't work!".format(
  88. tenant["embd_id"]))
  89. def init_llm_factory():
  90. try:
  91. LLMService.filter_delete([(LLM.fid == "MiniMax" or LLM.fid == "Minimax")])
  92. LLMService.filter_delete([(LLM.fid == "cohere")])
  93. LLMFactoriesService.filter_delete([LLMFactories.name == "cohere"])
  94. except Exception:
  95. pass
  96. factory_llm_infos = json.load(
  97. open(
  98. os.path.join(get_project_base_directory(), "conf", "llm_factories.json"),
  99. "r",
  100. )
  101. )
  102. for factory_llm_info in factory_llm_infos["factory_llm_infos"]:
  103. llm_infos = factory_llm_info.pop("llm")
  104. try:
  105. LLMFactoriesService.save(**factory_llm_info)
  106. except Exception:
  107. pass
  108. LLMService.filter_delete([LLM.fid == factory_llm_info["name"]])
  109. for llm_info in llm_infos:
  110. llm_info["fid"] = factory_llm_info["name"]
  111. try:
  112. LLMService.save(**llm_info)
  113. except Exception:
  114. pass
  115. LLMFactoriesService.filter_delete([LLMFactories.name == "Local"])
  116. LLMService.filter_delete([LLM.fid == "Local"])
  117. LLMService.filter_delete([LLM.llm_name == "qwen-vl-max"])
  118. LLMService.filter_delete([LLM.fid == "Moonshot", LLM.llm_name == "flag-embedding"])
  119. TenantLLMService.filter_delete([TenantLLM.llm_factory == "Moonshot", TenantLLM.llm_name == "flag-embedding"])
  120. LLMFactoriesService.filter_delete([LLMFactoriesService.model.name == "QAnything"])
  121. LLMService.filter_delete([LLMService.model.fid == "QAnything"])
  122. TenantLLMService.filter_update([TenantLLMService.model.llm_factory == "QAnything"], {"llm_factory": "Youdao"})
  123. TenantLLMService.filter_update([TenantLLMService.model.llm_factory == "cohere"], {"llm_factory": "Cohere"})
  124. TenantService.filter_update([1 == 1], {
  125. "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"})
  126. ## insert openai two embedding models to the current openai user.
  127. # print("Start to insert 2 OpenAI embedding models...")
  128. tenant_ids = set([row["tenant_id"] for row in TenantLLMService.get_openai_models()])
  129. for tid in tenant_ids:
  130. for row in TenantLLMService.query(llm_factory="OpenAI", tenant_id=tid):
  131. row = row.to_dict()
  132. row["model_type"] = LLMType.EMBEDDING.value
  133. row["llm_name"] = "text-embedding-3-small"
  134. row["used_tokens"] = 0
  135. try:
  136. TenantLLMService.save(**row)
  137. row = deepcopy(row)
  138. row["llm_name"] = "text-embedding-3-large"
  139. TenantLLMService.save(**row)
  140. except Exception:
  141. pass
  142. break
  143. for kb_id in KnowledgebaseService.get_all_ids():
  144. KnowledgebaseService.update_by_id(kb_id, {"doc_num": DocumentService.get_kb_doc_count(kb_id)})
  145. """
  146. drop table llm;
  147. drop table llm_factories;
  148. 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';
  149. alter table knowledgebase modify avatar longtext;
  150. alter table user modify avatar longtext;
  151. alter table dialog modify icon longtext;
  152. """
  153. def add_graph_templates():
  154. dir = os.path.join(get_project_base_directory(), "agent", "templates")
  155. for fnm in os.listdir(dir):
  156. try:
  157. cnvs = json.load(open(os.path.join(dir, fnm), "r"))
  158. try:
  159. CanvasTemplateService.save(**cnvs)
  160. except Exception:
  161. CanvasTemplateService.update_by_id(cnvs["id"], cnvs)
  162. except Exception:
  163. logging.exception("Add graph templates error: ")
  164. def init_web_data():
  165. start_time = time.time()
  166. init_llm_factory()
  167. # if not UserService.get_all().count():
  168. # init_superuser()
  169. add_graph_templates()
  170. logging.info("init web data success:{}".format(time.time() - start_time))
  171. if __name__ == '__main__':
  172. init_web_db()
  173. init_web_data()