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 4.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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 import duplicate_name
  19. from api.db.services.llm_service import LLMFactoriesService, TenantLLMService, LLMService
  20. from api.db.services.user_service import TenantService, UserTenantService
  21. from api.utils.api_utils import server_error_response, get_data_error_result, validate_request
  22. from api.utils import get_uuid, get_format_time
  23. from api.db import StatusEnum, UserTenantRole, LLMType
  24. from api.db.services.knowledgebase_service import KnowledgebaseService
  25. from api.db.db_models import Knowledgebase, TenantLLM
  26. from api.settings import stat_logger, RetCode
  27. from api.utils.api_utils import get_json_result
  28. from rag.llm import EmbeddingModel, CvModel, ChatModel
  29. @manager.route('/factories', methods=['GET'])
  30. @login_required
  31. def factories():
  32. try:
  33. fac = LLMFactoriesService.get_all()
  34. return get_json_result(data=[f.to_dict() for f in fac])
  35. except Exception as e:
  36. return server_error_response(e)
  37. @manager.route('/set_api_key', methods=['POST'])
  38. @login_required
  39. @validate_request("llm_factory", "api_key")
  40. def set_api_key():
  41. req = request.json
  42. # test if api key works
  43. msg = ""
  44. for llm in LLMService.query(fid=req["llm_factory"]):
  45. if llm.model_type == LLMType.EMBEDDING.value:
  46. mdl = EmbeddingModel[req["llm_factory"]](
  47. req["api_key"], llm.llm_name)
  48. try:
  49. arr, tc = mdl.encode(["Test if the api key is available"])
  50. if len(arr[0]) == 0 or tc ==0: raise Exception("Fail")
  51. except Exception as e:
  52. msg += f"\nFail to access embedding model({llm.llm_name}) using this api key."
  53. elif llm.model_type == LLMType.CHAT.value:
  54. mdl = ChatModel[req["llm_factory"]](
  55. req["api_key"], llm.llm_name)
  56. try:
  57. m, tc = mdl.chat(None, [{"role": "user", "content": "Hello! How are you doing!"}], {"temperature": 0.9})
  58. if not tc: raise Exception(m)
  59. except Exception as e:
  60. msg += f"\nFail to access model({llm.llm_name}) using this api key." + str(e)
  61. if msg: return get_data_error_result(retmsg=msg)
  62. llm = {
  63. "tenant_id": current_user.id,
  64. "llm_factory": req["llm_factory"],
  65. "api_key": req["api_key"]
  66. }
  67. for n in ["model_type", "llm_name"]:
  68. if n in req: llm[n] = req[n]
  69. TenantLLMService.filter_update([TenantLLM.tenant_id==llm["tenant_id"], TenantLLM.llm_factory==llm["llm_factory"]], llm)
  70. return get_json_result(data=True)
  71. @manager.route('/my_llms', methods=['GET'])
  72. @login_required
  73. def my_llms():
  74. try:
  75. objs = TenantLLMService.get_my_llms(current_user.id)
  76. return get_json_result(data=objs)
  77. except Exception as e:
  78. return server_error_response(e)
  79. @manager.route('/list', methods=['GET'])
  80. @login_required
  81. def list():
  82. model_type = request.args.get("model_type")
  83. try:
  84. objs = TenantLLMService.query(tenant_id=current_user.id)
  85. facts = set([o.to_dict()["llm_factory"] for o in objs if o.api_key])
  86. llms = LLMService.get_all()
  87. llms = [m.to_dict() for m in llms if m.status == StatusEnum.VALID.value]
  88. for m in llms:
  89. m["available"] = m["fid"] in facts
  90. res = {}
  91. for m in llms:
  92. if model_type and m["model_type"] != model_type: continue
  93. if m["fid"] not in res: res[m["fid"]] = []
  94. res[m["fid"]].append(m)
  95. return get_json_result(data=res)
  96. except Exception as e:
  97. return server_error_response(e)