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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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.services.user_service import TenantService
  17. from api.settings import database_logger
  18. from rag.llm import EmbeddingModel, CvModel, ChatModel
  19. from api.db import LLMType
  20. from api.db.db_models import DB, UserTenant
  21. from api.db.db_models import LLMFactories, LLM, TenantLLM
  22. from api.db.services.common_service import CommonService
  23. class LLMFactoriesService(CommonService):
  24. model = LLMFactories
  25. class LLMService(CommonService):
  26. model = LLM
  27. class TenantLLMService(CommonService):
  28. model = TenantLLM
  29. @classmethod
  30. @DB.connection_context()
  31. def get_api_key(cls, tenant_id, model_name):
  32. objs = cls.query(tenant_id=tenant_id, llm_name=model_name)
  33. if not objs:
  34. return
  35. return objs[0]
  36. @classmethod
  37. @DB.connection_context()
  38. def get_my_llms(cls, tenant_id):
  39. fields = [
  40. cls.model.llm_factory,
  41. LLMFactories.logo,
  42. LLMFactories.tags,
  43. cls.model.model_type,
  44. cls.model.llm_name,
  45. cls.model.used_tokens
  46. ]
  47. objs = cls.model.select(*fields).join(LLMFactories, on=(cls.model.llm_factory == LLMFactories.name)).where(
  48. cls.model.tenant_id == tenant_id, ~cls.model.api_key.is_null()).dicts()
  49. return list(objs)
  50. @classmethod
  51. @DB.connection_context()
  52. def model_instance(cls, tenant_id, llm_type,
  53. llm_name=None, lang="Chinese"):
  54. e, tenant = TenantService.get_by_id(tenant_id)
  55. if not e:
  56. raise LookupError("Tenant not found")
  57. if llm_type == LLMType.EMBEDDING.value:
  58. mdlnm = tenant.embd_id if not llm_name else llm_name
  59. elif llm_type == LLMType.SPEECH2TEXT.value:
  60. mdlnm = tenant.asr_id
  61. elif llm_type == LLMType.IMAGE2TEXT.value:
  62. mdlnm = tenant.img2txt_id
  63. elif llm_type == LLMType.CHAT.value:
  64. mdlnm = tenant.llm_id if not llm_name else llm_name
  65. else:
  66. assert False, "LLM type error"
  67. model_config = cls.get_api_key(tenant_id, mdlnm)
  68. if model_config: model_config = model_config.to_dict()
  69. if not model_config:
  70. if llm_type == LLMType.EMBEDDING.value:
  71. llm = LLMService.query(llm_name=llm_name)
  72. if llm and llm[0].fid in ["Youdao", "FastEmbed"]:
  73. model_config = {"llm_factory": llm[0].fid, "api_key":"", "llm_name": llm_name, "api_base": ""}
  74. if not model_config:
  75. if llm_name == "flag-embedding":
  76. model_config = {"llm_factory": "Tongyi-Qianwen", "api_key": "",
  77. "llm_name": llm_name, "api_base": ""}
  78. else:
  79. raise LookupError("Model({}) not authorized".format(mdlnm))
  80. if llm_type == LLMType.EMBEDDING.value:
  81. if model_config["llm_factory"] not in EmbeddingModel:
  82. return
  83. return EmbeddingModel[model_config["llm_factory"]](
  84. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  85. if llm_type == LLMType.IMAGE2TEXT.value:
  86. if model_config["llm_factory"] not in CvModel:
  87. return
  88. return CvModel[model_config["llm_factory"]](
  89. model_config["api_key"], model_config["llm_name"], lang,
  90. base_url=model_config["api_base"]
  91. )
  92. if llm_type == LLMType.CHAT.value:
  93. if model_config["llm_factory"] not in ChatModel:
  94. return
  95. return ChatModel[model_config["llm_factory"]](
  96. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  97. @classmethod
  98. @DB.connection_context()
  99. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  100. e, tenant = TenantService.get_by_id(tenant_id)
  101. if not e:
  102. raise LookupError("Tenant not found")
  103. if llm_type == LLMType.EMBEDDING.value:
  104. mdlnm = tenant.embd_id
  105. elif llm_type == LLMType.SPEECH2TEXT.value:
  106. mdlnm = tenant.asr_id
  107. elif llm_type == LLMType.IMAGE2TEXT.value:
  108. mdlnm = tenant.img2txt_id
  109. elif llm_type == LLMType.CHAT.value:
  110. mdlnm = tenant.llm_id if not llm_name else llm_name
  111. else:
  112. assert False, "LLM type error"
  113. num = 0
  114. for u in cls.query(tenant_id = tenant_id, llm_name=mdlnm):
  115. num += cls.model.update(used_tokens = u.used_tokens + used_tokens)\
  116. .where(cls.model.tenant_id == tenant_id, cls.model.llm_name == mdlnm)\
  117. .execute()
  118. return num
  119. class LLMBundle(object):
  120. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese"):
  121. self.tenant_id = tenant_id
  122. self.llm_type = llm_type
  123. self.llm_name = llm_name
  124. self.mdl = TenantLLMService.model_instance(
  125. tenant_id, llm_type, llm_name, lang=lang)
  126. assert self.mdl, "Can't find mole for {}/{}/{}".format(
  127. tenant_id, llm_type, llm_name)
  128. def encode(self, texts: list, batch_size=32):
  129. emd, used_tokens = self.mdl.encode(texts, batch_size)
  130. if not TenantLLMService.increase_usage(
  131. self.tenant_id, self.llm_type, used_tokens):
  132. database_logger.error(
  133. "Can't update token usage for {}/EMBEDDING".format(self.tenant_id))
  134. return emd, used_tokens
  135. def encode_queries(self, query: str):
  136. emd, used_tokens = self.mdl.encode_queries(query)
  137. if not TenantLLMService.increase_usage(
  138. self.tenant_id, self.llm_type, used_tokens):
  139. database_logger.error(
  140. "Can't update token usage for {}/EMBEDDING".format(self.tenant_id))
  141. return emd, used_tokens
  142. def describe(self, image, max_tokens=300):
  143. txt, used_tokens = self.mdl.describe(image, max_tokens)
  144. if not TenantLLMService.increase_usage(
  145. self.tenant_id, self.llm_type, used_tokens):
  146. database_logger.error(
  147. "Can't update token usage for {}/IMAGE2TEXT".format(self.tenant_id))
  148. return txt
  149. def chat(self, system, history, gen_conf):
  150. txt, used_tokens = self.mdl.chat(system, history, gen_conf)
  151. if TenantLLMService.increase_usage(
  152. self.tenant_id, self.llm_type, used_tokens, self.llm_name):
  153. database_logger.error(
  154. "Can't update token usage for {}/CHAT".format(self.tenant_id))
  155. return txt