app_model_config_service.py 19 KB

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