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.

llm_service.py 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  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. objs = cls.model.select(*fields).join(LLMFactories, on=(cls.model.llm_factory == LLMFactories.name)).where(
  46. cls.model.tenant_id == tenant_id).dicts()
  47. return list(objs)
  48. @classmethod
  49. @DB.connection_context()
  50. def model_instance(cls, tenant_id, llm_type, llm_name=None):
  51. e, tenant = TenantService.get_by_id(tenant_id)
  52. if not e:
  53. raise LookupError("Tenant not found")
  54. if llm_type == LLMType.EMBEDDING.value:
  55. mdlnm = tenant.embd_id
  56. elif llm_type == LLMType.SPEECH2TEXT.value:
  57. mdlnm = tenant.asr_id
  58. elif llm_type == LLMType.IMAGE2TEXT.value:
  59. mdlnm = tenant.img2txt_id
  60. elif llm_type == LLMType.CHAT.value:
  61. mdlnm = tenant.llm_id if not llm_name else llm_name
  62. else:
  63. assert False, "LLM type error"
  64. model_config = cls.get_api_key(tenant_id, mdlnm)
  65. if not model_config:
  66. raise LookupError("Model({}) not authorized".format(mdlnm))
  67. model_config = model_config.to_dict()
  68. if llm_type == LLMType.EMBEDDING.value:
  69. if model_config["llm_factory"] not in EmbeddingModel:
  70. return
  71. return EmbeddingModel[model_config["llm_factory"]](
  72. model_config["api_key"], model_config["llm_name"])
  73. if llm_type == LLMType.IMAGE2TEXT.value:
  74. if model_config["llm_factory"] not in CvModel:
  75. return
  76. return CvModel[model_config["llm_factory"]](
  77. model_config["api_key"], model_config["llm_name"])
  78. if llm_type == LLMType.CHAT.value:
  79. if model_config["llm_factory"] not in ChatModel:
  80. return
  81. return ChatModel[model_config["llm_factory"]](
  82. model_config["api_key"], model_config["llm_name"])
  83. @classmethod
  84. @DB.connection_context()
  85. def increase_usage(cls, tenant_id, llm_type, used_tokens, llm_name=None):
  86. e, tenant = TenantService.get_by_id(tenant_id)
  87. if not e:
  88. raise LookupError("Tenant not found")
  89. if llm_type == LLMType.EMBEDDING.value:
  90. mdlnm = tenant.embd_id
  91. elif llm_type == LLMType.SPEECH2TEXT.value:
  92. mdlnm = tenant.asr_id
  93. elif llm_type == LLMType.IMAGE2TEXT.value:
  94. mdlnm = tenant.img2txt_id
  95. elif llm_type == LLMType.CHAT.value:
  96. mdlnm = tenant.llm_id if not llm_name else llm_name
  97. else:
  98. assert False, "LLM type error"
  99. num = cls.model.update(used_tokens=cls.model.used_tokens + used_tokens)\
  100. .where(cls.model.tenant_id == tenant_id, cls.model.llm_name == mdlnm)\
  101. .execute()
  102. return num
  103. class LLMBundle(object):
  104. def __init__(self, tenant_id, llm_type, llm_name=None):
  105. self.tenant_id = tenant_id
  106. self.llm_type = llm_type
  107. self.llm_name = llm_name
  108. self.mdl = TenantLLMService.model_instance(tenant_id, llm_type, llm_name)
  109. assert self.mdl, "Can't find mole for {}/{}/{}".format(tenant_id, llm_type, llm_name)
  110. def encode(self, texts: list, batch_size=32):
  111. emd, used_tokens = self.mdl.encode(texts, batch_size)
  112. if TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens):
  113. database_logger.error("Can't update token usage for {}/EMBEDDING".format(self.tenant_id))
  114. return emd, used_tokens
  115. def encode_queries(self, query: str):
  116. emd, used_tokens = self.mdl.encode_queries(query)
  117. if TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens):
  118. database_logger.error("Can't update token usage for {}/EMBEDDING".format(self.tenant_id))
  119. return emd, used_tokens
  120. def describe(self, image, max_tokens=300):
  121. txt, used_tokens = self.mdl.describe(image, max_tokens)
  122. if not TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens):
  123. database_logger.error("Can't update token usage for {}/IMAGE2TEXT".format(self.tenant_id))
  124. return txt
  125. def chat(self, system, history, gen_conf):
  126. txt, used_tokens = self.mdl.chat(system, history, gen_conf)
  127. if TenantLLMService.increase_usage(self.tenant_id, self.llm_type, used_tokens, self.llm_name):
  128. database_logger.error("Can't update token usage for {}/CHAT".format(self.tenant_id))
  129. return txt