app_model_config_service.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. import re
  2. import uuid
  3. from core.constant import llm_constant
  4. from models.account import Account
  5. from services.dataset_service import DatasetService
  6. from services.errors.account import NoPermissionError
  7. class AppModelConfigService:
  8. @staticmethod
  9. def is_dataset_exists(account: Account, dataset_id: str) -> bool:
  10. # verify if the dataset ID exists
  11. dataset = DatasetService.get_dataset(dataset_id)
  12. if not dataset:
  13. return False
  14. if dataset.tenant_id != account.current_tenant_id:
  15. return False
  16. return True
  17. @staticmethod
  18. def validate_model_completion_params(cp: dict, model_name: str) -> dict:
  19. # 6. model.completion_params
  20. if not isinstance(cp, dict):
  21. raise ValueError("model.completion_params must be of object type")
  22. # max_tokens
  23. if 'max_tokens' not in cp:
  24. cp["max_tokens"] = 512
  25. if not isinstance(cp["max_tokens"], int) or cp["max_tokens"] <= 0 or cp["max_tokens"] > \
  26. llm_constant.max_context_token_length[model_name]:
  27. raise ValueError(
  28. "max_tokens must be an integer greater than 0 and not exceeding the maximum value of the corresponding model")
  29. # temperature
  30. if 'temperature' not in cp:
  31. cp["temperature"] = 1
  32. if not isinstance(cp["temperature"], (float, int)) or cp["temperature"] < 0 or cp["temperature"] > 2:
  33. raise ValueError("temperature must be a float between 0 and 2")
  34. # top_p
  35. if 'top_p' not in cp:
  36. cp["top_p"] = 1
  37. if not isinstance(cp["top_p"], (float, int)) or cp["top_p"] < 0 or cp["top_p"] > 2:
  38. raise ValueError("top_p must be a float between 0 and 2")
  39. # presence_penalty
  40. if 'presence_penalty' not in cp:
  41. cp["presence_penalty"] = 0
  42. if not isinstance(cp["presence_penalty"], (float, int)) or cp["presence_penalty"] < -2 or cp["presence_penalty"] > 2:
  43. raise ValueError("presence_penalty must be a float between -2 and 2")
  44. # presence_penalty
  45. if 'frequency_penalty' not in cp:
  46. cp["frequency_penalty"] = 0
  47. if not isinstance(cp["frequency_penalty"], (float, int)) or cp["frequency_penalty"] < -2 or cp["frequency_penalty"] > 2:
  48. raise ValueError("frequency_penalty must be a float between -2 and 2")
  49. # Filter out extra parameters
  50. filtered_cp = {
  51. "max_tokens": cp["max_tokens"],
  52. "temperature": cp["temperature"],
  53. "top_p": cp["top_p"],
  54. "presence_penalty": cp["presence_penalty"],
  55. "frequency_penalty": cp["frequency_penalty"]
  56. }
  57. return filtered_cp
  58. @staticmethod
  59. def validate_configuration(account: Account, config: dict, mode: str) -> dict:
  60. # opening_statement
  61. if 'opening_statement' not in config or not config["opening_statement"]:
  62. config["opening_statement"] = ""
  63. if not isinstance(config["opening_statement"], str):
  64. raise ValueError("opening_statement must be of string type")
  65. # suggested_questions
  66. if 'suggested_questions' not in config or not config["suggested_questions"]:
  67. config["suggested_questions"] = []
  68. if not isinstance(config["suggested_questions"], list):
  69. raise ValueError("suggested_questions must be of list type")
  70. for question in config["suggested_questions"]:
  71. if not isinstance(question, str):
  72. raise ValueError("Elements in suggested_questions list must be of string type")
  73. # suggested_questions_after_answer
  74. if 'suggested_questions_after_answer' not in config or not config["suggested_questions_after_answer"]:
  75. config["suggested_questions_after_answer"] = {
  76. "enabled": False
  77. }
  78. if not isinstance(config["suggested_questions_after_answer"], dict):
  79. raise ValueError("suggested_questions_after_answer must be of dict type")
  80. if "enabled" not in config["suggested_questions_after_answer"] or not config["suggested_questions_after_answer"]["enabled"]:
  81. config["suggested_questions_after_answer"]["enabled"] = False
  82. if not isinstance(config["suggested_questions_after_answer"]["enabled"], bool):
  83. raise ValueError("enabled in suggested_questions_after_answer must be of boolean type")
  84. # more_like_this
  85. if 'more_like_this' not in config or not config["more_like_this"]:
  86. config["more_like_this"] = {
  87. "enabled": False
  88. }
  89. if not isinstance(config["more_like_this"], dict):
  90. raise ValueError("more_like_this must be of dict type")
  91. if "enabled" not in config["more_like_this"] or not config["more_like_this"]["enabled"]:
  92. config["more_like_this"]["enabled"] = False
  93. if not isinstance(config["more_like_this"]["enabled"], bool):
  94. raise ValueError("enabled in more_like_this must be of boolean type")
  95. # model
  96. if 'model' not in config:
  97. raise ValueError("model is required")
  98. if not isinstance(config["model"], dict):
  99. raise ValueError("model must be of object type")
  100. # model.provider
  101. if 'provider' not in config["model"] or config["model"]["provider"] != "openai":
  102. raise ValueError("model.provider must be 'openai'")
  103. # model.name
  104. if 'name' not in config["model"]:
  105. raise ValueError("model.name is required")
  106. if config["model"]["name"] not in llm_constant.models_by_mode[mode]:
  107. raise ValueError("model.name must be in the specified model list")
  108. # model.completion_params
  109. if 'completion_params' not in config["model"]:
  110. raise ValueError("model.completion_params is required")
  111. config["model"]["completion_params"] = AppModelConfigService.validate_model_completion_params(
  112. config["model"]["completion_params"],
  113. config["model"]["name"]
  114. )
  115. # user_input_form
  116. if "user_input_form" not in config or not config["user_input_form"]:
  117. config["user_input_form"] = []
  118. if not isinstance(config["user_input_form"], list):
  119. raise ValueError("user_input_form must be a list of objects")
  120. variables = []
  121. for item in config["user_input_form"]:
  122. key = list(item.keys())[0]
  123. if key not in ["text-input", "select"]:
  124. raise ValueError("Keys in user_input_form list can only be 'text-input' or 'select'")
  125. form_item = item[key]
  126. if 'label' not in form_item:
  127. raise ValueError("label is required in user_input_form")
  128. if not isinstance(form_item["label"], str):
  129. raise ValueError("label in user_input_form must be of string type")
  130. if 'variable' not in form_item:
  131. raise ValueError("variable is required in user_input_form")
  132. if not isinstance(form_item["variable"], str):
  133. raise ValueError("variable in user_input_form must be of string type")
  134. pattern = re.compile(r"^(?!\d)[\u4e00-\u9fa5A-Za-z0-9_\U0001F300-\U0001F64F\U0001F680-\U0001F6FF]{1,100}$")
  135. if pattern.match(form_item["variable"]) is None:
  136. raise ValueError("variable in user_input_form must be a string, "
  137. "and cannot start with a number")
  138. variables.append(form_item["variable"])
  139. if 'required' not in form_item or not form_item["required"]:
  140. form_item["required"] = False
  141. if not isinstance(form_item["required"], bool):
  142. raise ValueError("required in user_input_form must be of boolean type")
  143. if key == "select":
  144. if 'options' not in form_item or not form_item["options"]:
  145. form_item["options"] = []
  146. if not isinstance(form_item["options"], list):
  147. raise ValueError("options in user_input_form must be a list of strings")
  148. if "default" in form_item and form_item['default'] \
  149. and form_item["default"] not in form_item["options"]:
  150. raise ValueError("default value in user_input_form must be in the options list")
  151. # pre_prompt
  152. if "pre_prompt" not in config or not config["pre_prompt"]:
  153. config["pre_prompt"] = ""
  154. if not isinstance(config["pre_prompt"], str):
  155. raise ValueError("pre_prompt must be of string type")
  156. template_vars = re.findall(r"\{\{(\w+)\}\}", config["pre_prompt"])
  157. for var in template_vars:
  158. if var not in variables:
  159. raise ValueError("Template variables in pre_prompt must be defined in user_input_form")
  160. # agent_mode
  161. if "agent_mode" not in config or not config["agent_mode"]:
  162. config["agent_mode"] = {
  163. "enabled": False,
  164. "tools": []
  165. }
  166. if not isinstance(config["agent_mode"], dict):
  167. raise ValueError("agent_mode must be of object type")
  168. if "enabled" not in config["agent_mode"] or not config["agent_mode"]["enabled"]:
  169. config["agent_mode"]["enabled"] = False
  170. if not isinstance(config["agent_mode"]["enabled"], bool):
  171. raise ValueError("enabled in agent_mode must be of boolean type")
  172. if "tools" not in config["agent_mode"] or not config["agent_mode"]["tools"]:
  173. config["agent_mode"]["tools"] = []
  174. if not isinstance(config["agent_mode"]["tools"], list):
  175. raise ValueError("tools in agent_mode must be a list of objects")
  176. for tool in config["agent_mode"]["tools"]:
  177. key = list(tool.keys())[0]
  178. if key not in ["sensitive-word-avoidance", "dataset"]:
  179. raise ValueError("Keys in agent_mode.tools list can only be 'sensitive-word-avoidance' or 'dataset'")
  180. tool_item = tool[key]
  181. if "enabled" not in tool_item or not tool_item["enabled"]:
  182. tool_item["enabled"] = False
  183. if not isinstance(tool_item["enabled"], bool):
  184. raise ValueError("enabled in agent_mode.tools must be of boolean type")
  185. if key == "sensitive-word-avoidance":
  186. if "words" not in tool_item or not tool_item["words"]:
  187. tool_item["words"] = ""
  188. if not isinstance(tool_item["words"], str):
  189. raise ValueError("words in sensitive-word-avoidance must be of string type")
  190. if "canned_response" not in tool_item or not tool_item["canned_response"]:
  191. tool_item["canned_response"] = ""
  192. if not isinstance(tool_item["canned_response"], str):
  193. raise ValueError("canned_response in sensitive-word-avoidance must be of string type")
  194. elif key == "dataset":
  195. if 'id' not in tool_item:
  196. raise ValueError("id is required in dataset")
  197. try:
  198. uuid.UUID(tool_item["id"])
  199. except ValueError:
  200. raise ValueError("id in dataset must be of UUID type")
  201. if not AppModelConfigService.is_dataset_exists(account, tool_item["id"]):
  202. raise ValueError("Dataset ID does not exist, please check your permission.")
  203. # Filter out extra parameters
  204. filtered_config = {
  205. "opening_statement": config["opening_statement"],
  206. "suggested_questions": config["suggested_questions"],
  207. "suggested_questions_after_answer": config["suggested_questions_after_answer"],
  208. "more_like_this": config["more_like_this"],
  209. "model": {
  210. "provider": config["model"]["provider"],
  211. "name": config["model"]["name"],
  212. "completion_params": config["model"]["completion_params"]
  213. },
  214. "user_input_form": config["user_input_form"],
  215. "pre_prompt": config["pre_prompt"],
  216. "agent_mode": config["agent_mode"]
  217. }
  218. return filtered_config