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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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, RerankModel, Seq2txtModel
  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 if not llm_name else llm_name
  63. elif llm_type == LLMType.CHAT.value:
  64. mdlnm = tenant.llm_id if not llm_name else llm_name
  65. elif llm_type == LLMType.RERANK:
  66. mdlnm = tenant.rerank_id if not llm_name else llm_name
  67. else:
  68. assert False, "LLM type error"
  69. model_config = cls.get_api_key(tenant_id, mdlnm)
  70. if model_config: model_config = model_config.to_dict()
  71. if not model_config:
  72. if llm_type in [LLMType.EMBEDDING, LLMType.RERANK]:
  73. llm = LLMService.query(llm_name=llm_name if llm_name else mdlnm)
  74. if llm and llm[0].fid in ["Youdao", "FastEmbed", "BAAI"]:
  75. model_config = {"llm_factory": llm[0].fid, "api_key":"", "llm_name": llm_name if llm_name else mdlnm, "api_base": ""}
  76. if not model_config:
  77. if llm_name == "flag-embedding":
  78. model_config = {"llm_factory": "Tongyi-Qianwen", "api_key": "",
  79. "llm_name": llm_name, "api_base": ""}
  80. else:
  81. if not mdlnm:
  82. raise LookupError(f"Type of {llm_type} model is not set.")
  83. raise LookupError("Model({}) not authorized".format(mdlnm))
  84. if llm_type == LLMType.EMBEDDING.value:
  85. if model_config["llm_factory"] not in EmbeddingModel:
  86. return
  87. return EmbeddingModel[model_config["llm_factory"]](
  88. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  89. if llm_type == LLMType.RERANK:
  90. if model_config["llm_factory"] not in RerankModel:
  91. return
  92. return RerankModel[model_config["llm_factory"]](
  93. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  94. if llm_type == LLMType.IMAGE2TEXT.value:
  95. if model_config["llm_factory"] not in CvModel:
  96. return
  97. return CvModel[model_config["llm_factory"]](
  98. model_config["api_key"], model_config["llm_name"], lang,
  99. base_url=model_config["api_base"]
  100. )
  101. if llm_type == LLMType.CHAT.value:
  102. if model_config["llm_factory"] not in ChatModel:
  103. return
  104. return ChatModel[model_config["llm_factory"]](
  105. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  106. if llm_type == LLMType.SPEECH2TEXT:
  107. if model_config["llm_factory"] not in Seq2txtModel:
  108. return
  109. return Seq2txtModel[model_config["llm_factory"]](
  110. model_config["api_key"], model_config["llm_name"], lang,
  111. base_url=model_config["api_base"]
  112. )
  113. @classmethod
  114. @DB.connection_context()
  115. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  116. e, tenant = TenantService.get_by_id(tenant_id)
  117. if not e:
  118. raise LookupError("Tenant not found")
  119. if llm_type == LLMType.EMBEDDING.value:
  120. mdlnm = tenant.embd_id
  121. elif llm_type == LLMType.SPEECH2TEXT.value:
  122. mdlnm = tenant.asr_id
  123. elif llm_type == LLMType.IMAGE2TEXT.value:
  124. mdlnm = tenant.img2txt_id
  125. elif llm_type == LLMType.CHAT.value:
  126. mdlnm = tenant.llm_id if not llm_name else llm_name
  127. elif llm_type == LLMType.RERANK:
  128. mdlnm = tenant.llm_id if not llm_name else llm_name
  129. else:
  130. assert False, "LLM type error"
  131. num = 0
  132. try:
  133. for u in cls.query(tenant_id = tenant_id, llm_name=mdlnm):
  134. num += cls.model.update(used_tokens = u.used_tokens + used_tokens)\
  135. .where(cls.model.tenant_id == tenant_id, cls.model.llm_name == mdlnm)\
  136. .execute()
  137. except Exception as e:
  138. pass
  139. return num
  140. @classmethod
  141. @DB.connection_context()
  142. def get_openai_models(cls):
  143. objs = cls.model.select().where(
  144. (cls.model.llm_factory == "OpenAI"),
  145. ~(cls.model.llm_name == "text-embedding-3-small"),
  146. ~(cls.model.llm_name == "text-embedding-3-large")
  147. ).dicts()
  148. return list(objs)
  149. class LLMBundle(object):
  150. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese"):
  151. self.tenant_id = tenant_id
  152. self.llm_type = llm_type
  153. self.llm_name = llm_name
  154. self.mdl = TenantLLMService.model_instance(
  155. tenant_id, llm_type, llm_name, lang=lang)
  156. assert self.mdl, "Can't find mole for {}/{}/{}".format(
  157. tenant_id, llm_type, llm_name)
  158. self.max_length = 512
  159. for lm in LLMService.query(llm_name=llm_name):
  160. self.max_length = lm.max_tokens
  161. break
  162. def encode(self, texts: list, batch_size=32):
  163. emd, used_tokens = self.mdl.encode(texts, batch_size)
  164. if not TenantLLMService.increase_usage(
  165. self.tenant_id, self.llm_type, used_tokens):
  166. database_logger.error(
  167. "Can't update token usage for {}/EMBEDDING".format(self.tenant_id))
  168. return emd, used_tokens
  169. def encode_queries(self, query: str):
  170. emd, used_tokens = self.mdl.encode_queries(query)
  171. if not TenantLLMService.increase_usage(
  172. self.tenant_id, self.llm_type, used_tokens):
  173. database_logger.error(
  174. "Can't update token usage for {}/EMBEDDING".format(self.tenant_id))
  175. return emd, used_tokens
  176. def similarity(self, query: str, texts: list):
  177. sim, used_tokens = self.mdl.similarity(query, texts)
  178. if not TenantLLMService.increase_usage(
  179. self.tenant_id, self.llm_type, used_tokens):
  180. database_logger.error(
  181. "Can't update token usage for {}/RERANK".format(self.tenant_id))
  182. return sim, used_tokens
  183. def describe(self, image, max_tokens=300):
  184. txt, used_tokens = self.mdl.describe(image, max_tokens)
  185. if not TenantLLMService.increase_usage(
  186. self.tenant_id, self.llm_type, used_tokens):
  187. database_logger.error(
  188. "Can't update token usage for {}/IMAGE2TEXT".format(self.tenant_id))
  189. return txt
  190. def transcription(self, audio):
  191. txt, used_tokens = self.mdl.transcription(audio)
  192. if not TenantLLMService.increase_usage(
  193. self.tenant_id, self.llm_type, used_tokens):
  194. database_logger.error(
  195. "Can't update token usage for {}/SEQUENCE2TXT".format(self.tenant_id))
  196. return txt
  197. def chat(self, system, history, gen_conf):
  198. txt, used_tokens = self.mdl.chat(system, history, gen_conf)
  199. if not TenantLLMService.increase_usage(
  200. self.tenant_id, self.llm_type, used_tokens, self.llm_name):
  201. database_logger.error(
  202. "Can't update token usage for {}/CHAT".format(self.tenant_id))
  203. return txt
  204. def chat_streamly(self, system, history, gen_conf):
  205. for txt in self.mdl.chat_streamly(system, history, gen_conf):
  206. if isinstance(txt, int):
  207. if not TenantLLMService.increase_usage(
  208. self.tenant_id, self.llm_type, txt, self.llm_name):
  209. database_logger.error(
  210. "Can't update token usage for {}/CHAT".format(self.tenant_id))
  211. return
  212. yield txt