您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

llm_service.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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. import re
  18. from functools import partial
  19. from langfuse import Langfuse
  20. from api import settings
  21. from api.db import LLMType
  22. from api.db.db_models import DB, LLM, LLMFactories, TenantLLM
  23. from api.db.services.common_service import CommonService
  24. from api.db.services.langfuse_service import TenantLangfuseService
  25. from api.db.services.user_service import TenantService
  26. from rag.llm import ChatModel, CvModel, EmbeddingModel, RerankModel, Seq2txtModel, TTSModel
  27. class LLMFactoriesService(CommonService):
  28. model = LLMFactories
  29. class LLMService(CommonService):
  30. model = LLM
  31. class TenantLLMService(CommonService):
  32. model = TenantLLM
  33. @classmethod
  34. @DB.connection_context()
  35. def get_api_key(cls, tenant_id, model_name):
  36. mdlnm, fid = TenantLLMService.split_model_name_and_factory(model_name)
  37. if not fid:
  38. objs = cls.query(tenant_id=tenant_id, llm_name=mdlnm)
  39. else:
  40. objs = cls.query(tenant_id=tenant_id, llm_name=mdlnm, llm_factory=fid)
  41. if (not objs) and fid:
  42. if fid == "LocalAI":
  43. mdlnm += "___LocalAI"
  44. elif fid == "HuggingFace":
  45. mdlnm += "___HuggingFace"
  46. elif fid == "OpenAI-API-Compatible":
  47. mdlnm += "___OpenAI-API"
  48. elif fid == "VLLM":
  49. mdlnm += "___VLLM"
  50. objs = cls.query(tenant_id=tenant_id, llm_name=mdlnm, llm_factory=fid)
  51. if not objs:
  52. return
  53. return objs[0]
  54. @classmethod
  55. @DB.connection_context()
  56. def get_my_llms(cls, tenant_id):
  57. fields = [cls.model.llm_factory, LLMFactories.logo, LLMFactories.tags, cls.model.model_type, cls.model.llm_name, cls.model.used_tokens]
  58. 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()
  59. return list(objs)
  60. @staticmethod
  61. def split_model_name_and_factory(model_name):
  62. arr = model_name.split("@")
  63. if len(arr) < 2:
  64. return model_name, None
  65. if len(arr) > 2:
  66. return "@".join(arr[0:-1]), arr[-1]
  67. # model name must be xxx@yyy
  68. try:
  69. model_factories = settings.FACTORY_LLM_INFOS
  70. model_providers = set([f["name"] for f in model_factories])
  71. if arr[-1] not in model_providers:
  72. return model_name, None
  73. return arr[0], arr[-1]
  74. except Exception as e:
  75. logging.exception(f"TenantLLMService.split_model_name_and_factory got exception: {e}")
  76. return model_name, None
  77. @classmethod
  78. @DB.connection_context()
  79. def get_model_config(cls, tenant_id, llm_type, llm_name=None):
  80. e, tenant = TenantService.get_by_id(tenant_id)
  81. if not e:
  82. raise LookupError("Tenant not found")
  83. if llm_type == LLMType.EMBEDDING.value:
  84. mdlnm = tenant.embd_id if not llm_name else llm_name
  85. elif llm_type == LLMType.SPEECH2TEXT.value:
  86. mdlnm = tenant.asr_id
  87. elif llm_type == LLMType.IMAGE2TEXT.value:
  88. mdlnm = tenant.img2txt_id if not llm_name else llm_name
  89. elif llm_type == LLMType.CHAT.value:
  90. mdlnm = tenant.llm_id if not llm_name else llm_name
  91. elif llm_type == LLMType.RERANK:
  92. mdlnm = tenant.rerank_id if not llm_name else llm_name
  93. elif llm_type == LLMType.TTS:
  94. mdlnm = tenant.tts_id if not llm_name else llm_name
  95. else:
  96. assert False, "LLM type error"
  97. model_config = cls.get_api_key(tenant_id, mdlnm)
  98. mdlnm, fid = TenantLLMService.split_model_name_and_factory(mdlnm)
  99. if not model_config: # for some cases seems fid mismatch
  100. model_config = cls.get_api_key(tenant_id, mdlnm)
  101. if model_config:
  102. model_config = model_config.to_dict()
  103. llm = LLMService.query(llm_name=mdlnm) if not fid else LLMService.query(llm_name=mdlnm, fid=fid)
  104. if not llm and fid: # for some cases seems fid mismatch
  105. llm = LLMService.query(llm_name=mdlnm)
  106. if llm:
  107. model_config["is_tools"] = llm[0].is_tools
  108. if not model_config:
  109. if llm_type in [LLMType.EMBEDDING, LLMType.RERANK]:
  110. llm = LLMService.query(llm_name=mdlnm) if not fid else LLMService.query(llm_name=mdlnm, fid=fid)
  111. if llm and llm[0].fid in ["Youdao", "FastEmbed", "BAAI"]:
  112. model_config = {"llm_factory": llm[0].fid, "api_key": "", "llm_name": mdlnm, "api_base": ""}
  113. if not model_config:
  114. if mdlnm == "flag-embedding":
  115. model_config = {"llm_factory": "Tongyi-Qianwen", "api_key": "", "llm_name": llm_name, "api_base": ""}
  116. else:
  117. if not mdlnm:
  118. raise LookupError(f"Type of {llm_type} model is not set.")
  119. raise LookupError("Model({}) not authorized".format(mdlnm))
  120. return model_config
  121. @classmethod
  122. @DB.connection_context()
  123. def model_instance(cls, tenant_id, llm_type, llm_name=None, lang="Chinese", **kwargs):
  124. model_config = TenantLLMService.get_model_config(tenant_id, llm_type, llm_name)
  125. if llm_type == LLMType.EMBEDDING.value:
  126. if model_config["llm_factory"] not in EmbeddingModel:
  127. return
  128. return EmbeddingModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  129. if llm_type == LLMType.RERANK:
  130. if model_config["llm_factory"] not in RerankModel:
  131. return
  132. return RerankModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  133. if llm_type == LLMType.IMAGE2TEXT.value:
  134. if model_config["llm_factory"] not in CvModel:
  135. return
  136. return CvModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], lang, base_url=model_config["api_base"], **kwargs)
  137. if llm_type == LLMType.CHAT.value:
  138. if model_config["llm_factory"] not in ChatModel:
  139. return
  140. return ChatModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"], **kwargs)
  141. if llm_type == LLMType.SPEECH2TEXT:
  142. if model_config["llm_factory"] not in Seq2txtModel:
  143. return
  144. 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"])
  145. if llm_type == LLMType.TTS:
  146. if model_config["llm_factory"] not in TTSModel:
  147. return
  148. return TTSModel[model_config["llm_factory"]](
  149. model_config["api_key"],
  150. model_config["llm_name"],
  151. base_url=model_config["api_base"],
  152. )
  153. @classmethod
  154. @DB.connection_context()
  155. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  156. e, tenant = TenantService.get_by_id(tenant_id)
  157. if not e:
  158. logging.error(f"Tenant not found: {tenant_id}")
  159. return 0
  160. llm_map = {
  161. LLMType.EMBEDDING.value: tenant.embd_id if not llm_name else llm_name,
  162. LLMType.SPEECH2TEXT.value: tenant.asr_id,
  163. LLMType.IMAGE2TEXT.value: tenant.img2txt_id,
  164. LLMType.CHAT.value: tenant.llm_id if not llm_name else llm_name,
  165. LLMType.RERANK.value: tenant.rerank_id if not llm_name else llm_name,
  166. LLMType.TTS.value: tenant.tts_id if not llm_name else llm_name,
  167. }
  168. mdlnm = llm_map.get(llm_type)
  169. if mdlnm is None:
  170. logging.error(f"LLM type error: {llm_type}")
  171. return 0
  172. llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(mdlnm)
  173. try:
  174. num = (
  175. cls.model.update(used_tokens=cls.model.used_tokens + used_tokens)
  176. .where(cls.model.tenant_id == tenant_id, cls.model.llm_name == llm_name, cls.model.llm_factory == llm_factory if llm_factory else True)
  177. .execute()
  178. )
  179. except Exception:
  180. logging.exception("TenantLLMService.increase_usage got exception,Failed to update used_tokens for tenant_id=%s, llm_name=%s", tenant_id, llm_name)
  181. return 0
  182. return num
  183. @classmethod
  184. @DB.connection_context()
  185. def get_openai_models(cls):
  186. 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()
  187. return list(objs)
  188. @staticmethod
  189. def llm_id2llm_type(llm_id: str) ->str|None:
  190. llm_id, *_ = TenantLLMService.split_model_name_and_factory(llm_id)
  191. llm_factories = settings.FACTORY_LLM_INFOS
  192. for llm_factory in llm_factories:
  193. for llm in llm_factory["llm"]:
  194. if llm_id == llm["llm_name"]:
  195. return llm["model_type"].split(",")[-1]
  196. class LLMBundle:
  197. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese", **kwargs):
  198. self.tenant_id = tenant_id
  199. self.llm_type = llm_type
  200. self.llm_name = llm_name
  201. self.mdl = TenantLLMService.model_instance(tenant_id, llm_type, llm_name, lang=lang, **kwargs)
  202. assert self.mdl, "Can't find model for {}/{}/{}".format(tenant_id, llm_type, llm_name)
  203. model_config = TenantLLMService.get_model_config(tenant_id, llm_type, llm_name)
  204. self.max_length = model_config.get("max_tokens", 8192)
  205. self.is_tools = model_config.get("is_tools", False)
  206. self.verbose_tool_use = kwargs.get("verbose_tool_use")
  207. langfuse_keys = TenantLangfuseService.filter_by_tenant(tenant_id=tenant_id)
  208. if langfuse_keys:
  209. langfuse = Langfuse(public_key=langfuse_keys.public_key, secret_key=langfuse_keys.secret_key, host=langfuse_keys.host)
  210. if langfuse.auth_check():
  211. self.langfuse = langfuse
  212. self.trace = self.langfuse.trace(name=f"{self.llm_type}-{self.llm_name}")
  213. else:
  214. self.langfuse = None
  215. def bind_tools(self, toolcall_session, tools):
  216. if not self.is_tools:
  217. logging.warning(f"Model {self.llm_name} does not support tool call, but you have assigned one or more tools to it!")
  218. return
  219. self.mdl.bind_tools(toolcall_session, tools)
  220. def encode(self, texts: list):
  221. if self.langfuse:
  222. generation = self.trace.generation(name="encode", model=self.llm_name, input={"texts": texts})
  223. embeddings, used_tokens = self.mdl.encode(texts)
  224. llm_name = getattr(self, "llm_name", None)
  225. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens, llm_name):
  226. logging.error("LLMBundle.encode can't update token usage for {}/EMBEDDING used_tokens: {}".format(self.tenant_id, used_tokens))
  227. if self.langfuse:
  228. generation.end(usage_details={"total_tokens": used_tokens})
  229. return embeddings, used_tokens
  230. def encode_queries(self, query: str):
  231. if self.langfuse:
  232. generation = self.trace.generation(name="encode_queries", model=self.llm_name, input={"query": query})
  233. emd, used_tokens = self.mdl.encode_queries(query)
  234. llm_name = getattr(self, "llm_name", None)
  235. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens, llm_name):
  236. logging.error("LLMBundle.encode_queries can't update token usage for {}/EMBEDDING used_tokens: {}".format(self.tenant_id, used_tokens))
  237. if self.langfuse:
  238. generation.end(usage_details={"total_tokens": used_tokens})
  239. return emd, used_tokens
  240. def similarity(self, query: str, texts: list):
  241. if self.langfuse:
  242. generation = self.trace.generation(name="similarity", model=self.llm_name, input={"query": query, "texts": texts})
  243. sim, used_tokens = self.mdl.similarity(query, texts)
  244. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens):
  245. logging.error("LLMBundle.similarity can't update token usage for {}/RERANK used_tokens: {}".format(self.tenant_id, used_tokens))
  246. if self.langfuse:
  247. generation.end(usage_details={"total_tokens": used_tokens})
  248. return sim, used_tokens
  249. def describe(self, image, max_tokens=300):
  250. if self.langfuse:
  251. generation = self.trace.generation(name="describe", metadata={"model": self.llm_name})
  252. txt, used_tokens = self.mdl.describe(image)
  253. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens):
  254. logging.error("LLMBundle.describe can't update token usage for {}/IMAGE2TEXT used_tokens: {}".format(self.tenant_id, used_tokens))
  255. if self.langfuse:
  256. generation.end(output={"output": txt}, usage_details={"total_tokens": used_tokens})
  257. return txt
  258. def describe_with_prompt(self, image, prompt):
  259. if self.langfuse:
  260. generation = self.trace.generation(name="describe_with_prompt", metadata={"model": self.llm_name, "prompt": prompt})
  261. txt, used_tokens = self.mdl.describe_with_prompt(image, prompt)
  262. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens):
  263. logging.error("LLMBundle.describe can't update token usage for {}/IMAGE2TEXT used_tokens: {}".format(self.tenant_id, used_tokens))
  264. if self.langfuse:
  265. generation.end(output={"output": txt}, usage_details={"total_tokens": used_tokens})
  266. return txt
  267. def transcription(self, audio):
  268. if self.langfuse:
  269. generation = self.trace.generation(name="transcription", metadata={"model": self.llm_name})
  270. txt, used_tokens = self.mdl.transcription(audio)
  271. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens):
  272. logging.error("LLMBundle.transcription can't update token usage for {}/SEQUENCE2TXT used_tokens: {}".format(self.tenant_id, used_tokens))
  273. if self.langfuse:
  274. generation.end(output={"output": txt}, usage_details={"total_tokens": used_tokens})
  275. return txt
  276. def tts(self, text: str) -> None:
  277. if self.langfuse:
  278. span = self.trace.span(name="tts", input={"text": text})
  279. for chunk in self.mdl.tts(text):
  280. if isinstance(chunk, int):
  281. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, chunk, self.llm_name):
  282. logging.error("LLMBundle.tts can't update token usage for {}/TTS".format(self.tenant_id))
  283. return
  284. yield chunk
  285. if self.langfuse:
  286. span.end()
  287. def _remove_reasoning_content(self, txt: str) -> str:
  288. first_think_start = txt.find("<think>")
  289. if first_think_start == -1:
  290. return txt
  291. last_think_end = txt.rfind("</think>")
  292. if last_think_end == -1:
  293. return txt
  294. if last_think_end < first_think_start:
  295. return txt
  296. return txt[last_think_end + len("</think>") :]
  297. def chat(self, system: str, history: list, gen_conf: dict={}, **kwargs) -> str:
  298. if self.langfuse:
  299. generation = self.trace.generation(name="chat", model=self.llm_name, input={"system": system, "history": history})
  300. chat_partial = partial(self.mdl.chat, system, history, gen_conf)
  301. if self.is_tools and self.mdl.is_tools:
  302. chat_partial = partial(self.mdl.chat_with_tools, system, history, gen_conf)
  303. txt, used_tokens = chat_partial(**kwargs)
  304. txt = self._remove_reasoning_content(txt)
  305. if not self.verbose_tool_use:
  306. txt = re.sub(r"<tool_call>.*?</tool_call>", "", txt, flags=re.DOTALL)
  307. if isinstance(txt, int) and not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens, self.llm_name):
  308. logging.error("LLMBundle.chat can't update token usage for {}/CHAT llm_name: {}, used_tokens: {}".format(self.tenant_id, self.llm_name, used_tokens))
  309. if self.langfuse:
  310. generation.end(output={"output": txt}, usage_details={"total_tokens": used_tokens})
  311. return txt
  312. def chat_streamly(self, system: str, history: list, gen_conf: dict={}, **kwargs):
  313. if self.langfuse:
  314. generation = self.trace.generation(name="chat_streamly", model=self.llm_name, input={"system": system, "history": history})
  315. ans = ""
  316. chat_partial = partial(self.mdl.chat_streamly, system, history, gen_conf)
  317. total_tokens = 0
  318. if self.is_tools and self.mdl.is_tools:
  319. chat_partial = partial(self.mdl.chat_streamly_with_tools, system, history, gen_conf)
  320. for txt in chat_partial(**kwargs):
  321. if isinstance(txt, int):
  322. total_tokens = txt
  323. if self.langfuse:
  324. generation.end(output={"output": ans})
  325. break
  326. if txt.endswith("</think>"):
  327. ans = ans.rstrip("</think>")
  328. if not self.verbose_tool_use:
  329. txt = re.sub(r"<tool_call>.*?</tool_call>", "", txt, flags=re.DOTALL)
  330. ans += txt
  331. yield ans
  332. if total_tokens > 0:
  333. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, txt, self.llm_name):
  334. logging.error("LLMBundle.chat_streamly can't update token usage for {}/CHAT llm_name: {}, content: {}".format(self.tenant_id, self.llm_name, txt))