您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

llm_app.py 5.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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, base_url=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, base_url=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. "api_base": req.get("base_url", "")
  68. }
  69. for n in ["model_type", "llm_name"]:
  70. if n in req:
  71. llm[n] = req[n]
  72. if not TenantLLMService.filter_update(
  73. [TenantLLM.tenant_id == current_user.id, TenantLLM.llm_factory == factory], llm):
  74. for llm in LLMService.query(fid=factory):
  75. TenantLLMService.save(
  76. tenant_id=current_user.id,
  77. llm_factory=factory,
  78. llm_name=llm.llm_name,
  79. model_type=llm.model_type,
  80. api_key=req["api_key"],
  81. api_base=req.get("base_url", "")
  82. )
  83. return get_json_result(data=True)
  84. @manager.route('/my_llms', methods=['GET'])
  85. @login_required
  86. def my_llms():
  87. try:
  88. res = {}
  89. for o in TenantLLMService.get_my_llms(current_user.id):
  90. if o["llm_factory"] not in res:
  91. res[o["llm_factory"]] = {
  92. "tags": o["tags"],
  93. "llm": []
  94. }
  95. res[o["llm_factory"]]["llm"].append({
  96. "type": o["model_type"],
  97. "name": o["llm_name"],
  98. "used_token": o["used_tokens"]
  99. })
  100. return get_json_result(data=res)
  101. except Exception as e:
  102. return server_error_response(e)
  103. @manager.route('/list', methods=['GET'])
  104. @login_required
  105. def list():
  106. model_type = request.args.get("model_type")
  107. try:
  108. objs = TenantLLMService.query(tenant_id=current_user.id)
  109. facts = set([o.to_dict()["llm_factory"] for o in objs if o.api_key])
  110. llms = LLMService.get_all()
  111. llms = [m.to_dict()
  112. for m in llms if m.status == StatusEnum.VALID.value]
  113. for m in llms:
  114. m["available"] = m["fid"] in facts or m["llm_name"].lower() == "flag-embedding"
  115. res = {}
  116. for m in llms:
  117. if model_type and m["model_type"] != model_type:
  118. continue
  119. if m["fid"] not in res:
  120. res[m["fid"]] = []
  121. res[m["fid"]].append(m)
  122. return get_json_result(data=res)
  123. except Exception as e:
  124. return server_error_response(e)