You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

tenant_llm_service.py 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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, 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 TenantLLMService(CommonService):
  28. model = TenantLLM
  29. @classmethod
  30. @DB.connection_context()
  31. def get_api_key(cls, tenant_id, model_name):
  32. mdlnm, fid = TenantLLMService.split_model_name_and_factory(model_name)
  33. if not fid:
  34. objs = cls.query(tenant_id=tenant_id, llm_name=mdlnm)
  35. else:
  36. objs = cls.query(tenant_id=tenant_id, llm_name=mdlnm, llm_factory=fid)
  37. if (not objs) and fid:
  38. if fid == "LocalAI":
  39. mdlnm += "___LocalAI"
  40. elif fid == "HuggingFace":
  41. mdlnm += "___HuggingFace"
  42. elif fid == "OpenAI-API-Compatible":
  43. mdlnm += "___OpenAI-API"
  44. elif fid == "VLLM":
  45. mdlnm += "___VLLM"
  46. objs = cls.query(tenant_id=tenant_id, llm_name=mdlnm, llm_factory=fid)
  47. if not objs:
  48. return
  49. return objs[0]
  50. @classmethod
  51. @DB.connection_context()
  52. def get_my_llms(cls, tenant_id):
  53. fields = [cls.model.llm_factory, LLMFactories.logo, LLMFactories.tags, cls.model.model_type, cls.model.llm_name, cls.model.used_tokens]
  54. 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()
  55. return list(objs)
  56. @staticmethod
  57. def split_model_name_and_factory(model_name):
  58. arr = model_name.split("@")
  59. if len(arr) < 2:
  60. return model_name, None
  61. if len(arr) > 2:
  62. return "@".join(arr[0:-1]), arr[-1]
  63. # model name must be xxx@yyy
  64. try:
  65. model_factories = settings.FACTORY_LLM_INFOS
  66. model_providers = set([f["name"] for f in model_factories])
  67. if arr[-1] not in model_providers:
  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 get_model_config(cls, tenant_id, llm_type, llm_name=None):
  76. from api.db.services.llm_service import LLMService
  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 not model_config: # for some cases seems fid mismatch
  97. model_config = cls.get_api_key(tenant_id, mdlnm)
  98. if model_config:
  99. model_config = model_config.to_dict()
  100. llm = LLMService.query(llm_name=mdlnm) if not fid else LLMService.query(llm_name=mdlnm, fid=fid)
  101. if not llm and fid: # for some cases seems fid mismatch
  102. llm = LLMService.query(llm_name=mdlnm)
  103. if llm:
  104. model_config["is_tools"] = llm[0].is_tools
  105. if not model_config:
  106. if llm_type in [LLMType.EMBEDDING, LLMType.RERANK]:
  107. llm = LLMService.query(llm_name=mdlnm) if not fid else LLMService.query(llm_name=mdlnm, fid=fid)
  108. if llm and llm[0].fid in ["Youdao", "FastEmbed", "BAAI"]:
  109. model_config = {"llm_factory": llm[0].fid, "api_key": "", "llm_name": mdlnm, "api_base": ""}
  110. if not model_config:
  111. if mdlnm == "flag-embedding":
  112. model_config = {"llm_factory": "Tongyi-Qianwen", "api_key": "", "llm_name": llm_name, "api_base": ""}
  113. else:
  114. if not mdlnm:
  115. raise LookupError(f"Type of {llm_type} model is not set.")
  116. raise LookupError("Model({}) not authorized".format(mdlnm))
  117. return model_config
  118. @classmethod
  119. @DB.connection_context()
  120. def model_instance(cls, tenant_id, llm_type, llm_name=None, lang="Chinese", **kwargs):
  121. model_config = TenantLLMService.get_model_config(tenant_id, llm_type, llm_name)
  122. kwargs.update({"provider": model_config["llm_factory"]})
  123. if llm_type == LLMType.EMBEDDING.value:
  124. if model_config["llm_factory"] not in EmbeddingModel:
  125. return
  126. return EmbeddingModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  127. if llm_type == LLMType.RERANK:
  128. if model_config["llm_factory"] not in RerankModel:
  129. return
  130. return RerankModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  131. if llm_type == LLMType.IMAGE2TEXT.value:
  132. if model_config["llm_factory"] not in CvModel:
  133. return
  134. return CvModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], lang, base_url=model_config["api_base"], **kwargs)
  135. if llm_type == LLMType.CHAT.value:
  136. if model_config["llm_factory"] not in ChatModel:
  137. return
  138. return ChatModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"], **kwargs)
  139. if llm_type == LLMType.SPEECH2TEXT:
  140. if model_config["llm_factory"] not in Seq2txtModel:
  141. return
  142. 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"])
  143. if llm_type == LLMType.TTS:
  144. if model_config["llm_factory"] not in TTSModel:
  145. return
  146. return TTSModel[model_config["llm_factory"]](
  147. model_config["api_key"],
  148. model_config["llm_name"],
  149. base_url=model_config["api_base"],
  150. )
  151. @classmethod
  152. @DB.connection_context()
  153. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  154. e, tenant = TenantService.get_by_id(tenant_id)
  155. if not e:
  156. logging.error(f"Tenant not found: {tenant_id}")
  157. return 0
  158. llm_map = {
  159. LLMType.EMBEDDING.value: tenant.embd_id if not llm_name else llm_name,
  160. LLMType.SPEECH2TEXT.value: tenant.asr_id,
  161. LLMType.IMAGE2TEXT.value: tenant.img2txt_id,
  162. LLMType.CHAT.value: tenant.llm_id if not llm_name else llm_name,
  163. LLMType.RERANK.value: tenant.rerank_id if not llm_name else llm_name,
  164. LLMType.TTS.value: tenant.tts_id if not llm_name else llm_name,
  165. }
  166. mdlnm = llm_map.get(llm_type)
  167. if mdlnm is None:
  168. logging.error(f"LLM type error: {llm_type}")
  169. return 0
  170. llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(mdlnm)
  171. try:
  172. num = (
  173. cls.model.update(used_tokens=cls.model.used_tokens + used_tokens)
  174. .where(cls.model.tenant_id == tenant_id, cls.model.llm_name == llm_name, cls.model.llm_factory == llm_factory if llm_factory else True)
  175. .execute()
  176. )
  177. except Exception:
  178. logging.exception("TenantLLMService.increase_usage got exception,Failed to update used_tokens for tenant_id=%s, llm_name=%s", tenant_id, llm_name)
  179. return 0
  180. return num
  181. @classmethod
  182. @DB.connection_context()
  183. def get_openai_models(cls):
  184. 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()
  185. return list(objs)
  186. @staticmethod
  187. def llm_id2llm_type(llm_id: str) -> str | None:
  188. from api.db.services.llm_service import LLMService
  189. llm_id, *_ = TenantLLMService.split_model_name_and_factory(llm_id)
  190. llm_factories = settings.FACTORY_LLM_INFOS
  191. for llm_factory in llm_factories:
  192. for llm in llm_factory["llm"]:
  193. if llm_id == llm["llm_name"]:
  194. return llm["model_type"].split(",")[-1]
  195. for llm in LLMService.query(llm_name=llm_id):
  196. return llm.model_type
  197. llm = TenantLLMService.get_or_none(llm_name=llm_id)
  198. if llm:
  199. return llm.model_type
  200. for llm in TenantLLMService.query(llm_name=llm_id):
  201. return llm.model_type
  202. class LLM4Tenant:
  203. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese", **kwargs):
  204. self.tenant_id = tenant_id
  205. self.llm_type = llm_type
  206. self.llm_name = llm_name
  207. self.mdl = TenantLLMService.model_instance(tenant_id, llm_type, llm_name, lang=lang, **kwargs)
  208. assert self.mdl, "Can't find model for {}/{}/{}".format(tenant_id, llm_type, llm_name)
  209. model_config = TenantLLMService.get_model_config(tenant_id, llm_type, llm_name)
  210. self.max_length = model_config.get("max_tokens", 8192)
  211. self.is_tools = model_config.get("is_tools", False)
  212. self.verbose_tool_use = kwargs.get("verbose_tool_use")
  213. langfuse_keys = TenantLangfuseService.filter_by_tenant(tenant_id=tenant_id)
  214. self.langfuse = None
  215. if langfuse_keys:
  216. langfuse = Langfuse(public_key=langfuse_keys.public_key, secret_key=langfuse_keys.secret_key, host=langfuse_keys.host)
  217. if langfuse.auth_check():
  218. self.langfuse = langfuse
  219. trace_id = self.langfuse.create_trace_id()
  220. self.trace_context = {"trace_id": trace_id}