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

llm_service.py 6.2KB

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