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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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: model_config = model_config.to_dict()
  97. if not model_config:
  98. if llm_type in [LLMType.EMBEDDING, LLMType.RERANK]:
  99. llm = LLMService.query(llm_name=mdlnm) if not fid else LLMService.query(llm_name=mdlnm, fid=fid)
  100. if llm and llm[0].fid in ["Youdao", "FastEmbed", "BAAI"]:
  101. model_config = {"llm_factory": llm[0].fid, "api_key":"", "llm_name": mdlnm, "api_base": ""}
  102. if not model_config:
  103. if mdlnm == "flag-embedding":
  104. model_config = {"llm_factory": "Tongyi-Qianwen", "api_key": "",
  105. "llm_name": llm_name, "api_base": ""}
  106. else:
  107. if not mdlnm:
  108. raise LookupError(f"Type of {llm_type} model is not set.")
  109. raise LookupError("Model({}) not authorized".format(mdlnm))
  110. if llm_type == LLMType.EMBEDDING.value:
  111. if model_config["llm_factory"] not in EmbeddingModel:
  112. return
  113. return EmbeddingModel[model_config["llm_factory"]](
  114. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  115. if llm_type == LLMType.RERANK:
  116. if model_config["llm_factory"] not in RerankModel:
  117. return
  118. return RerankModel[model_config["llm_factory"]](
  119. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  120. if llm_type == LLMType.IMAGE2TEXT.value:
  121. if model_config["llm_factory"] not in CvModel:
  122. return
  123. return CvModel[model_config["llm_factory"]](
  124. model_config["api_key"], model_config["llm_name"], lang,
  125. base_url=model_config["api_base"]
  126. )
  127. if llm_type == LLMType.CHAT.value:
  128. if model_config["llm_factory"] not in ChatModel:
  129. return
  130. return ChatModel[model_config["llm_factory"]](
  131. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  132. if llm_type == LLMType.SPEECH2TEXT:
  133. if model_config["llm_factory"] not in Seq2txtModel:
  134. return
  135. return Seq2txtModel[model_config["llm_factory"]](
  136. key=model_config["api_key"], model_name=model_config["llm_name"],
  137. lang=lang,
  138. base_url=model_config["api_base"]
  139. )
  140. if llm_type == LLMType.TTS:
  141. if model_config["llm_factory"] not in TTSModel:
  142. return
  143. return TTSModel[model_config["llm_factory"]](
  144. model_config["api_key"],
  145. model_config["llm_name"],
  146. base_url=model_config["api_base"],
  147. )
  148. @classmethod
  149. @DB.connection_context()
  150. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  151. e, tenant = TenantService.get_by_id(tenant_id)
  152. if not e:
  153. raise LookupError("Tenant not found")
  154. if llm_type == LLMType.EMBEDDING.value:
  155. mdlnm = tenant.embd_id
  156. elif llm_type == LLMType.SPEECH2TEXT.value:
  157. mdlnm = tenant.asr_id
  158. elif llm_type == LLMType.IMAGE2TEXT.value:
  159. mdlnm = tenant.img2txt_id
  160. elif llm_type == LLMType.CHAT.value:
  161. mdlnm = tenant.llm_id if not llm_name else llm_name
  162. elif llm_type == LLMType.RERANK:
  163. mdlnm = tenant.rerank_id if not llm_name else llm_name
  164. elif llm_type == LLMType.TTS:
  165. mdlnm = tenant.tts_id if not llm_name else llm_name
  166. else:
  167. assert False, "LLM type error"
  168. llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(mdlnm)
  169. num = 0
  170. try:
  171. if llm_factory:
  172. tenant_llms = cls.query(tenant_id=tenant_id, llm_name=llm_name, llm_factory=llm_factory)
  173. else:
  174. tenant_llms = cls.query(tenant_id=tenant_id, llm_name=llm_name)
  175. if not tenant_llms:
  176. return num
  177. else:
  178. tenant_llm = tenant_llms[0]
  179. num = cls.model.update(used_tokens=tenant_llm.used_tokens + used_tokens)\
  180. .where(cls.model.tenant_id == tenant_id, cls.model.llm_factory == tenant_llm.llm_factory, cls.model.llm_name == llm_name)\
  181. .execute()
  182. except Exception:
  183. logging.exception("TenantLLMService.increase_usage got exception")
  184. return num
  185. @classmethod
  186. @DB.connection_context()
  187. def get_openai_models(cls):
  188. objs = cls.model.select().where(
  189. (cls.model.llm_factory == "OpenAI"),
  190. ~(cls.model.llm_name == "text-embedding-3-small"),
  191. ~(cls.model.llm_name == "text-embedding-3-large")
  192. ).dicts()
  193. return list(objs)
  194. class LLMBundle(object):
  195. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese"):
  196. self.tenant_id = tenant_id
  197. self.llm_type = llm_type
  198. self.llm_name = llm_name
  199. self.mdl = TenantLLMService.model_instance(
  200. tenant_id, llm_type, llm_name, lang=lang)
  201. assert self.mdl, "Can't find model for {}/{}/{}".format(
  202. tenant_id, llm_type, llm_name)
  203. self.max_length = 8192
  204. for lm in LLMService.query(llm_name=llm_name):
  205. self.max_length = lm.max_tokens
  206. break
  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, 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, txt))
  265. return
  266. yield txt