app_model_config_service.py 15 KB

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