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

llm_service.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. import logging
  17. from api import settings
  18. from api.db import LLMType
  19. from api.db.db_models import DB, LLM, LLMFactories, TenantLLM
  20. from api.db.services.common_service import CommonService
  21. from api.db.services.user_service import TenantService
  22. from rag.llm import ChatModel, CvModel, EmbeddingModel, RerankModel, Seq2txtModel, TTSModel
  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. mdlnm, fid = TenantLLMService.split_model_name_and_factory(model_name)
  33. if not fid:
  34. objs = cls.query(tenant_id=tenant_id, llm_name=mdlnm)
  35. else:
  36. objs = cls.query(tenant_id=tenant_id, llm_name=mdlnm, llm_factory=fid)
  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. @staticmethod
  55. def split_model_name_and_factory(model_name):
  56. arr = model_name.split("@")
  57. if len(arr) < 2:
  58. return model_name, None
  59. if len(arr) > 2:
  60. return "@".join(arr[0:-1]), arr[-1]
  61. # model name must be xxx@yyy
  62. try:
  63. model_factories = settings.FACTORY_LLM_INFOS
  64. model_providers = set([f["name"] for f in model_factories])
  65. if arr[-1] not in model_providers:
  66. return model_name, None
  67. return arr[0], arr[-1]
  68. except Exception as e:
  69. logging.exception(f"TenantLLMService.split_model_name_and_factory got exception: {e}")
  70. return model_name, None
  71. @classmethod
  72. @DB.connection_context()
  73. def get_model_config(cls, tenant_id, llm_type, llm_name=None):
  74. e, tenant = TenantService.get_by_id(tenant_id)
  75. if not e:
  76. raise LookupError("Tenant not found")
  77. if llm_type == LLMType.EMBEDDING.value:
  78. mdlnm = tenant.embd_id if not llm_name else llm_name
  79. elif llm_type == LLMType.SPEECH2TEXT.value:
  80. mdlnm = tenant.asr_id
  81. elif llm_type == LLMType.IMAGE2TEXT.value:
  82. mdlnm = tenant.img2txt_id if not llm_name else llm_name
  83. elif llm_type == LLMType.CHAT.value:
  84. mdlnm = tenant.llm_id if not llm_name else llm_name
  85. elif llm_type == LLMType.RERANK:
  86. mdlnm = tenant.rerank_id if not llm_name else llm_name
  87. elif llm_type == LLMType.TTS:
  88. mdlnm = tenant.tts_id if not llm_name else llm_name
  89. else:
  90. assert False, "LLM type error"
  91. model_config = cls.get_api_key(tenant_id, mdlnm)
  92. mdlnm, fid = TenantLLMService.split_model_name_and_factory(mdlnm)
  93. if model_config:
  94. model_config = model_config.to_dict()
  95. if not model_config:
  96. if llm_type in [LLMType.EMBEDDING, LLMType.RERANK]:
  97. llm = LLMService.query(llm_name=mdlnm) if not fid else LLMService.query(llm_name=mdlnm, fid=fid)
  98. if llm and llm[0].fid in ["Youdao", "FastEmbed", "BAAI"]:
  99. model_config = {"llm_factory": llm[0].fid, "api_key": "", "llm_name": mdlnm, "api_base": ""}
  100. if not model_config:
  101. if mdlnm == "flag-embedding":
  102. model_config = {"llm_factory": "Tongyi-Qianwen", "api_key": "",
  103. "llm_name": llm_name, "api_base": ""}
  104. else:
  105. if not mdlnm:
  106. raise LookupError(f"Type of {llm_type} model is not set.")
  107. raise LookupError("Model({}) not authorized".format(mdlnm))
  108. return model_config
  109. @classmethod
  110. @DB.connection_context()
  111. def model_instance(cls, tenant_id, llm_type,
  112. llm_name=None, lang="Chinese"):
  113. model_config = TenantLLMService.get_model_config(tenant_id, llm_type, llm_name)
  114. if llm_type == LLMType.EMBEDDING.value:
  115. if model_config["llm_factory"] not in EmbeddingModel:
  116. return
  117. return EmbeddingModel[model_config["llm_factory"]](
  118. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  119. if llm_type == LLMType.RERANK:
  120. if model_config["llm_factory"] not in RerankModel:
  121. return
  122. return RerankModel[model_config["llm_factory"]](
  123. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  124. if llm_type == LLMType.IMAGE2TEXT.value:
  125. if model_config["llm_factory"] not in CvModel:
  126. return
  127. return CvModel[model_config["llm_factory"]](
  128. model_config["api_key"], model_config["llm_name"], lang,
  129. base_url=model_config["api_base"]
  130. )
  131. if llm_type == LLMType.CHAT.value:
  132. if model_config["llm_factory"] not in ChatModel:
  133. return
  134. return ChatModel[model_config["llm_factory"]](
  135. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  136. if llm_type == LLMType.SPEECH2TEXT:
  137. if model_config["llm_factory"] not in Seq2txtModel:
  138. return
  139. return Seq2txtModel[model_config["llm_factory"]](
  140. key=model_config["api_key"], model_name=model_config["llm_name"],
  141. lang=lang,
  142. base_url=model_config["api_base"]
  143. )
  144. if llm_type == LLMType.TTS:
  145. if model_config["llm_factory"] not in TTSModel:
  146. return
  147. return TTSModel[model_config["llm_factory"]](
  148. model_config["api_key"],
  149. model_config["llm_name"],
  150. base_url=model_config["api_base"],
  151. )
  152. @classmethod
  153. @DB.connection_context()
  154. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  155. e, tenant = TenantService.get_by_id(tenant_id)
  156. if not e:
  157. logging.error(f"Tenant not found: {tenant_id}")
  158. return 0
  159. llm_map = {
  160. LLMType.EMBEDDING.value: tenant.embd_id,
  161. LLMType.SPEECH2TEXT.value: tenant.asr_id,
  162. LLMType.IMAGE2TEXT.value: tenant.img2txt_id,
  163. LLMType.CHAT.value: tenant.llm_id if not llm_name else llm_name,
  164. LLMType.RERANK.value: tenant.rerank_id if not llm_name else llm_name,
  165. LLMType.TTS.value: tenant.tts_id if not llm_name else llm_name
  166. }
  167. mdlnm = llm_map.get(llm_type)
  168. if mdlnm is None:
  169. logging.error(f"LLM type error: {llm_type}")
  170. return 0
  171. llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(mdlnm)
  172. try:
  173. num = cls.model.update(
  174. used_tokens=cls.model.used_tokens + used_tokens
  175. ).where(
  176. cls.model.tenant_id == tenant_id,
  177. cls.model.llm_name == llm_name,
  178. cls.model.llm_factory == llm_factory if llm_factory else True
  179. ).execute()
  180. except Exception:
  181. logging.exception(
  182. "TenantLLMService.increase_usage got exception,Failed to update used_tokens for tenant_id=%s, llm_name=%s",
  183. tenant_id, llm_name)
  184. return 0
  185. return num
  186. @classmethod
  187. @DB.connection_context()
  188. def get_openai_models(cls):
  189. objs = cls.model.select().where(
  190. (cls.model.llm_factory == "OpenAI"),
  191. ~(cls.model.llm_name == "text-embedding-3-small"),
  192. ~(cls.model.llm_name == "text-embedding-3-large")
  193. ).dicts()
  194. return list(objs)
  195. class LLMBundle:
  196. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese"):
  197. self.tenant_id = tenant_id
  198. self.llm_type = llm_type
  199. self.llm_name = llm_name
  200. self.mdl = TenantLLMService.model_instance(
  201. tenant_id, llm_type, llm_name, lang=lang)
  202. assert self.mdl, "Can't find model for {}/{}/{}".format(
  203. tenant_id, llm_type, llm_name)
  204. model_config = TenantLLMService.get_model_config(tenant_id, llm_type, llm_name)
  205. self.max_length = model_config.get("max_tokens", 8192)
  206. def encode(self, texts: list):
  207. embeddings, used_tokens = self.mdl.encode(texts)
  208. if not TenantLLMService.increase_usage(
  209. self.tenant_id, self.llm_type, used_tokens):
  210. logging.error(
  211. "LLMBundle.encode can't update token usage for {}/EMBEDDING used_tokens: {}".format(self.tenant_id, used_tokens))
  212. return embeddings, used_tokens
  213. def encode_queries(self, query: str):
  214. emd, used_tokens = self.mdl.encode_queries(query)
  215. if not TenantLLMService.increase_usage(
  216. self.tenant_id, self.llm_type, used_tokens):
  217. logging.error(
  218. "LLMBundle.encode_queries can't update token usage for {}/EMBEDDING used_tokens: {}".format(self.tenant_id, used_tokens))
  219. return emd, used_tokens
  220. def similarity(self, query: str, texts: list):
  221. sim, used_tokens = self.mdl.similarity(query, texts)
  222. if not TenantLLMService.increase_usage(
  223. self.tenant_id, self.llm_type, used_tokens):
  224. logging.error(
  225. "LLMBundle.similarity can't update token usage for {}/RERANK used_tokens: {}".format(self.tenant_id, used_tokens))
  226. return sim, used_tokens
  227. def describe(self, image, max_tokens=300):
  228. txt, used_tokens = self.mdl.describe(image, max_tokens)
  229. if not TenantLLMService.increase_usage(
  230. self.tenant_id, self.llm_type, used_tokens):
  231. logging.error(
  232. "LLMBundle.describe can't update token usage for {}/IMAGE2TEXT used_tokens: {}".format(self.tenant_id, used_tokens))
  233. return txt
  234. def describe_with_prompt(self, image, prompt):
  235. txt, used_tokens = self.mdl.describe_with_prompt(image, prompt)
  236. if not TenantLLMService.increase_usage(
  237. self.tenant_id, self.llm_type, used_tokens):
  238. logging.error(
  239. "LLMBundle.describe can't update token usage for {}/IMAGE2TEXT used_tokens: {}".format(self.tenant_id, used_tokens))
  240. return txt
  241. def transcription(self, audio):
  242. txt, used_tokens = self.mdl.transcription(audio)
  243. if not TenantLLMService.increase_usage(
  244. self.tenant_id, self.llm_type, used_tokens):
  245. logging.error(
  246. "LLMBundle.transcription can't update token usage for {}/SEQUENCE2TXT used_tokens: {}".format(self.tenant_id, used_tokens))
  247. return txt
  248. def tts(self, text):
  249. for chunk in self.mdl.tts(text):
  250. if isinstance(chunk, int):
  251. if not TenantLLMService.increase_usage(
  252. self.tenant_id, self.llm_type, chunk, self.llm_name):
  253. logging.error(
  254. "LLMBundle.tts can't update token usage for {}/TTS".format(self.tenant_id))
  255. return
  256. yield chunk
  257. def chat(self, system, history, gen_conf):
  258. txt, used_tokens = self.mdl.chat(system, history, gen_conf)
  259. if isinstance(txt, int) and not TenantLLMService.increase_usage(
  260. self.tenant_id, self.llm_type, used_tokens, self.llm_name):
  261. logging.error(
  262. "LLMBundle.chat can't update token usage for {}/CHAT llm_name: {}, used_tokens: {}".format(self.tenant_id, self.llm_name,
  263. used_tokens))
  264. return txt
  265. def chat_streamly(self, system, history, gen_conf):
  266. for txt in self.mdl.chat_streamly(system, history, gen_conf):
  267. if isinstance(txt, int):
  268. if not TenantLLMService.increase_usage(
  269. self.tenant_id, self.llm_type, txt, self.llm_name):
  270. logging.error(
  271. "LLMBundle.chat_streamly can't update token usage for {}/CHAT llm_name: {}, content: {}".format(self.tenant_id, self.llm_name,
  272. txt))
  273. return
  274. yield txt