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 13KB

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