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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  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 get_model_config(cls, tenant_id, llm_type, llm_name=None):
  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. return model_config
  112. @classmethod
  113. @DB.connection_context()
  114. def model_instance(cls, tenant_id, llm_type,
  115. llm_name=None, lang="Chinese"):
  116. model_config = TenantLLMService.get_model_config(tenant_id, llm_type, llm_name)
  117. if llm_type == LLMType.EMBEDDING.value:
  118. if model_config["llm_factory"] not in EmbeddingModel:
  119. return
  120. return EmbeddingModel[model_config["llm_factory"]](
  121. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  122. if llm_type == LLMType.RERANK:
  123. if model_config["llm_factory"] not in RerankModel:
  124. return
  125. return RerankModel[model_config["llm_factory"]](
  126. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  127. if llm_type == LLMType.IMAGE2TEXT.value:
  128. if model_config["llm_factory"] not in CvModel:
  129. return
  130. return CvModel[model_config["llm_factory"]](
  131. model_config["api_key"], model_config["llm_name"], lang,
  132. base_url=model_config["api_base"]
  133. )
  134. if llm_type == LLMType.CHAT.value:
  135. if model_config["llm_factory"] not in ChatModel:
  136. return
  137. return ChatModel[model_config["llm_factory"]](
  138. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  139. if llm_type == LLMType.SPEECH2TEXT:
  140. if model_config["llm_factory"] not in Seq2txtModel:
  141. return
  142. return Seq2txtModel[model_config["llm_factory"]](
  143. key=model_config["api_key"], model_name=model_config["llm_name"],
  144. lang=lang,
  145. base_url=model_config["api_base"]
  146. )
  147. if llm_type == LLMType.TTS:
  148. if model_config["llm_factory"] not in TTSModel:
  149. return
  150. return TTSModel[model_config["llm_factory"]](
  151. model_config["api_key"],
  152. model_config["llm_name"],
  153. base_url=model_config["api_base"],
  154. )
  155. @classmethod
  156. @DB.connection_context()
  157. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  158. e, tenant = TenantService.get_by_id(tenant_id)
  159. if not e:
  160. logging.error(f"Tenant not found: {tenant_id}")
  161. return 0
  162. llm_map = {
  163. LLMType.EMBEDDING.value: tenant.embd_id,
  164. LLMType.SPEECH2TEXT.value: tenant.asr_id,
  165. LLMType.IMAGE2TEXT.value: tenant.img2txt_id,
  166. LLMType.CHAT.value: tenant.llm_id if not llm_name else llm_name,
  167. LLMType.RERANK.value: tenant.rerank_id if not llm_name else llm_name,
  168. LLMType.TTS.value: tenant.tts_id if not llm_name else llm_name
  169. }
  170. mdlnm = llm_map.get(llm_type)
  171. if mdlnm is None:
  172. logging.error(f"LLM type error: {llm_type}")
  173. return 0
  174. llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(mdlnm)
  175. try:
  176. num = cls.model.update(
  177. used_tokens=cls.model.used_tokens + used_tokens
  178. ).where(
  179. cls.model.tenant_id == tenant_id,
  180. cls.model.llm_name == llm_name,
  181. cls.model.llm_factory == llm_factory if llm_factory else True
  182. ).execute()
  183. except Exception:
  184. logging.exception(
  185. "TenantLLMService.increase_usage got exception,Failed to update used_tokens for tenant_id=%s, llm_name=%s",
  186. tenant_id, llm_name)
  187. return 0
  188. return num
  189. @classmethod
  190. @DB.connection_context()
  191. def get_openai_models(cls):
  192. objs = cls.model.select().where(
  193. (cls.model.llm_factory == "OpenAI"),
  194. ~(cls.model.llm_name == "text-embedding-3-small"),
  195. ~(cls.model.llm_name == "text-embedding-3-large")
  196. ).dicts()
  197. return list(objs)
  198. class LLMBundle:
  199. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese"):
  200. self.tenant_id = tenant_id
  201. self.llm_type = llm_type
  202. self.llm_name = llm_name
  203. self.mdl = TenantLLMService.model_instance(
  204. tenant_id, llm_type, llm_name, lang=lang)
  205. assert self.mdl, "Can't find model for {}/{}/{}".format(
  206. tenant_id, llm_type, llm_name)
  207. model_config = TenantLLMService.get_model_config(tenant_id, llm_type, llm_name)
  208. self.max_length = model_config.get("max_tokens", 8192)
  209. def encode(self, texts: list):
  210. embeddings, used_tokens = self.mdl.encode(texts)
  211. if not TenantLLMService.increase_usage(
  212. self.tenant_id, self.llm_type, used_tokens):
  213. logging.error(
  214. "LLMBundle.encode can't update token usage for {}/EMBEDDING used_tokens: {}".format(self.tenant_id, used_tokens))
  215. return embeddings, used_tokens
  216. def encode_queries(self, query: str):
  217. emd, used_tokens = self.mdl.encode_queries(query)
  218. if not TenantLLMService.increase_usage(
  219. self.tenant_id, self.llm_type, used_tokens):
  220. logging.error(
  221. "LLMBundle.encode_queries can't update token usage for {}/EMBEDDING used_tokens: {}".format(self.tenant_id, used_tokens))
  222. return emd, used_tokens
  223. def similarity(self, query: str, texts: list):
  224. sim, used_tokens = self.mdl.similarity(query, texts)
  225. if not TenantLLMService.increase_usage(
  226. self.tenant_id, self.llm_type, used_tokens):
  227. logging.error(
  228. "LLMBundle.similarity can't update token usage for {}/RERANK used_tokens: {}".format(self.tenant_id, used_tokens))
  229. return sim, used_tokens
  230. def describe(self, image, max_tokens=300):
  231. txt, used_tokens = self.mdl.describe(image, max_tokens)
  232. if not TenantLLMService.increase_usage(
  233. self.tenant_id, self.llm_type, used_tokens):
  234. logging.error(
  235. "LLMBundle.describe can't update token usage for {}/IMAGE2TEXT used_tokens: {}".format(self.tenant_id, used_tokens))
  236. return txt
  237. def transcription(self, audio):
  238. txt, used_tokens = self.mdl.transcription(audio)
  239. if not TenantLLMService.increase_usage(
  240. self.tenant_id, self.llm_type, used_tokens):
  241. logging.error(
  242. "LLMBundle.transcription can't update token usage for {}/SEQUENCE2TXT used_tokens: {}".format(self.tenant_id, used_tokens))
  243. return txt
  244. def tts(self, text):
  245. for chunk in self.mdl.tts(text):
  246. if isinstance(chunk, int):
  247. if not TenantLLMService.increase_usage(
  248. self.tenant_id, self.llm_type, chunk, self.llm_name):
  249. logging.error(
  250. "LLMBundle.tts can't update token usage for {}/TTS".format(self.tenant_id))
  251. return
  252. yield chunk
  253. def chat(self, system, history, gen_conf):
  254. txt, used_tokens = self.mdl.chat(system, history, gen_conf)
  255. if isinstance(txt, int) and not TenantLLMService.increase_usage(
  256. self.tenant_id, self.llm_type, used_tokens, self.llm_name):
  257. logging.error(
  258. "LLMBundle.chat can't update token usage for {}/CHAT llm_name: {}, used_tokens: {}".format(self.tenant_id, self.llm_name,
  259. used_tokens))
  260. return txt
  261. def chat_streamly(self, system, history, gen_conf):
  262. for txt in self.mdl.chat_streamly(system, history, gen_conf):
  263. if isinstance(txt, int):
  264. if not TenantLLMService.increase_usage(
  265. self.tenant_id, self.llm_type, txt, self.llm_name):
  266. logging.error(
  267. "LLMBundle.chat_streamly can't update token usage for {}/CHAT llm_name: {}, content: {}".format(self.tenant_id, self.llm_name,
  268. txt))
  269. return
  270. yield txt