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 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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 not model_config: # for some cases seems fid mismatch
  88. model_config = cls.get_api_key(tenant_id, mdlnm)
  89. if model_config:
  90. model_config = model_config.to_dict()
  91. llm = LLMService.query(llm_name=mdlnm) if not fid else LLMService.query(llm_name=mdlnm, fid=fid)
  92. if not llm and fid: # for some cases seems fid mismatch
  93. llm = LLMService.query(llm_name=mdlnm)
  94. if llm:
  95. model_config["is_tools"] = llm[0].is_tools
  96. if not model_config:
  97. if llm_type in [LLMType.EMBEDDING, LLMType.RERANK]:
  98. llm = LLMService.query(llm_name=mdlnm) if not fid else LLMService.query(llm_name=mdlnm, fid=fid)
  99. if llm and llm[0].fid in ["Youdao", "FastEmbed", "BAAI"]:
  100. model_config = {"llm_factory": llm[0].fid, "api_key": "", "llm_name": mdlnm, "api_base": ""}
  101. if not model_config:
  102. if mdlnm == "flag-embedding":
  103. model_config = {"llm_factory": "Tongyi-Qianwen", "api_key": "", "llm_name": llm_name, "api_base": ""}
  104. else:
  105. if not mdlnm:
  106. raise LookupError(f"Type of {llm_type} model is not set.")
  107. raise LookupError("Model({}) not authorized".format(mdlnm))
  108. return model_config
  109. @classmethod
  110. @DB.connection_context()
  111. def model_instance(cls, tenant_id, llm_type, llm_name=None, lang="Chinese"):
  112. model_config = TenantLLMService.get_model_config(tenant_id, llm_type, llm_name)
  113. if llm_type == LLMType.EMBEDDING.value:
  114. if model_config["llm_factory"] not in EmbeddingModel:
  115. return
  116. return EmbeddingModel[model_config["llm_factory"]](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"]](model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  121. if llm_type == LLMType.IMAGE2TEXT.value:
  122. if model_config["llm_factory"] not in CvModel:
  123. return
  124. return CvModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], lang, base_url=model_config["api_base"])
  125. if llm_type == LLMType.CHAT.value:
  126. if model_config["llm_factory"] not in ChatModel:
  127. return
  128. return ChatModel[model_config["llm_factory"]](model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  129. if llm_type == LLMType.SPEECH2TEXT:
  130. if model_config["llm_factory"] not in Seq2txtModel:
  131. return
  132. 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"])
  133. if llm_type == LLMType.TTS:
  134. if model_config["llm_factory"] not in TTSModel:
  135. return
  136. return TTSModel[model_config["llm_factory"]](
  137. model_config["api_key"],
  138. model_config["llm_name"],
  139. base_url=model_config["api_base"],
  140. )
  141. @classmethod
  142. @DB.connection_context()
  143. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  144. e, tenant = TenantService.get_by_id(tenant_id)
  145. if not e:
  146. logging.error(f"Tenant not found: {tenant_id}")
  147. return 0
  148. llm_map = {
  149. LLMType.EMBEDDING.value: tenant.embd_id,
  150. LLMType.SPEECH2TEXT.value: tenant.asr_id,
  151. LLMType.IMAGE2TEXT.value: tenant.img2txt_id,
  152. LLMType.CHAT.value: tenant.llm_id if not llm_name else llm_name,
  153. LLMType.RERANK.value: tenant.rerank_id if not llm_name else llm_name,
  154. LLMType.TTS.value: tenant.tts_id if not llm_name else llm_name,
  155. }
  156. mdlnm = llm_map.get(llm_type)
  157. if mdlnm is None:
  158. logging.error(f"LLM type error: {llm_type}")
  159. return 0
  160. llm_name, llm_factory = TenantLLMService.split_model_name_and_factory(mdlnm)
  161. try:
  162. num = (
  163. cls.model.update(used_tokens=cls.model.used_tokens + used_tokens)
  164. .where(cls.model.tenant_id == tenant_id, cls.model.llm_name == llm_name, cls.model.llm_factory == llm_factory if llm_factory else True)
  165. .execute()
  166. )
  167. except Exception:
  168. logging.exception("TenantLLMService.increase_usage got exception,Failed to update used_tokens for tenant_id=%s, llm_name=%s", tenant_id, llm_name)
  169. return 0
  170. return num
  171. @classmethod
  172. @DB.connection_context()
  173. def get_openai_models(cls):
  174. 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()
  175. return list(objs)
  176. class LLMBundle:
  177. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese"):
  178. self.tenant_id = tenant_id
  179. self.llm_type = llm_type
  180. self.llm_name = llm_name
  181. self.mdl = TenantLLMService.model_instance(tenant_id, llm_type, llm_name, lang=lang)
  182. assert self.mdl, "Can't find model for {}/{}/{}".format(tenant_id, llm_type, llm_name)
  183. model_config = TenantLLMService.get_model_config(tenant_id, llm_type, llm_name)
  184. self.max_length = model_config.get("max_tokens", 8192)
  185. self.is_tools = model_config.get("is_tools", False)
  186. langfuse_keys = TenantLangfuseService.filter_by_tenant(tenant_id=tenant_id)
  187. if langfuse_keys:
  188. langfuse = Langfuse(public_key=langfuse_keys.public_key, secret_key=langfuse_keys.secret_key, host=langfuse_keys.host)
  189. if langfuse.auth_check():
  190. self.langfuse = langfuse
  191. self.trace = self.langfuse.trace(name=f"{self.llm_type}-{self.llm_name}")
  192. else:
  193. self.langfuse = None
  194. def bind_tools(self, toolcall_session, tools):
  195. if not self.is_tools:
  196. logging.warning(f"Model {self.llm_name} does not support tool call, but you have assigned one or more tools to it!")
  197. return
  198. self.mdl.bind_tools(toolcall_session, tools)
  199. def encode(self, texts: list):
  200. if self.langfuse:
  201. generation = self.trace.generation(name="encode", model=self.llm_name, input={"texts": texts})
  202. embeddings, used_tokens = self.mdl.encode(texts)
  203. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens):
  204. logging.error("LLMBundle.encode can't update token usage for {}/EMBEDDING used_tokens: {}".format(self.tenant_id, used_tokens))
  205. if self.langfuse:
  206. generation.end(usage_details={"total_tokens": used_tokens})
  207. return embeddings, used_tokens
  208. def encode_queries(self, query: str):
  209. if self.langfuse:
  210. generation = self.trace.generation(name="encode_queries", model=self.llm_name, input={"query": query})
  211. emd, used_tokens = self.mdl.encode_queries(query)
  212. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens):
  213. logging.error("LLMBundle.encode_queries can't update token usage for {}/EMBEDDING used_tokens: {}".format(self.tenant_id, used_tokens))
  214. if self.langfuse:
  215. generation.end(usage_details={"total_tokens": used_tokens})
  216. return emd, used_tokens
  217. def similarity(self, query: str, texts: list):
  218. if self.langfuse:
  219. generation = self.trace.generation(name="similarity", model=self.llm_name, input={"query": query, "texts": texts})
  220. sim, used_tokens = self.mdl.similarity(query, texts)
  221. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens):
  222. logging.error("LLMBundle.similarity can't update token usage for {}/RERANK used_tokens: {}".format(self.tenant_id, used_tokens))
  223. if self.langfuse:
  224. generation.end(usage_details={"total_tokens": used_tokens})
  225. return sim, used_tokens
  226. def describe(self, image, max_tokens=300):
  227. if self.langfuse:
  228. generation = self.trace.generation(name="describe", metadata={"model": self.llm_name})
  229. txt, used_tokens = self.mdl.describe(image)
  230. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens):
  231. logging.error("LLMBundle.describe can't update token usage for {}/IMAGE2TEXT used_tokens: {}".format(self.tenant_id, used_tokens))
  232. if self.langfuse:
  233. generation.end(output={"output": txt}, usage_details={"total_tokens": used_tokens})
  234. return txt
  235. def describe_with_prompt(self, image, prompt):
  236. if self.langfuse:
  237. generation = self.trace.generation(name="describe_with_prompt", metadata={"model": self.llm_name, "prompt": prompt})
  238. txt, used_tokens = self.mdl.describe_with_prompt(image, prompt)
  239. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens):
  240. logging.error("LLMBundle.describe can't update token usage for {}/IMAGE2TEXT used_tokens: {}".format(self.tenant_id, used_tokens))
  241. if self.langfuse:
  242. generation.end(output={"output": txt}, usage_details={"total_tokens": used_tokens})
  243. return txt
  244. def transcription(self, audio):
  245. if self.langfuse:
  246. generation = self.trace.generation(name="transcription", metadata={"model": self.llm_name})
  247. txt, used_tokens = self.mdl.transcription(audio)
  248. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens):
  249. logging.error("LLMBundle.transcription can't update token usage for {}/SEQUENCE2TXT used_tokens: {}".format(self.tenant_id, used_tokens))
  250. if self.langfuse:
  251. generation.end(output={"output": txt}, usage_details={"total_tokens": used_tokens})
  252. return txt
  253. def tts(self, text):
  254. if self.langfuse:
  255. span = self.trace.span(name="tts", input={"text": text})
  256. for chunk in self.mdl.tts(text):
  257. if isinstance(chunk, int):
  258. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, chunk, self.llm_name):
  259. logging.error("LLMBundle.tts can't update token usage for {}/TTS".format(self.tenant_id))
  260. return
  261. yield chunk
  262. if self.langfuse:
  263. span.end()
  264. def _remove_reasoning_content(self, txt: str) -> str:
  265. first_think_start = txt.find("<think>")
  266. if first_think_start == -1:
  267. return txt
  268. last_think_end = txt.rfind("</think>")
  269. if last_think_end == -1:
  270. return txt
  271. if last_think_end < first_think_start:
  272. return txt
  273. return txt[last_think_end + len("</think>") :]
  274. def chat(self, system, history, gen_conf):
  275. if self.langfuse:
  276. generation = self.trace.generation(name="chat", model=self.llm_name, input={"system": system, "history": history})
  277. chat = self.mdl.chat
  278. if self.is_tools and self.mdl.is_tools:
  279. chat = self.mdl.chat_with_tools
  280. txt, used_tokens = chat(system, history, gen_conf)
  281. txt = self._remove_reasoning_content(txt)
  282. if isinstance(txt, int) and not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens, self.llm_name):
  283. logging.error("LLMBundle.chat can't update token usage for {}/CHAT llm_name: {}, used_tokens: {}".format(self.tenant_id, self.llm_name, used_tokens))
  284. if self.langfuse:
  285. generation.end(output={"output": txt}, usage_details={"total_tokens": used_tokens})
  286. return txt
  287. def chat_streamly(self, system, history, gen_conf):
  288. if self.langfuse:
  289. generation = self.trace.generation(name="chat_streamly", model=self.llm_name, input={"system": system, "history": history})
  290. ans = ""
  291. chat_streamly = self.mdl.chat_streamly
  292. total_tokens = 0
  293. if self.is_tools and self.mdl.is_tools:
  294. chat_streamly = self.mdl.chat_streamly_with_tools
  295. for txt in chat_streamly(system, history, gen_conf):
  296. if isinstance(txt, int):
  297. total_tokens = txt
  298. if self.langfuse:
  299. generation.end(output={"output": ans})
  300. break
  301. if txt.endswith("</think>"):
  302. ans = ans.rstrip("</think>")
  303. ans += txt
  304. yield ans
  305. if total_tokens > 0:
  306. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, txt, self.llm_name):
  307. logging.error("LLMBundle.chat_streamly can't update token usage for {}/CHAT llm_name: {}, content: {}".format(self.tenant_id, self.llm_name, txt))