app_model_config_service.py 13 KB

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