Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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