app_model_config_service.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  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. # return retriever resource
  105. if 'retriever_resource' not in config or not config["retriever_resource"]:
  106. config["retriever_resource"] = {
  107. "enabled": False
  108. }
  109. if not isinstance(config["retriever_resource"], dict):
  110. raise ValueError("retriever_resource must be of dict type")
  111. if "enabled" not in config["retriever_resource"] or not config["retriever_resource"]["enabled"]:
  112. config["retriever_resource"]["enabled"] = False
  113. if not isinstance(config["retriever_resource"]["enabled"], bool):
  114. raise ValueError("enabled in speech_to_text must be of boolean type")
  115. # more_like_this
  116. if 'more_like_this' not in config or not config["more_like_this"]:
  117. config["more_like_this"] = {
  118. "enabled": False
  119. }
  120. if not isinstance(config["more_like_this"], dict):
  121. raise ValueError("more_like_this must be of dict type")
  122. if "enabled" not in config["more_like_this"] or not config["more_like_this"]["enabled"]:
  123. config["more_like_this"]["enabled"] = False
  124. if not isinstance(config["more_like_this"]["enabled"], bool):
  125. raise ValueError("enabled in more_like_this must be of boolean type")
  126. # sensitive_word_avoidance
  127. if 'sensitive_word_avoidance' not in config or not config["sensitive_word_avoidance"]:
  128. config["sensitive_word_avoidance"] = {
  129. "enabled": False
  130. }
  131. if not isinstance(config["sensitive_word_avoidance"], dict):
  132. raise ValueError("sensitive_word_avoidance must be of dict type")
  133. if "enabled" not in config["sensitive_word_avoidance"] or not config["sensitive_word_avoidance"]["enabled"]:
  134. config["sensitive_word_avoidance"]["enabled"] = False
  135. if not isinstance(config["sensitive_word_avoidance"]["enabled"], bool):
  136. raise ValueError("enabled in sensitive_word_avoidance must be of boolean type")
  137. if "words" not in config["sensitive_word_avoidance"] or not config["sensitive_word_avoidance"]["words"]:
  138. config["sensitive_word_avoidance"]["words"] = ""
  139. if not isinstance(config["sensitive_word_avoidance"]["words"], str):
  140. raise ValueError("words in sensitive_word_avoidance must be of string type")
  141. if "canned_response" not in config["sensitive_word_avoidance"] or not config["sensitive_word_avoidance"]["canned_response"]:
  142. config["sensitive_word_avoidance"]["canned_response"] = ""
  143. if not isinstance(config["sensitive_word_avoidance"]["canned_response"], str):
  144. raise ValueError("canned_response in sensitive_word_avoidance must be of string type")
  145. # model
  146. if 'model' not in config:
  147. raise ValueError("model is required")
  148. if not isinstance(config["model"], dict):
  149. raise ValueError("model must be of object type")
  150. # model.provider
  151. model_provider_names = ModelProviderFactory.get_provider_names()
  152. if 'provider' not in config["model"] or config["model"]["provider"] not in model_provider_names:
  153. raise ValueError(f"model.provider is required and must be in {str(model_provider_names)}")
  154. # model.name
  155. if 'name' not in config["model"]:
  156. raise ValueError("model.name is required")
  157. model_provider = ModelProviderFactory.get_preferred_model_provider(tenant_id, config["model"]["provider"])
  158. if not model_provider:
  159. raise ValueError("model.name must be in the specified model list")
  160. model_list = model_provider.get_supported_model_list(ModelType.TEXT_GENERATION)
  161. model_ids = [m['id'] for m in model_list]
  162. if config["model"]["name"] not in model_ids:
  163. raise ValueError("model.name must be in the specified model list")
  164. # model.completion_params
  165. if 'completion_params' not in config["model"]:
  166. raise ValueError("model.completion_params is required")
  167. config["model"]["completion_params"] = AppModelConfigService.validate_model_completion_params(
  168. config["model"]["completion_params"],
  169. config["model"]["name"]
  170. )
  171. # user_input_form
  172. if "user_input_form" not in config or not config["user_input_form"]:
  173. config["user_input_form"] = []
  174. if not isinstance(config["user_input_form"], list):
  175. raise ValueError("user_input_form must be a list of objects")
  176. variables = []
  177. for item in config["user_input_form"]:
  178. key = list(item.keys())[0]
  179. if key not in ["text-input", "select", "paragraph"]:
  180. raise ValueError("Keys in user_input_form list can only be 'text-input', 'paragraph' or 'select'")
  181. form_item = item[key]
  182. if 'label' not in form_item:
  183. raise ValueError("label is required in user_input_form")
  184. if not isinstance(form_item["label"], str):
  185. raise ValueError("label in user_input_form must be of string type")
  186. if 'variable' not in form_item:
  187. raise ValueError("variable is required in user_input_form")
  188. if not isinstance(form_item["variable"], str):
  189. raise ValueError("variable in user_input_form must be of string type")
  190. pattern = re.compile(r"^(?!\d)[\u4e00-\u9fa5A-Za-z0-9_\U0001F300-\U0001F64F\U0001F680-\U0001F6FF]{1,100}$")
  191. if pattern.match(form_item["variable"]) is None:
  192. raise ValueError("variable in user_input_form must be a string, "
  193. "and cannot start with a number")
  194. variables.append(form_item["variable"])
  195. if 'required' not in form_item or not form_item["required"]:
  196. form_item["required"] = False
  197. if not isinstance(form_item["required"], bool):
  198. raise ValueError("required in user_input_form must be of boolean type")
  199. if key == "select":
  200. if 'options' not in form_item or not form_item["options"]:
  201. form_item["options"] = []
  202. if not isinstance(form_item["options"], list):
  203. raise ValueError("options in user_input_form must be a list of strings")
  204. if "default" in form_item and form_item['default'] \
  205. and form_item["default"] not in form_item["options"]:
  206. raise ValueError("default value in user_input_form must be in the options list")
  207. # pre_prompt
  208. if "pre_prompt" not in config or not config["pre_prompt"]:
  209. config["pre_prompt"] = ""
  210. if not isinstance(config["pre_prompt"], str):
  211. raise ValueError("pre_prompt must be of string type")
  212. template_vars = re.findall(r"\{\{(\w+)\}\}", config["pre_prompt"])
  213. for var in template_vars:
  214. if var not in variables:
  215. raise ValueError("Template variables in pre_prompt must be defined in user_input_form")
  216. # agent_mode
  217. if "agent_mode" not in config or not config["agent_mode"]:
  218. config["agent_mode"] = {
  219. "enabled": False,
  220. "tools": []
  221. }
  222. if not isinstance(config["agent_mode"], dict):
  223. raise ValueError("agent_mode must be of object type")
  224. if "enabled" not in config["agent_mode"] or not config["agent_mode"]["enabled"]:
  225. config["agent_mode"]["enabled"] = False
  226. if not isinstance(config["agent_mode"]["enabled"], bool):
  227. raise ValueError("enabled in agent_mode must be of boolean type")
  228. if "strategy" not in config["agent_mode"] or not config["agent_mode"]["strategy"]:
  229. config["agent_mode"]["strategy"] = PlanningStrategy.ROUTER.value
  230. if config["agent_mode"]["strategy"] not in [member.value for member in list(PlanningStrategy.__members__.values())]:
  231. raise ValueError("strategy in agent_mode must be in the specified strategy list")
  232. if "tools" not in config["agent_mode"] or not config["agent_mode"]["tools"]:
  233. config["agent_mode"]["tools"] = []
  234. if not isinstance(config["agent_mode"]["tools"], list):
  235. raise ValueError("tools in agent_mode must be a list of objects")
  236. for tool in config["agent_mode"]["tools"]:
  237. key = list(tool.keys())[0]
  238. if key not in SUPPORT_TOOLS:
  239. raise ValueError("Keys in agent_mode.tools must be in the specified tool list")
  240. tool_item = tool[key]
  241. if "enabled" not in tool_item or not tool_item["enabled"]:
  242. tool_item["enabled"] = False
  243. if not isinstance(tool_item["enabled"], bool):
  244. raise ValueError("enabled in agent_mode.tools must be of boolean type")
  245. if key == "dataset":
  246. if 'id' not in tool_item:
  247. raise ValueError("id is required in dataset")
  248. try:
  249. uuid.UUID(tool_item["id"])
  250. except ValueError:
  251. raise ValueError("id in dataset must be of UUID type")
  252. if not AppModelConfigService.is_dataset_exists(account, tool_item["id"]):
  253. raise ValueError("Dataset ID does not exist, please check your permission.")
  254. # Filter out extra parameters
  255. filtered_config = {
  256. "opening_statement": config["opening_statement"],
  257. "suggested_questions": config["suggested_questions"],
  258. "suggested_questions_after_answer": config["suggested_questions_after_answer"],
  259. "speech_to_text": config["speech_to_text"],
  260. "retriever_resource": config["retriever_resource"],
  261. "more_like_this": config["more_like_this"],
  262. "sensitive_word_avoidance": config["sensitive_word_avoidance"],
  263. "model": {
  264. "provider": config["model"]["provider"],
  265. "name": config["model"]["name"],
  266. "completion_params": config["model"]["completion_params"]
  267. },
  268. "user_input_form": config["user_input_form"],
  269. "pre_prompt": config["pre_prompt"],
  270. "agent_mode": config["agent_mode"]
  271. }
  272. return filtered_config