您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

llm_service.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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. llm_name = mdlnm.split("@")[0] if "@" in mdlnm else mdlnm
  151. num = 0
  152. try:
  153. for u in cls.query(tenant_id=tenant_id, llm_name=llm_name):
  154. num += cls.model.update(used_tokens=u.used_tokens + used_tokens)\
  155. .where(cls.model.tenant_id == tenant_id, cls.model.llm_name == llm_name)\
  156. .execute()
  157. except Exception as e:
  158. pass
  159. return num
  160. @classmethod
  161. @DB.connection_context()
  162. def get_openai_models(cls):
  163. objs = cls.model.select().where(
  164. (cls.model.llm_factory == "OpenAI"),
  165. ~(cls.model.llm_name == "text-embedding-3-small"),
  166. ~(cls.model.llm_name == "text-embedding-3-large")
  167. ).dicts()
  168. return list(objs)
  169. class LLMBundle(object):
  170. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese"):
  171. self.tenant_id = tenant_id
  172. self.llm_type = llm_type
  173. self.llm_name = llm_name
  174. self.mdl = TenantLLMService.model_instance(
  175. tenant_id, llm_type, llm_name, lang=lang)
  176. assert self.mdl, "Can't find model for {}/{}/{}".format(
  177. tenant_id, llm_type, llm_name)
  178. self.max_length = 8192
  179. for lm in LLMService.query(llm_name=llm_name):
  180. self.max_length = lm.max_tokens
  181. break
  182. def encode(self, texts: list, batch_size=32):
  183. emd, used_tokens = self.mdl.encode(texts, batch_size)
  184. if not TenantLLMService.increase_usage(
  185. self.tenant_id, self.llm_type, used_tokens):
  186. database_logger.error(
  187. "Can't update token usage for {}/EMBEDDING used_tokens: {}".format(self.tenant_id, used_tokens))
  188. return emd, used_tokens
  189. def encode_queries(self, query: str):
  190. emd, used_tokens = self.mdl.encode_queries(query)
  191. if not TenantLLMService.increase_usage(
  192. self.tenant_id, self.llm_type, used_tokens):
  193. database_logger.error(
  194. "Can't update token usage for {}/EMBEDDING used_tokens: {}".format(self.tenant_id, used_tokens))
  195. return emd, used_tokens
  196. def similarity(self, query: str, texts: list):
  197. sim, used_tokens = self.mdl.similarity(query, texts)
  198. if not TenantLLMService.increase_usage(
  199. self.tenant_id, self.llm_type, used_tokens):
  200. database_logger.error(
  201. "Can't update token usage for {}/RERANK used_tokens: {}".format(self.tenant_id, used_tokens))
  202. return sim, used_tokens
  203. def describe(self, image, max_tokens=300):
  204. txt, used_tokens = self.mdl.describe(image, max_tokens)
  205. if not TenantLLMService.increase_usage(
  206. self.tenant_id, self.llm_type, used_tokens):
  207. database_logger.error(
  208. "Can't update token usage for {}/IMAGE2TEXT used_tokens: {}".format(self.tenant_id, used_tokens))
  209. return txt
  210. def transcription(self, audio):
  211. txt, used_tokens = self.mdl.transcription(audio)
  212. if not TenantLLMService.increase_usage(
  213. self.tenant_id, self.llm_type, used_tokens):
  214. database_logger.error(
  215. "Can't update token usage for {}/SEQUENCE2TXT used_tokens: {}".format(self.tenant_id, used_tokens))
  216. return txt
  217. def tts(self, text):
  218. for chunk in self.mdl.tts(text):
  219. if isinstance(chunk,int):
  220. if not TenantLLMService.increase_usage(
  221. self.tenant_id, self.llm_type, chunk, self.llm_name):
  222. database_logger.error(
  223. "Can't update token usage for {}/TTS".format(self.tenant_id))
  224. return
  225. yield chunk
  226. def chat(self, system, history, gen_conf):
  227. txt, used_tokens = self.mdl.chat(system, history, gen_conf)
  228. if isinstance(txt, int) and not TenantLLMService.increase_usage(
  229. self.tenant_id, self.llm_type, used_tokens, self.llm_name):
  230. database_logger.error(
  231. "Can't update token usage for {}/CHAT llm_name: {}, used_tokens: {}".format(self.tenant_id, self.llm_name, used_tokens))
  232. return txt
  233. def chat_streamly(self, system, history, gen_conf):
  234. for txt in self.mdl.chat_streamly(system, history, gen_conf):
  235. if isinstance(txt, int):
  236. if not TenantLLMService.increase_usage(
  237. self.tenant_id, self.llm_type, txt, self.llm_name):
  238. database_logger.error(
  239. "Can't update token usage for {}/CHAT llm_name: {}, content: {}".format(self.tenant_id, self.llm_name, txt))
  240. return
  241. yield txt