Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

llm_service.py 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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
  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 not model_config:
  69. raise LookupError("Model({}) not authorized".format(mdlnm))
  70. model_config = model_config.to_dict()
  71. if llm_type == LLMType.EMBEDDING.value:
  72. if model_config["llm_factory"] not in EmbeddingModel:
  73. return
  74. return EmbeddingModel[model_config["llm_factory"]](
  75. model_config["api_key"], model_config["llm_name"], model_config["api_base"])
  76. if llm_type == LLMType.IMAGE2TEXT.value:
  77. if model_config["llm_factory"] not in CvModel:
  78. return
  79. return CvModel[model_config["llm_factory"]](
  80. model_config["api_key"], model_config["llm_name"], lang,
  81. base_url=model_config["api_base"]
  82. )
  83. if llm_type == LLMType.CHAT.value:
  84. if model_config["llm_factory"] not in ChatModel:
  85. return
  86. return ChatModel[model_config["llm_factory"]](
  87. model_config["api_key"], model_config["llm_name"], model_config["api_base"])
  88. @classmethod
  89. @DB.connection_context()
  90. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  91. e, tenant = TenantService.get_by_id(tenant_id)
  92. if not e:
  93. raise LookupError("Tenant not found")
  94. if llm_type == LLMType.EMBEDDING.value:
  95. mdlnm = tenant.embd_id
  96. elif llm_type == LLMType.SPEECH2TEXT.value:
  97. mdlnm = tenant.asr_id
  98. elif llm_type == LLMType.IMAGE2TEXT.value:
  99. mdlnm = tenant.img2txt_id
  100. elif llm_type == LLMType.CHAT.value:
  101. mdlnm = tenant.llm_id if not llm_name else llm_name
  102. else:
  103. assert False, "LLM type error"
  104. num = cls.model.update(used_tokens=cls.model.used_tokens + used_tokens)\
  105. .where(cls.model.tenant_id == tenant_id, cls.model.llm_name == mdlnm)\
  106. .execute()
  107. return num
  108. class LLMBundle(object):
  109. def __init__(self, tenant_id, llm_type, llm_name=None, lang="Chinese"):
  110. self.tenant_id = tenant_id
  111. self.llm_type = llm_type
  112. self.llm_name = llm_name
  113. self.mdl = TenantLLMService.model_instance(
  114. tenant_id, llm_type, llm_name, lang=lang)
  115. assert self.mdl, "Can't find mole for {}/{}/{}".format(
  116. tenant_id, llm_type, llm_name)
  117. def encode(self, texts: list, batch_size=32):
  118. emd, used_tokens = self.mdl.encode(texts, batch_size)
  119. if TenantLLMService.increase_usage(
  120. self.tenant_id, self.llm_type, used_tokens):
  121. database_logger.error(
  122. "Can't update token usage for {}/EMBEDDING".format(self.tenant_id))
  123. return emd, used_tokens
  124. def encode_queries(self, query: str):
  125. emd, used_tokens = self.mdl.encode_queries(query)
  126. if TenantLLMService.increase_usage(
  127. self.tenant_id, self.llm_type, used_tokens):
  128. database_logger.error(
  129. "Can't update token usage for {}/EMBEDDING".format(self.tenant_id))
  130. return emd, used_tokens
  131. def describe(self, image, max_tokens=300):
  132. txt, used_tokens = self.mdl.describe(image, max_tokens)
  133. if not TenantLLMService.increase_usage(
  134. self.tenant_id, self.llm_type, used_tokens):
  135. database_logger.error(
  136. "Can't update token usage for {}/IMAGE2TEXT".format(self.tenant_id))
  137. return txt
  138. def chat(self, system, history, gen_conf):
  139. txt, used_tokens = self.mdl.chat(system, history, gen_conf)
  140. if TenantLLMService.increase_usage(
  141. self.tenant_id, self.llm_type, used_tokens, self.llm_name):
  142. database_logger.error(
  143. "Can't update token usage for {}/CHAT".format(self.tenant_id))
  144. return txt