Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

llm_service.py 6.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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. from api.db.services.user_service import TenantService
  17. from api.settings import database_logger
  18. from rag.llm import EmbeddingModel, CvModel, ChatModel
  19. from api.db import LLMType
  20. from api.db.db_models import DB, UserTenant
  21. from api.db.db_models import LLMFactories, LLM, TenantLLM
  22. from api.db.services.common_service import CommonService
  23. class LLMFactoriesService(CommonService):
  24. model = LLMFactories
  25. class LLMService(CommonService):
  26. model = LLM
  27. class TenantLLMService(CommonService):
  28. model = TenantLLM
  29. @classmethod
  30. @DB.connection_context()
  31. def get_api_key(cls, tenant_id, model_name):
  32. objs = cls.query(tenant_id=tenant_id, llm_name=model_name)
  33. if not objs:
  34. return
  35. return objs[0]
  36. @classmethod
  37. @DB.connection_context()
  38. def get_my_llms(cls, tenant_id):
  39. fields = [
  40. cls.model.llm_factory,
  41. LLMFactories.logo,
  42. LLMFactories.tags,
  43. cls.model.model_type,
  44. cls.model.llm_name,
  45. cls.model.used_tokens
  46. ]
  47. objs = cls.model.select(*fields).join(LLMFactories, on=(cls.model.llm_factory == LLMFactories.name)).where(
  48. cls.model.tenant_id == tenant_id, ~cls.model.api_key.is_null()).dicts()
  49. return list(objs)
  50. @classmethod
  51. @DB.connection_context()
  52. def model_instance(cls, tenant_id, llm_type,
  53. llm_name=None, lang="Chinese"):
  54. e, tenant = TenantService.get_by_id(tenant_id)
  55. if not e:
  56. raise LookupError("Tenant not found")
  57. if llm_type == LLMType.EMBEDDING.value:
  58. mdlnm = tenant.embd_id if not llm_name else llm_name
  59. elif llm_type == LLMType.SPEECH2TEXT.value:
  60. mdlnm = tenant.asr_id
  61. elif llm_type == LLMType.IMAGE2TEXT.value:
  62. mdlnm = tenant.img2txt_id
  63. elif llm_type == LLMType.CHAT.value:
  64. mdlnm = tenant.llm_id if not llm_name else llm_name
  65. else:
  66. assert False, "LLM type error"
  67. model_config = cls.get_api_key(tenant_id, mdlnm)
  68. if model_config: model_config = model_config.to_dict()
  69. if not model_config:
  70. if llm_type == LLMType.EMBEDDING.value:
  71. llm = LLMService.query(llm_name=llm_name)
  72. if llm and llm[0].fid in ["QAnything", "FastEmbed"]:
  73. model_config = {"llm_factory": llm[0].fid, "api_key":"", "llm_name": llm_name, "api_base": ""}
  74. if not model_config: raise LookupError("Model({}) not authorized".format(mdlnm))
  75. if llm_type == LLMType.EMBEDDING.value:
  76. if model_config["llm_factory"] not in EmbeddingModel:
  77. return
  78. return EmbeddingModel[model_config["llm_factory"]](
  79. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  80. if llm_type == LLMType.IMAGE2TEXT.value:
  81. if model_config["llm_factory"] not in CvModel:
  82. return
  83. return CvModel[model_config["llm_factory"]](
  84. model_config["api_key"], model_config["llm_name"], lang,
  85. base_url=model_config["api_base"]
  86. )
  87. if llm_type == LLMType.CHAT.value:
  88. if model_config["llm_factory"] not in ChatModel:
  89. return
  90. return ChatModel[model_config["llm_factory"]](
  91. model_config["api_key"], model_config["llm_name"], base_url=model_config["api_base"])
  92. @classmethod
  93. @DB.connection_context()
  94. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  95. e, tenant = TenantService.get_by_id(tenant_id)
  96. if not e:
  97. raise LookupError("Tenant not found")
  98. if llm_type == LLMType.EMBEDDING.value:
  99. mdlnm = tenant.embd_id
  100. elif llm_type == LLMType.SPEECH2TEXT.value:
  101. mdlnm = tenant.asr_id
  102. elif llm_type == LLMType.IMAGE2TEXT.value:
  103. mdlnm = tenant.img2txt_id
  104. elif llm_type == LLMType.CHAT.value:
  105. mdlnm = tenant.llm_id if not llm_name else llm_name
  106. else:
  107. assert False, "LLM type error"
  108. num = cls.model.update(used_tokens=cls.model.used_tokens + used_tokens)\
  109. .where(cls.model.tenant_id == tenant_id, cls.model.llm_name == mdlnm)\
  110. .execute()
  111. return num
  112. class LLMBundle(object):
  113. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese"):
  114. self.tenant_id = tenant_id
  115. self.llm_type = llm_type
  116. self.llm_name = llm_name
  117. self.mdl = TenantLLMService.model_instance(
  118. tenant_id, llm_type, llm_name, lang=lang)
  119. assert self.mdl, "Can't find mole for {}/{}/{}".format(
  120. tenant_id, llm_type, llm_name)
  121. def encode(self, texts: list, batch_size=32):
  122. emd, used_tokens = self.mdl.encode(texts, batch_size)
  123. if not TenantLLMService.increase_usage(
  124. self.tenant_id, self.llm_type, used_tokens):
  125. database_logger.error(
  126. "Can't update token usage for {}/EMBEDDING".format(self.tenant_id))
  127. return emd, used_tokens
  128. def encode_queries(self, query: str):
  129. emd, used_tokens = self.mdl.encode_queries(query)
  130. if not TenantLLMService.increase_usage(
  131. self.tenant_id, self.llm_type, used_tokens):
  132. database_logger.error(
  133. "Can't update token usage for {}/EMBEDDING".format(self.tenant_id))
  134. return emd, used_tokens
  135. def describe(self, image, max_tokens=300):
  136. txt, used_tokens = self.mdl.describe(image, max_tokens)
  137. if not TenantLLMService.increase_usage(
  138. self.tenant_id, self.llm_type, used_tokens):
  139. database_logger.error(
  140. "Can't update token usage for {}/IMAGE2TEXT".format(self.tenant_id))
  141. return txt
  142. def chat(self, system, history, gen_conf):
  143. txt, used_tokens = self.mdl.chat(system, history, gen_conf)
  144. if TenantLLMService.increase_usage(
  145. self.tenant_id, self.llm_type, used_tokens, self.llm_name):
  146. database_logger.error(
  147. "Can't update token usage for {}/CHAT".format(self.tenant_id))
  148. return txt