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_app.py 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  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 flask import request
  17. from flask_login import login_required, current_user
  18. from api.db.services.llm_service import LLMFactoriesService, TenantLLMService, LLMService
  19. from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
  20. from api.db import StatusEnum, LLMType
  21. from api.db.db_models import TenantLLM
  22. from api.utils.api_utils import get_json_result
  23. from rag.llm import EmbeddingModel, ChatModel
  24. @manager.route('/factories', methods=['GET'])
  25. @login_required
  26. def factories():
  27. try:
  28. fac = LLMFactoriesService.get_all()
  29. return get_json_result(data=[f.to_dict() for f in fac])
  30. except Exception as e:
  31. return server_error_response(e)
  32. @manager.route('/set_api_key', methods=['POST'])
  33. @login_required
  34. @validate_request("llm_factory", "api_key")
  35. def set_api_key():
  36. req = request.json
  37. # test if api key works
  38. chat_passed = False
  39. factory = req["llm_factory"]
  40. msg = ""
  41. for llm in LLMService.query(fid=factory):
  42. if llm.model_type == LLMType.EMBEDDING.value:
  43. mdl = EmbeddingModel[factory](
  44. req["api_key"], llm.llm_name, req.get("base_url"))
  45. try:
  46. arr, tc = mdl.encode(["Test if the api key is available"])
  47. if len(arr[0]) == 0 or tc == 0:
  48. raise Exception("Fail")
  49. except Exception as e:
  50. msg += f"\nFail to access embedding model({llm.llm_name}) using this api key." + str(e)
  51. elif not chat_passed and llm.model_type == LLMType.CHAT.value:
  52. mdl = ChatModel[factory](
  53. req["api_key"], llm.llm_name, req.get("base_url"))
  54. try:
  55. m, tc = mdl.chat(None, [{"role": "user", "content": "Hello! How are you doing!"}], {
  56. "temperature": 0.9})
  57. if not tc:
  58. raise Exception(m)
  59. chat_passed = True
  60. except Exception as e:
  61. msg += f"\nFail to access model({llm.llm_name}) using this api key." + str(
  62. e)
  63. if msg:
  64. return get_data_error_result(retmsg=msg)
  65. llm = {
  66. "api_key": req["api_key"]
  67. }
  68. for n in ["model_type", "llm_name"]:
  69. if n in req:
  70. llm[n] = req[n]
  71. if not TenantLLMService.filter_update(
  72. [TenantLLM.tenant_id == current_user.id, TenantLLM.llm_factory == factory], llm):
  73. for llm in LLMService.query(fid=factory):
  74. TenantLLMService.save(
  75. tenant_id=current_user.id,
  76. llm_factory=factory,
  77. llm_name=llm.llm_name,
  78. model_type=llm.model_type,
  79. api_key=req["api_key"],
  80. api_base=req.get("base_url", "")
  81. )
  82. return get_json_result(data=True)
  83. @manager.route('/my_llms', methods=['GET'])
  84. @login_required
  85. def my_llms():
  86. try:
  87. res = {}
  88. for o in TenantLLMService.get_my_llms(current_user.id):
  89. if o["llm_factory"] not in res:
  90. res[o["llm_factory"]] = {
  91. "tags": o["tags"],
  92. "llm": []
  93. }
  94. res[o["llm_factory"]]["llm"].append({
  95. "type": o["model_type"],
  96. "name": o["llm_name"],
  97. "used_token": o["used_tokens"]
  98. })
  99. return get_json_result(data=res)
  100. except Exception as e:
  101. return server_error_response(e)
  102. @manager.route('/list', methods=['GET'])
  103. @login_required
  104. def list():
  105. model_type = request.args.get("model_type")
  106. try:
  107. objs = TenantLLMService.query(tenant_id=current_user.id)
  108. facts = set([o.to_dict()["llm_factory"] for o in objs if o.api_key])
  109. llms = LLMService.get_all()
  110. llms = [m.to_dict()
  111. for m in llms if m.status == StatusEnum.VALID.value]
  112. for m in llms:
  113. m["available"] = m["fid"] in facts or m["llm_name"].lower() == "flag-embedding"
  114. res = {}
  115. for m in llms:
  116. if model_type and m["model_type"] != model_type:
  117. continue
  118. if m["fid"] not in res:
  119. res[m["fid"]] = []
  120. res[m["fid"]].append(m)
  121. return get_json_result(data=res)
  122. except Exception as e:
  123. return server_error_response(e)