Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

llm_service.py 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. # model name must be xxx@yyy
  65. try:
  66. model_factories = json.load(open(os.path.join(get_project_base_directory(), "conf/llm_factories.json"), "r"))["factory_llm_infos"]
  67. model_providers = set([f["name"] for f in model_factories])
  68. if arr[-1] not in model_providers:
  69. return model_name, None
  70. return arr[0], arr[-1]
  71. except Exception as e:
  72. logging.exception(f"TenantLLMService.split_model_name_and_factory got exception: {e}")
  73. return model_name, None
  74. @classmethod
  75. @DB.connection_context()
  76. def model_instance(cls, tenant_id, llm_type,
  77. llm_name=None, lang="Chinese"):
  78. e, tenant = TenantService.get_by_id(tenant_id)
  79. if not e:
  80. raise LookupError("Tenant not found")
  81. if llm_type == LLMType.EMBEDDING.value:
  82. mdlnm = tenant.embd_id if not llm_name else llm_name
  83. elif llm_type == LLMType.SPEECH2TEXT.value:
  84. mdlnm = tenant.asr_id
  85. elif llm_type == LLMType.IMAGE2TEXT.value:
  86. mdlnm = tenant.img2txt_id if not llm_name else llm_name
  87. elif llm_type == LLMType.CHAT.value:
  88. mdlnm = tenant.llm_id if not llm_name else llm_name
  89. elif llm_type == LLMType.RERANK:
  90. mdlnm = tenant.rerank_id if not llm_name else llm_name
  91. elif llm_type == LLMType.TTS:
  92. mdlnm = tenant.tts_id if not llm_name else llm_name
  93. else:
  94. assert False, "LLM type error"
  95. model_config = cls.get_api_key(tenant_id, mdlnm)
  96. mdlnm, fid = TenantLLMService.split_model_name_and_factory(mdlnm)
  97. if model_config:
  98. model_config = model_config.to_dict()
  99. if not model_config:
  100. if llm_type in [LLMType.EMBEDDING, LLMType.RERANK]:
  101. llm = LLMService.query(llm_name=mdlnm) if not fid else LLMService.query(llm_name=mdlnm, fid=fid)
  102. if llm and llm[0].fid in ["Youdao", "FastEmbed", "BAAI"]:
  103. model_config = {"llm_factory": llm[0].fid, "api_key": "", "llm_name": mdlnm, "api_base": ""}
  104. if not model_config:
  105. if mdlnm == "flag-embedding":
  106. model_config = {"llm_factory": "Tongyi-Qianwen", "api_key": "",
  107. "llm_name": llm_name, "api_base": ""}
  108. else:
  109. if not mdlnm:
  110. raise LookupError(f"Type of {llm_type} model is not set.")
  111. raise LookupError("Model({}) not authorized".format(mdlnm))
  112. if llm_type == LLMType.EMBEDDING.value:
  113. if model_config["llm_factory"] not in EmbeddingModel:
  114. return
  115. return EmbeddingModel[model_config["llm_factory"]](
  116. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  117. if llm_type == LLMType.RERANK:
  118. if model_config["llm_factory"] not in RerankModel:
  119. return
  120. return RerankModel[model_config["llm_factory"]](
  121. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  122. if llm_type == LLMType.IMAGE2TEXT.value:
  123. if model_config["llm_factory"] not in CvModel:
  124. return
  125. return CvModel[model_config["llm_factory"]](
  126. model_config["api_key"], model_config["llm_name"], lang,
  127. base_url=model_config["api_base"]
  128. )
  129. if llm_type == LLMType.CHAT.value:
  130. if model_config["llm_factory"] not in ChatModel:
  131. return
  132. return ChatModel[model_config["llm_factory"]](
  133. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  134. if llm_type == LLMType.SPEECH2TEXT:
  135. if model_config["llm_factory"] not in Seq2txtModel:
  136. return
  137. return Seq2txtModel[model_config["llm_factory"]](
  138. key=model_config["api_key"], model_name=model_config["llm_name"],
  139. lang=lang,
  140. base_url=model_config["api_base"]
  141. )
  142. if llm_type == LLMType.TTS:
  143. if model_config["llm_factory"] not in TTSModel:
  144. return
  145. return TTSModel[model_config["llm_factory"]](
  146. model_config["api_key"],
  147. model_config["llm_name"],
  148. base_url=model_config["api_base"],
  149. )
  150. @classmethod
  151. @DB.connection_context()
  152. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  153. e, tenant = TenantService.get_by_id(tenant_id)
  154. if not e:
  155. logging.error(f"Tenant not found: {tenant_id}")
  156. return 0
  157. llm_map = {
  158. LLMType.EMBEDDING.value: tenant.embd_id,
  159. LLMType.SPEECH2TEXT.value: tenant.asr_id,
  160. LLMType.IMAGE2TEXT.value: tenant.img2txt_id,
  161. LLMType.CHAT.value: tenant.llm_id if not llm_name else llm_name,
  162. LLMType.RERANK.value: tenant.rerank_id if not llm_name else llm_name,
  163. LLMType.TTS.value: tenant.tts_id if not llm_name else llm_name
  164. }
  165. mdlnm = llm_map.get(llm_type)
  166. if mdlnm is None:
  167. logging.error(f"LLM type error: {llm_type}")
  168. return 0
  169. llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(mdlnm)
  170. try:
  171. num = cls.model.update(
  172. used_tokens=cls.model.used_tokens + used_tokens
  173. ).where(
  174. cls.model.tenant_id == tenant_id,
  175. cls.model.llm_name == llm_name,
  176. cls.model.llm_factory == llm_factory if llm_factory else True
  177. ).execute()
  178. except Exception:
  179. logging.exception(
  180. "TenantLLMService.increase_usage got exception,Failed to update used_tokens for tenant_id=%s, llm_name=%s",
  181. tenant_id, llm_name)
  182. return 0
  183. return num
  184. @classmethod
  185. @DB.connection_context()
  186. def get_openai_models(cls):
  187. objs = cls.model.select().where(
  188. (cls.model.llm_factory == "OpenAI"),
  189. ~(cls.model.llm_name == "text-embedding-3-small"),
  190. ~(cls.model.llm_name == "text-embedding-3-large")
  191. ).dicts()
  192. return list(objs)
  193. class LLMBundle(object):
  194. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese"):
  195. self.tenant_id = tenant_id
  196. self.llm_type = llm_type
  197. self.llm_name = llm_name
  198. self.mdl = TenantLLMService.model_instance(
  199. tenant_id, llm_type, llm_name, lang=lang)
  200. assert self.mdl, "Can't find model for {}/{}/{}".format(
  201. tenant_id, llm_type, llm_name)
  202. self.max_length = 8192
  203. for lm in LLMService.query(llm_name=llm_name):
  204. self.max_length = lm.max_tokens
  205. break
  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 transcription(self, audio):
  235. txt, used_tokens = self.mdl.transcription(audio)
  236. if not TenantLLMService.increase_usage(
  237. self.tenant_id, self.llm_type, used_tokens):
  238. logging.error(
  239. "LLMBundle.transcription can't update token usage for {}/SEQUENCE2TXT used_tokens: {}".format(self.tenant_id, used_tokens))
  240. return txt
  241. def tts(self, text):
  242. for chunk in self.mdl.tts(text):
  243. if isinstance(chunk, int):
  244. if not TenantLLMService.increase_usage(
  245. self.tenant_id, self.llm_type, chunk, self.llm_name):
  246. logging.error(
  247. "LLMBundle.tts can't update token usage for {}/TTS".format(self.tenant_id))
  248. return
  249. yield chunk
  250. def chat(self, system, history, gen_conf):
  251. txt, used_tokens = self.mdl.chat(system, history, gen_conf)
  252. if isinstance(txt, int) and not TenantLLMService.increase_usage(
  253. self.tenant_id, self.llm_type, used_tokens, self.llm_name):
  254. logging.error(
  255. "LLMBundle.chat can't update token usage for {}/CHAT llm_name: {}, used_tokens: {}".format(self.tenant_id, self.llm_name,
  256. used_tokens))
  257. return txt
  258. def chat_streamly(self, system, history, gen_conf):
  259. for txt in self.mdl.chat_streamly(system, history, gen_conf):
  260. if isinstance(txt, int):
  261. if not TenantLLMService.increase_usage(
  262. self.tenant_id, self.llm_type, txt, self.llm_name):
  263. logging.error(
  264. "LLMBundle.chat_streamly can't update token usage for {}/CHAT llm_name: {}, content: {}".format(self.tenant_id, self.llm_name,
  265. txt))
  266. return
  267. yield txt