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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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 rag.llm import EmbeddingModel, CvModel, ChatModel, RerankModel, Seq2txtModel, TTSModel
  18. from api.db import LLMType
  19. from api.db.db_models import DB
  20. from api.db.db_models import LLMFactories, LLM, TenantLLM
  21. from api.db.services.common_service import CommonService
  22. from api.utils.log_utils import logger
  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. arr = model_name.split("@")
  33. if len(arr) < 2:
  34. objs = cls.query(tenant_id=tenant_id, llm_name=model_name)
  35. else:
  36. objs = cls.query(tenant_id=tenant_id, llm_name=arr[0], llm_factory=arr[1])
  37. if not objs:
  38. return
  39. return objs[0]
  40. @classmethod
  41. @DB.connection_context()
  42. def get_my_llms(cls, tenant_id):
  43. fields = [
  44. cls.model.llm_factory,
  45. LLMFactories.logo,
  46. LLMFactories.tags,
  47. cls.model.model_type,
  48. cls.model.llm_name,
  49. cls.model.used_tokens
  50. ]
  51. objs = cls.model.select(*fields).join(LLMFactories, on=(cls.model.llm_factory == LLMFactories.name)).where(
  52. cls.model.tenant_id == tenant_id, ~cls.model.api_key.is_null()).dicts()
  53. return list(objs)
  54. @classmethod
  55. @DB.connection_context()
  56. def model_instance(cls, tenant_id, llm_type,
  57. llm_name=None, lang="Chinese"):
  58. e, tenant = TenantService.get_by_id(tenant_id)
  59. if not e:
  60. raise LookupError("Tenant not found")
  61. if llm_type == LLMType.EMBEDDING.value:
  62. mdlnm = tenant.embd_id if not llm_name else llm_name
  63. elif llm_type == LLMType.SPEECH2TEXT.value:
  64. mdlnm = tenant.asr_id
  65. elif llm_type == LLMType.IMAGE2TEXT.value:
  66. mdlnm = tenant.img2txt_id if not llm_name else llm_name
  67. elif llm_type == LLMType.CHAT.value:
  68. mdlnm = tenant.llm_id if not llm_name else llm_name
  69. elif llm_type == LLMType.RERANK:
  70. mdlnm = tenant.rerank_id if not llm_name else llm_name
  71. elif llm_type == LLMType.TTS:
  72. mdlnm = tenant.tts_id if not llm_name else llm_name
  73. else:
  74. assert False, "LLM type error"
  75. model_config = cls.get_api_key(tenant_id, mdlnm)
  76. tmp = mdlnm.split("@")
  77. fid = None if len(tmp) < 2 else tmp[1]
  78. mdlnm = tmp[0]
  79. if model_config: model_config = model_config.to_dict()
  80. if not model_config:
  81. if llm_type in [LLMType.EMBEDDING, LLMType.RERANK]:
  82. llm = LLMService.query(llm_name=mdlnm) if not fid else LLMService.query(llm_name=mdlnm, fid=fid)
  83. if llm and llm[0].fid in ["Youdao", "FastEmbed", "BAAI"]:
  84. model_config = {"llm_factory": llm[0].fid, "api_key":"", "llm_name": mdlnm, "api_base": ""}
  85. if not model_config:
  86. if mdlnm == "flag-embedding":
  87. model_config = {"llm_factory": "Tongyi-Qianwen", "api_key": "",
  88. "llm_name": llm_name, "api_base": ""}
  89. else:
  90. if not mdlnm:
  91. raise LookupError(f"Type of {llm_type} model is not set.")
  92. raise LookupError("Model({}) not authorized".format(mdlnm))
  93. if llm_type == LLMType.EMBEDDING.value:
  94. if model_config["llm_factory"] not in EmbeddingModel:
  95. return
  96. return EmbeddingModel[model_config["llm_factory"]](
  97. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  98. if llm_type == LLMType.RERANK:
  99. if model_config["llm_factory"] not in RerankModel:
  100. return
  101. return RerankModel[model_config["llm_factory"]](
  102. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  103. if llm_type == LLMType.IMAGE2TEXT.value:
  104. if model_config["llm_factory"] not in CvModel:
  105. return
  106. return CvModel[model_config["llm_factory"]](
  107. model_config["api_key"], model_config["llm_name"], lang,
  108. base_url=model_config["api_base"]
  109. )
  110. if llm_type == LLMType.CHAT.value:
  111. if model_config["llm_factory"] not in ChatModel:
  112. return
  113. return ChatModel[model_config["llm_factory"]](
  114. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  115. if llm_type == LLMType.SPEECH2TEXT:
  116. if model_config["llm_factory"] not in Seq2txtModel:
  117. return
  118. return Seq2txtModel[model_config["llm_factory"]](
  119. key=model_config["api_key"], model_name=model_config["llm_name"],
  120. lang=lang,
  121. base_url=model_config["api_base"]
  122. )
  123. if llm_type == LLMType.TTS:
  124. if model_config["llm_factory"] not in TTSModel:
  125. return
  126. return TTSModel[model_config["llm_factory"]](
  127. model_config["api_key"],
  128. model_config["llm_name"],
  129. base_url=model_config["api_base"],
  130. )
  131. @classmethod
  132. @DB.connection_context()
  133. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  134. e, tenant = TenantService.get_by_id(tenant_id)
  135. if not e:
  136. raise LookupError("Tenant not found")
  137. if llm_type == LLMType.EMBEDDING.value:
  138. mdlnm = tenant.embd_id
  139. elif llm_type == LLMType.SPEECH2TEXT.value:
  140. mdlnm = tenant.asr_id
  141. elif llm_type == LLMType.IMAGE2TEXT.value:
  142. mdlnm = tenant.img2txt_id
  143. elif llm_type == LLMType.CHAT.value:
  144. mdlnm = tenant.llm_id if not llm_name else llm_name
  145. elif llm_type == LLMType.RERANK:
  146. mdlnm = tenant.rerank_id if not llm_name else llm_name
  147. elif llm_type == LLMType.TTS:
  148. mdlnm = tenant.tts_id if not llm_name else llm_name
  149. else:
  150. assert False, "LLM type error"
  151. llm_name = mdlnm.split("@")[0] if "@" in mdlnm else mdlnm
  152. num = 0
  153. try:
  154. for u in cls.query(tenant_id=tenant_id, llm_name=llm_name):
  155. num += cls.model.update(used_tokens=u.used_tokens + used_tokens)\
  156. .where(cls.model.tenant_id == tenant_id, cls.model.llm_name == llm_name)\
  157. .execute()
  158. except Exception as e:
  159. pass
  160. return num
  161. @classmethod
  162. @DB.connection_context()
  163. def get_openai_models(cls):
  164. objs = cls.model.select().where(
  165. (cls.model.llm_factory == "OpenAI"),
  166. ~(cls.model.llm_name == "text-embedding-3-small"),
  167. ~(cls.model.llm_name == "text-embedding-3-large")
  168. ).dicts()
  169. return list(objs)
  170. class LLMBundle(object):
  171. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese"):
  172. self.tenant_id = tenant_id
  173. self.llm_type = llm_type
  174. self.llm_name = llm_name
  175. self.mdl = TenantLLMService.model_instance(
  176. tenant_id, llm_type, llm_name, lang=lang)
  177. assert self.mdl, "Can't find model for {}/{}/{}".format(
  178. tenant_id, llm_type, llm_name)
  179. self.max_length = 8192
  180. for lm in LLMService.query(llm_name=llm_name):
  181. self.max_length = lm.max_tokens
  182. break
  183. def encode(self, texts: list, batch_size=32):
  184. emd, used_tokens = self.mdl.encode(texts, batch_size)
  185. if not TenantLLMService.increase_usage(
  186. self.tenant_id, self.llm_type, used_tokens):
  187. logger.error(
  188. "LLMBundle.encode can't update token usage for {}/EMBEDDING used_tokens: {}".format(self.tenant_id, used_tokens))
  189. return emd, used_tokens
  190. def encode_queries(self, query: str):
  191. emd, used_tokens = self.mdl.encode_queries(query)
  192. if not TenantLLMService.increase_usage(
  193. self.tenant_id, self.llm_type, used_tokens):
  194. logger.error(
  195. "LLMBundle.encode_queries can't update token usage for {}/EMBEDDING used_tokens: {}".format(self.tenant_id, used_tokens))
  196. return emd, used_tokens
  197. def similarity(self, query: str, texts: list):
  198. sim, used_tokens = self.mdl.similarity(query, texts)
  199. if not TenantLLMService.increase_usage(
  200. self.tenant_id, self.llm_type, used_tokens):
  201. logger.error(
  202. "LLMBundle.similarity can't update token usage for {}/RERANK used_tokens: {}".format(self.tenant_id, used_tokens))
  203. return sim, used_tokens
  204. def describe(self, image, max_tokens=300):
  205. txt, used_tokens = self.mdl.describe(image, max_tokens)
  206. if not TenantLLMService.increase_usage(
  207. self.tenant_id, self.llm_type, used_tokens):
  208. logger.error(
  209. "LLMBundle.describe can't update token usage for {}/IMAGE2TEXT used_tokens: {}".format(self.tenant_id, used_tokens))
  210. return txt
  211. def transcription(self, audio):
  212. txt, used_tokens = self.mdl.transcription(audio)
  213. if not TenantLLMService.increase_usage(
  214. self.tenant_id, self.llm_type, used_tokens):
  215. logger.error(
  216. "LLMBundle.transcription can't update token usage for {}/SEQUENCE2TXT used_tokens: {}".format(self.tenant_id, used_tokens))
  217. return txt
  218. def tts(self, text):
  219. for chunk in self.mdl.tts(text):
  220. if isinstance(chunk,int):
  221. if not TenantLLMService.increase_usage(
  222. self.tenant_id, self.llm_type, chunk, self.llm_name):
  223. logger.error(
  224. "LLMBundle.tts can't update token usage for {}/TTS".format(self.tenant_id))
  225. return
  226. yield chunk
  227. def chat(self, system, history, gen_conf):
  228. txt, used_tokens = self.mdl.chat(system, history, gen_conf)
  229. if isinstance(txt, int) and not TenantLLMService.increase_usage(
  230. self.tenant_id, self.llm_type, used_tokens, self.llm_name):
  231. logger.error(
  232. "LLMBundle.chat can't update token usage for {}/CHAT llm_name: {}, used_tokens: {}".format(self.tenant_id, self.llm_name, used_tokens))
  233. return txt
  234. def chat_streamly(self, system, history, gen_conf):
  235. for txt in self.mdl.chat_streamly(system, history, gen_conf):
  236. if isinstance(txt, int):
  237. if not TenantLLMService.increase_usage(
  238. self.tenant_id, self.llm_type, txt, self.llm_name):
  239. logger.error(
  240. "LLMBundle.chat_streamly can't update token usage for {}/CHAT llm_name: {}, content: {}".format(self.tenant_id, self.llm_name, txt))
  241. return
  242. yield txt