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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  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
  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. 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. model_config["api_key"], model_config["llm_name"], lang,
  120. base_url=model_config["api_base"]
  121. )
  122. if llm_type == LLMType.TTS:
  123. if model_config["llm_factory"] not in TTSModel:
  124. return
  125. return TTSModel[model_config["llm_factory"]](
  126. model_config["api_key"],
  127. model_config["llm_name"],
  128. base_url=model_config["api_base"],
  129. )
  130. @classmethod
  131. @DB.connection_context()
  132. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  133. e, tenant = TenantService.get_by_id(tenant_id)
  134. if not e:
  135. raise LookupError("Tenant not found")
  136. if llm_type == LLMType.EMBEDDING.value:
  137. mdlnm = tenant.embd_id
  138. elif llm_type == LLMType.SPEECH2TEXT.value:
  139. mdlnm = tenant.asr_id
  140. elif llm_type == LLMType.IMAGE2TEXT.value:
  141. mdlnm = tenant.img2txt_id
  142. elif llm_type == LLMType.CHAT.value:
  143. mdlnm = tenant.llm_id if not llm_name else llm_name
  144. elif llm_type == LLMType.RERANK:
  145. mdlnm = tenant.rerank_id if not llm_name else llm_name
  146. elif llm_type == LLMType.TTS:
  147. mdlnm = tenant.tts_id if not llm_name else llm_name
  148. else:
  149. assert False, "LLM type error"
  150. num = 0
  151. try:
  152. for u in cls.query(tenant_id=tenant_id, llm_name=mdlnm):
  153. num += cls.model.update(used_tokens=u.used_tokens + used_tokens)\
  154. .where(cls.model.tenant_id == tenant_id, cls.model.llm_name == mdlnm)\
  155. .execute()
  156. except Exception as e:
  157. pass
  158. return num
  159. @classmethod
  160. @DB.connection_context()
  161. def get_openai_models(cls):
  162. objs = cls.model.select().where(
  163. (cls.model.llm_factory == "OpenAI"),
  164. ~(cls.model.llm_name == "text-embedding-3-small"),
  165. ~(cls.model.llm_name == "text-embedding-3-large")
  166. ).dicts()
  167. return list(objs)
  168. class LLMBundle(object):
  169. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese"):
  170. self.tenant_id = tenant_id
  171. self.llm_type = llm_type
  172. self.llm_name = llm_name
  173. self.mdl = TenantLLMService.model_instance(
  174. tenant_id, llm_type, llm_name, lang=lang)
  175. assert self.mdl, "Can't find mole for {}/{}/{}".format(
  176. tenant_id, llm_type, llm_name)
  177. self.max_length = 8192
  178. for lm in LLMService.query(llm_name=llm_name):
  179. self.max_length = lm.max_tokens
  180. break
  181. def encode(self, texts: list, batch_size=32):
  182. emd, used_tokens = self.mdl.encode(texts, batch_size)
  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 encode_queries(self, query: str):
  189. emd, used_tokens = self.mdl.encode_queries(query)
  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 {}/EMBEDDING".format(self.tenant_id))
  194. return emd, used_tokens
  195. def similarity(self, query: str, texts: list):
  196. sim, used_tokens = self.mdl.similarity(query, texts)
  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 {}/RERANK".format(self.tenant_id))
  201. return sim, used_tokens
  202. def describe(self, image, max_tokens=300):
  203. txt, used_tokens = self.mdl.describe(image, max_tokens)
  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 {}/IMAGE2TEXT".format(self.tenant_id))
  208. return txt
  209. def transcription(self, audio):
  210. txt, used_tokens = self.mdl.transcription(audio)
  211. if not TenantLLMService.increase_usage(
  212. self.tenant_id, self.llm_type, used_tokens):
  213. database_logger.error(
  214. "Can't update token usage for {}/SEQUENCE2TXT".format(self.tenant_id))
  215. return txt
  216. def tts(self, text):
  217. for chunk in self.mdl.tts(text):
  218. if isinstance(chunk,int):
  219. if not TenantLLMService.increase_usage(
  220. self.tenant_id, self.llm_type, chunk, self.llm_name):
  221. database_logger.error(
  222. "Can't update token usage for {}/TTS".format(self.tenant_id))
  223. return
  224. yield chunk
  225. def chat(self, system, history, gen_conf):
  226. txt, used_tokens = self.mdl.chat(system, history, gen_conf)
  227. if not TenantLLMService.increase_usage(
  228. self.tenant_id, self.llm_type, used_tokens, self.llm_name):
  229. database_logger.error(
  230. "Can't update token usage for {}/CHAT".format(self.tenant_id))
  231. return txt
  232. def chat_streamly(self, system, history, gen_conf):
  233. for txt in self.mdl.chat_streamly(system, history, gen_conf):
  234. if isinstance(txt, int):
  235. if not TenantLLMService.increase_usage(
  236. self.tenant_id, self.llm_type, txt, self.llm_name):
  237. database_logger.error(
  238. "Can't update token usage for {}/CHAT".format(self.tenant_id))
  239. return
  240. yield txt