Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

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 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. raise LookupError("Tenant not found")
  156. if llm_type == LLMType.EMBEDDING.value:
  157. mdlnm = tenant.embd_id
  158. elif llm_type == LLMType.SPEECH2TEXT.value:
  159. mdlnm = tenant.asr_id
  160. elif llm_type == LLMType.IMAGE2TEXT.value:
  161. mdlnm = tenant.img2txt_id
  162. elif llm_type == LLMType.CHAT.value:
  163. mdlnm = tenant.llm_id if not llm_name else llm_name
  164. elif llm_type == LLMType.RERANK:
  165. mdlnm = tenant.rerank_id if not llm_name else llm_name
  166. elif llm_type == LLMType.TTS:
  167. mdlnm = tenant.tts_id if not llm_name else llm_name
  168. else:
  169. assert False, "LLM type error"
  170. llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(mdlnm)
  171. num = 0
  172. try:
  173. if llm_factory:
  174. tenant_llms = cls.query(tenant_id=tenant_id, llm_name=llm_name, llm_factory=llm_factory)
  175. else:
  176. tenant_llms = cls.query(tenant_id=tenant_id, llm_name=llm_name)
  177. if not tenant_llms:
  178. return num
  179. else:
  180. tenant_llm = tenant_llms[0]
  181. num = cls.model.update(used_tokens=tenant_llm.used_tokens + used_tokens) \
  182. .where(cls.model.tenant_id == tenant_id, cls.model.llm_factory == tenant_llm.llm_factory, cls.model.llm_name == llm_name) \
  183. .execute()
  184. except Exception:
  185. logging.exception("TenantLLMService.increase_usage got exception")
  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(object):
  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. self.max_length = 8192
  206. for lm in LLMService.query(llm_name=llm_name):
  207. self.max_length = lm.max_tokens
  208. break
  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