app_model_config_service.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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, ModelMode
  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. # temperature
  28. if 'temperature' not in cp:
  29. cp["temperature"] = 1
  30. # top_p
  31. if 'top_p' not in cp:
  32. cp["top_p"] = 1
  33. # presence_penalty
  34. if 'presence_penalty' not in cp:
  35. cp["presence_penalty"] = 0
  36. # presence_penalty
  37. if 'frequency_penalty' not in cp:
  38. cp["frequency_penalty"] = 0
  39. # stop
  40. if 'stop' not in cp:
  41. cp["stop"] = []
  42. elif not isinstance(cp["stop"], list):
  43. raise ValueError("stop in model.completion_params must be of list type")
  44. # Filter out extra parameters
  45. filtered_cp = {
  46. "max_tokens": cp["max_tokens"],
  47. "temperature": cp["temperature"],
  48. "top_p": cp["top_p"],
  49. "presence_penalty": cp["presence_penalty"],
  50. "frequency_penalty": cp["frequency_penalty"],
  51. "stop": cp["stop"]
  52. }
  53. return filtered_cp
  54. @staticmethod
  55. def validate_configuration(tenant_id: str, account: Account, config: dict, mode: str) -> dict:
  56. # opening_statement
  57. if 'opening_statement' not in config or not config["opening_statement"]:
  58. config["opening_statement"] = ""
  59. if not isinstance(config["opening_statement"], str):
  60. raise ValueError("opening_statement must be of string type")
  61. # suggested_questions
  62. if 'suggested_questions' not in config or not config["suggested_questions"]:
  63. config["suggested_questions"] = []
  64. if not isinstance(config["suggested_questions"], list):
  65. raise ValueError("suggested_questions must be of list type")
  66. for question in config["suggested_questions"]:
  67. if not isinstance(question, str):
  68. raise ValueError("Elements in suggested_questions list must be of string type")
  69. # suggested_questions_after_answer
  70. if 'suggested_questions_after_answer' not in config or not config["suggested_questions_after_answer"]:
  71. config["suggested_questions_after_answer"] = {
  72. "enabled": False
  73. }
  74. if not isinstance(config["suggested_questions_after_answer"], dict):
  75. raise ValueError("suggested_questions_after_answer must be of dict type")
  76. if "enabled" not in config["suggested_questions_after_answer"] or not config["suggested_questions_after_answer"]["enabled"]:
  77. config["suggested_questions_after_answer"]["enabled"] = False
  78. if not isinstance(config["suggested_questions_after_answer"]["enabled"], bool):
  79. raise ValueError("enabled in suggested_questions_after_answer must be of boolean type")
  80. # speech_to_text
  81. if 'speech_to_text' not in config or not config["speech_to_text"]:
  82. config["speech_to_text"] = {
  83. "enabled": False
  84. }
  85. if not isinstance(config["speech_to_text"], dict):
  86. raise ValueError("speech_to_text must be of dict type")
  87. if "enabled" not in config["speech_to_text"] or not config["speech_to_text"]["enabled"]:
  88. config["speech_to_text"]["enabled"] = False
  89. if not isinstance(config["speech_to_text"]["enabled"], bool):
  90. raise ValueError("enabled in speech_to_text must be of boolean type")
  91. # return retriever resource
  92. if 'retriever_resource' not in config or not config["retriever_resource"]:
  93. config["retriever_resource"] = {
  94. "enabled": False
  95. }
  96. if not isinstance(config["retriever_resource"], dict):
  97. raise ValueError("retriever_resource must be of dict type")
  98. if "enabled" not in config["retriever_resource"] or not config["retriever_resource"]["enabled"]:
  99. config["retriever_resource"]["enabled"] = False
  100. if not isinstance(config["retriever_resource"]["enabled"], bool):
  101. raise ValueError("enabled in speech_to_text must be of boolean type")
  102. # more_like_this
  103. if 'more_like_this' not in config or not config["more_like_this"]:
  104. config["more_like_this"] = {
  105. "enabled": False
  106. }
  107. if not isinstance(config["more_like_this"], dict):
  108. raise ValueError("more_like_this must be of dict type")
  109. if "enabled" not in config["more_like_this"] or not config["more_like_this"]["enabled"]:
  110. config["more_like_this"]["enabled"] = False
  111. if not isinstance(config["more_like_this"]["enabled"], bool):
  112. raise ValueError("enabled in more_like_this must be of boolean type")
  113. # sensitive_word_avoidance
  114. if 'sensitive_word_avoidance' not in config or not config["sensitive_word_avoidance"]:
  115. config["sensitive_word_avoidance"] = {
  116. "enabled": False
  117. }
  118. if not isinstance(config["sensitive_word_avoidance"], dict):
  119. raise ValueError("sensitive_word_avoidance must be of dict type")
  120. if "enabled" not in config["sensitive_word_avoidance"] or not config["sensitive_word_avoidance"]["enabled"]:
  121. config["sensitive_word_avoidance"]["enabled"] = False
  122. if not isinstance(config["sensitive_word_avoidance"]["enabled"], bool):
  123. raise ValueError("enabled in sensitive_word_avoidance must be of boolean type")
  124. if "words" not in config["sensitive_word_avoidance"] or not config["sensitive_word_avoidance"]["words"]:
  125. config["sensitive_word_avoidance"]["words"] = ""
  126. if not isinstance(config["sensitive_word_avoidance"]["words"], str):
  127. raise ValueError("words in sensitive_word_avoidance must be of string type")
  128. if "canned_response" not in config["sensitive_word_avoidance"] or not config["sensitive_word_avoidance"]["canned_response"]:
  129. config["sensitive_word_avoidance"]["canned_response"] = ""
  130. if not isinstance(config["sensitive_word_avoidance"]["canned_response"], str):
  131. raise ValueError("canned_response in sensitive_word_avoidance must be of string type")
  132. # model
  133. if 'model' not in config:
  134. raise ValueError("model is required")
  135. if not isinstance(config["model"], dict):
  136. raise ValueError("model must be of object type")
  137. # model.provider
  138. model_provider_names = ModelProviderFactory.get_provider_names()
  139. if 'provider' not in config["model"] or config["model"]["provider"] not in model_provider_names:
  140. raise ValueError(f"model.provider is required and must be in {str(model_provider_names)}")
  141. # model.name
  142. if 'name' not in config["model"]:
  143. raise ValueError("model.name is required")
  144. model_provider = ModelProviderFactory.get_preferred_model_provider(tenant_id, config["model"]["provider"])
  145. if not model_provider:
  146. raise ValueError("model.name must be in the specified model list")
  147. model_list = model_provider.get_supported_model_list(ModelType.TEXT_GENERATION)
  148. model_ids = [m['id'] for m in model_list]
  149. if config["model"]["name"] not in model_ids:
  150. raise ValueError("model.name must be in the specified model list")
  151. # model.mode
  152. if 'mode' not in config['model'] or not config['model']["mode"]:
  153. config['model']["mode"] = ""
  154. # model.completion_params
  155. if 'completion_params' not in config["model"]:
  156. raise ValueError("model.completion_params is required")
  157. config["model"]["completion_params"] = AppModelConfigService.validate_model_completion_params(
  158. config["model"]["completion_params"],
  159. config["model"]["name"]
  160. )
  161. # user_input_form
  162. if "user_input_form" not in config or not config["user_input_form"]:
  163. config["user_input_form"] = []
  164. if not isinstance(config["user_input_form"], list):
  165. raise ValueError("user_input_form must be a list of objects")
  166. variables = []
  167. for item in config["user_input_form"]:
  168. key = list(item.keys())[0]
  169. if key not in ["text-input", "select", "paragraph"]:
  170. raise ValueError("Keys in user_input_form list can only be 'text-input', 'paragraph' or 'select'")
  171. form_item = item[key]
  172. if 'label' not in form_item:
  173. raise ValueError("label is required in user_input_form")
  174. if not isinstance(form_item["label"], str):
  175. raise ValueError("label in user_input_form must be of string type")
  176. if 'variable' not in form_item:
  177. raise ValueError("variable is required in user_input_form")
  178. if not isinstance(form_item["variable"], str):
  179. raise ValueError("variable in user_input_form must be of string type")
  180. pattern = re.compile(r"^(?!\d)[\u4e00-\u9fa5A-Za-z0-9_\U0001F300-\U0001F64F\U0001F680-\U0001F6FF]{1,100}$")
  181. if pattern.match(form_item["variable"]) is None:
  182. raise ValueError("variable in user_input_form must be a string, "
  183. "and cannot start with a number")
  184. variables.append(form_item["variable"])
  185. if 'required' not in form_item or not form_item["required"]:
  186. form_item["required"] = False
  187. if not isinstance(form_item["required"], bool):
  188. raise ValueError("required in user_input_form must be of boolean type")
  189. if key == "select":
  190. if 'options' not in form_item or not form_item["options"]:
  191. form_item["options"] = []
  192. if not isinstance(form_item["options"], list):
  193. raise ValueError("options in user_input_form must be a list of strings")
  194. if "default" in form_item and form_item['default'] \
  195. and form_item["default"] not in form_item["options"]:
  196. raise ValueError("default value in user_input_form must be in the options list")
  197. # pre_prompt
  198. if "pre_prompt" not in config or not config["pre_prompt"]:
  199. config["pre_prompt"] = ""
  200. if not isinstance(config["pre_prompt"], str):
  201. raise ValueError("pre_prompt must be of string type")
  202. template_vars = re.findall(r"\{\{(\w+)\}\}", config["pre_prompt"])
  203. for var in template_vars:
  204. if var not in variables:
  205. raise ValueError("Template variables in pre_prompt must be defined in user_input_form")
  206. # agent_mode
  207. if "agent_mode" not in config or not config["agent_mode"]:
  208. config["agent_mode"] = {
  209. "enabled": False,
  210. "tools": []
  211. }
  212. if not isinstance(config["agent_mode"], dict):
  213. raise ValueError("agent_mode must be of object type")
  214. if "enabled" not in config["agent_mode"] or not config["agent_mode"]["enabled"]:
  215. config["agent_mode"]["enabled"] = False
  216. if not isinstance(config["agent_mode"]["enabled"], bool):
  217. raise ValueError("enabled in agent_mode must be of boolean type")
  218. if "strategy" not in config["agent_mode"] or not config["agent_mode"]["strategy"]:
  219. config["agent_mode"]["strategy"] = PlanningStrategy.ROUTER.value
  220. if config["agent_mode"]["strategy"] not in [member.value for member in list(PlanningStrategy.__members__.values())]:
  221. raise ValueError("strategy in agent_mode must be in the specified strategy list")
  222. if "tools" not in config["agent_mode"] or not config["agent_mode"]["tools"]:
  223. config["agent_mode"]["tools"] = []
  224. if not isinstance(config["agent_mode"]["tools"], list):
  225. raise ValueError("tools in agent_mode must be a list of objects")
  226. for tool in config["agent_mode"]["tools"]:
  227. key = list(tool.keys())[0]
  228. if key not in SUPPORT_TOOLS:
  229. raise ValueError("Keys in agent_mode.tools must be in the specified tool list")
  230. tool_item = tool[key]
  231. if "enabled" not in tool_item or not tool_item["enabled"]:
  232. tool_item["enabled"] = False
  233. if not isinstance(tool_item["enabled"], bool):
  234. raise ValueError("enabled in agent_mode.tools must be of boolean type")
  235. if key == "dataset":
  236. if 'id' not in tool_item:
  237. raise ValueError("id is required in dataset")
  238. try:
  239. uuid.UUID(tool_item["id"])
  240. except ValueError:
  241. raise ValueError("id in dataset must be of UUID type")
  242. if not AppModelConfigService.is_dataset_exists(account, tool_item["id"]):
  243. raise ValueError("Dataset ID does not exist, please check your permission.")
  244. # dataset_query_variable
  245. AppModelConfigService.is_dataset_query_variable_valid(config, mode)
  246. # advanced prompt validation
  247. AppModelConfigService.is_advanced_prompt_valid(config, mode)
  248. # Filter out extra parameters
  249. filtered_config = {
  250. "opening_statement": config["opening_statement"],
  251. "suggested_questions": config["suggested_questions"],
  252. "suggested_questions_after_answer": config["suggested_questions_after_answer"],
  253. "speech_to_text": config["speech_to_text"],
  254. "retriever_resource": config["retriever_resource"],
  255. "more_like_this": config["more_like_this"],
  256. "sensitive_word_avoidance": config["sensitive_word_avoidance"],
  257. "model": {
  258. "provider": config["model"]["provider"],
  259. "name": config["model"]["name"],
  260. "mode": config['model']["mode"],
  261. "completion_params": config["model"]["completion_params"]
  262. },
  263. "user_input_form": config["user_input_form"],
  264. "dataset_query_variable": config.get('dataset_query_variable'),
  265. "pre_prompt": config["pre_prompt"],
  266. "agent_mode": config["agent_mode"],
  267. "prompt_type": config["prompt_type"],
  268. "chat_prompt_config": config["chat_prompt_config"],
  269. "completion_prompt_config": config["completion_prompt_config"],
  270. "dataset_configs": config["dataset_configs"]
  271. }
  272. return filtered_config
  273. @staticmethod
  274. def is_dataset_query_variable_valid(config: dict, mode: str) -> None:
  275. # Only check when mode is completion
  276. if mode != 'completion':
  277. return
  278. agent_mode = config.get("agent_mode", {})
  279. tools = agent_mode.get("tools", [])
  280. dataset_exists = "dataset" in str(tools)
  281. dataset_query_variable = config.get("dataset_query_variable")
  282. if dataset_exists and not dataset_query_variable:
  283. raise ValueError("Dataset query variable is required when dataset is exist")
  284. @staticmethod
  285. def is_advanced_prompt_valid(config: dict, app_mode: str) -> None:
  286. # prompt_type
  287. if 'prompt_type' not in config or not config["prompt_type"]:
  288. config["prompt_type"] = "simple"
  289. if config['prompt_type'] not in ['simple', 'advanced']:
  290. raise ValueError("prompt_type must be in ['simple', 'advanced']")
  291. # chat_prompt_config
  292. if 'chat_prompt_config' not in config or not config["chat_prompt_config"]:
  293. config["chat_prompt_config"] = {}
  294. if not isinstance(config["chat_prompt_config"], dict):
  295. raise ValueError("chat_prompt_config must be of object type")
  296. # completion_prompt_config
  297. if 'completion_prompt_config' not in config or not config["completion_prompt_config"]:
  298. config["completion_prompt_config"] = {}
  299. if not isinstance(config["completion_prompt_config"], dict):
  300. raise ValueError("completion_prompt_config must be of object type")
  301. # dataset_configs
  302. if 'dataset_configs' not in config or not config["dataset_configs"]:
  303. config["dataset_configs"] = {"top_k": 2, "score_threshold": {"enable": False}}
  304. if not isinstance(config["dataset_configs"], dict):
  305. raise ValueError("dataset_configs must be of object type")
  306. if config['prompt_type'] == 'advanced':
  307. if not config['chat_prompt_config'] and not config['completion_prompt_config']:
  308. raise ValueError("chat_prompt_config or completion_prompt_config is required when prompt_type is advanced")
  309. if config['model']["mode"] not in ['chat', 'completion']:
  310. raise ValueError("model.mode must be in ['chat', 'completion'] when prompt_type is advanced")
  311. if app_mode == 'chat' and config['model']["mode"] == ModelMode.COMPLETION.value:
  312. user_prefix = config['completion_prompt_config']['conversation_histories_role']['user_prefix']
  313. assistant_prefix = config['completion_prompt_config']['conversation_histories_role']['assistant_prefix']
  314. if not user_prefix:
  315. config['completion_prompt_config']['conversation_histories_role']['user_prefix'] = 'Human'
  316. if not assistant_prefix:
  317. config['completion_prompt_config']['conversation_histories_role']['assistant_prefix'] = 'Assistant'