Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

llm_service.py 13KB

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