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.

llm_service.py 11KB

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