robot.class.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. <?php
  2. if (!defined('IN_ONLINE')) {
  3. exit('Access Denied');
  4. }
  5. /**
  6. * Description of robot
  7. *
  8. * @author Administrator
  9. */
  10. class robot{
  11. private static $_robot;
  12. function __construct() {
  13. }
  14. public static function getInstance() {
  15. global $memory_limit;
  16. $memory_limit = ini_get("memory_limit");
  17. ini_set("memory_limit", '2048M');
  18. if (!self::$_robot) {
  19. $c = __CLASS__;
  20. self::$_robot = new $c;
  21. }
  22. return self::$_robot;
  23. }
  24. public function robot_prompt_configuration() {
  25. $operate = utils::_get('operate');
  26. $operate = strtolower($operate);
  27. if (empty($operate)) {
  28. //查询所有配置信息 目前只有一个表一个数据
  29. $configuration = common::excuteObjectSql("select id, character_name,professional_field,main_tasks,table_name,table_description,
  30. table_structure_configuration,response_rule_configuration,output_format_configuration,fixed_problem_configuration
  31. from public.kln_robot_prompt_configuration where id = 1");
  32. $PromptAndVue = $this->dealPromptFormatAndVue($configuration);
  33. //tableDat-VUE
  34. $tableData = $PromptAndVue["vuedata"]["tableData"];
  35. //stepData -VUE
  36. $stepData = $PromptAndVue["vuedata"]["stepData"];
  37. //formatList -VUE
  38. $formatListType = $PromptAndVue["vuedata"]["formatListType"];
  39. $formatList = $PromptAndVue["vuedata"]["formatList"];
  40. //promptFormat
  41. $promptFormat =$PromptAndVue["promptFormat"];
  42. //获取历史变更记录
  43. $old_configuration = $this->getChangedLog($configuration["id"]);
  44. $id = $configuration['id'];
  45. $character_name = $configuration['character_name'];
  46. $professional_field = $configuration['professional_field'];
  47. $main_tasks = $configuration['main_tasks'];
  48. $table_name = $configuration['table_name'];
  49. $table_description = $configuration['table_description'];
  50. $prompt_summary = array("您是专門从事".$professional_field."的".$character_name."...",
  51. "表名:{".$table_name."}...",
  52. "响应规则,请按以下步骤处理...");
  53. $data = array(
  54. "id"=>$id,
  55. "character_name"=>$character_name,
  56. "professional_field"=>$professional_field,
  57. "main_tasks"=>$main_tasks,
  58. "table_name"=>$table_name,
  59. "table_description"=>$table_description,
  60. "tableData"=>$tableData,
  61. "stepData"=>$stepData,
  62. "formatList"=>$formatList,
  63. "formatListType"=>$formatListType,
  64. "complete_prompt"=>$promptFormat,
  65. "prompt_summary"=>$prompt_summary,
  66. "prompt_log_record"=>$old_configuration
  67. );
  68. $data = utils::arrayRemoveNull($data);
  69. common::echo_json_encode(200,$data);
  70. exit();
  71. }
  72. if ($operate == "save") {
  73. $id =common::check_input($_POST['id']);
  74. $character_name = common::check_input($_POST['role_name']);
  75. $professional_field = common::check_input($_POST['professional_field']);
  76. $main_tasks = common::check_input($_POST['main_tasks']);
  77. $table_name = common::check_input($_POST['table_name']);
  78. $table_description = common::check_input($_POST['table_description']);
  79. $outputvalue = common::check_input($_POST['outputvalue']);
  80. $tableDataList = $_POST['tableDataList'];
  81. $stepData = $_POST['stepData'];
  82. $formatList = $_POST['formatList'];
  83. $table_structure_configuration = common::check_input(json_encode($tableDataList));
  84. $response_rule_configuration = common::check_input(json_encode($stepData));
  85. $output_data = array("output_type"=>$outputvalue,"data"=>$formatList);
  86. $output_format_configuration = common::check_input(json_encode($output_data));
  87. if(empty($id)){
  88. $sql = "INSERT INTO public.kln_robot_prompt_configuration(
  89. character_name, professional_field, main_tasks, table_name,
  90. table_description, table_structure_configuration, response_rule_configuration,
  91. output_format_configuration, created_by, created_time)
  92. VALUES ('$character_name', '$professional_field', '$main_tasks', '$table_name',
  93. '$table_description', '$table_structure_configuration', '$response_rule_configuration',
  94. '$output_format_configuration', '"._getLoginName()."', now());";
  95. }else{
  96. $sql = "update public.kln_robot_prompt_configuration
  97. set character_name = '$character_name',professional_field ='$professional_field', main_tasks = '$main_tasks',
  98. table_name = '$table_name',table_description = '$table_description',
  99. table_structure_configuration = '$table_structure_configuration',
  100. response_rule_configuration = '$response_rule_configuration',
  101. output_format_configuration = '$output_format_configuration'
  102. where id = '$id';";
  103. //插入变更日志记录
  104. $sql .= "INSERT INTO public.kln_robot_prompt_configuration_log(ref_id, character_name, professional_field, main_tasks, table_name,
  105. table_description, table_structure_configuration, response_rule_configuration,
  106. output_format_configuration, created_by, created_time)
  107. VALUES ('$id','$character_name', '$professional_field', '$main_tasks', '$table_name',
  108. '$table_description', '$table_structure_configuration', '$response_rule_configuration',
  109. '$output_format_configuration', '"._getLoginName()."', now());";
  110. }
  111. error_log($sql);
  112. $rs = common::excuteUpdateSql($sql);
  113. if (!$rs) {
  114. $data = array("msg" => "save Error");
  115. } else {
  116. $data = array("msg" => "save Successful");
  117. }
  118. $data = array("msg" => "save Successful");
  119. common::echo_json_encode(200,$data);
  120. exit();
  121. }
  122. if($operate == "preview_propmpt_witout_save"){
  123. $character_name = common::check_input($_POST['role_name']);
  124. $professional_field = common::check_input($_POST['professional_field']);
  125. $main_tasks = common::check_input($_POST['main_tasks']);
  126. $table_name = common::check_input($_POST['table_name']);
  127. $table_description = common::check_input($_POST['table_description']);
  128. $outputvalue = common::check_input($_POST['outputvalue']);
  129. $tableDataList = $_POST['tableDataList'];
  130. $stepData = $_POST['stepData'];
  131. $formatList = $_POST['formatList'];
  132. $table_structure_configuration = common::check_input(json_encode($tableDataList));
  133. $response_rule_configuration = common::check_input(json_encode($stepData));
  134. $output_data = array("output_type"=>$outputvalue,"data"=>$formatList);
  135. $output_format_configuration = common::check_input(json_encode($output_data));
  136. //组合拼接需要的数据
  137. $configuration = array("character_name"=>$character_name,
  138. "professional_field"=>$professional_field,
  139. "main_tasks"=>$main_tasks,
  140. "table_name"=>$table_name,
  141. "table_description"=>$table_description,
  142. "professional_field"=>$professional_field,
  143. "table_structure_configuration"=>$table_structure_configuration,
  144. "response_rule_configuration" =>$response_rule_configuration,
  145. "output_format_configuration" =>$output_format_configuration
  146. );
  147. $PromptAndVue = $this->dealPromptFormatAndVue($configuration);
  148. //promptFormat
  149. $promptFormat =$PromptAndVue["promptFormat"];
  150. $character_name = empty($configuration['character_name']) ? "" :$configuration['character_name'];
  151. $professional_field = empty($configuration['professional_field']) ? "" :$configuration['professional_field'];
  152. $main_tasks = empty($configuration['main_tasks']) ? "" :$configuration['main_tasks'];
  153. $table_name = empty($configuration['table_name']) ? "" :$configuration['table_name'];
  154. $table_description = empty($configuration['table_description']) ? "" :$configuration['table_description'];
  155. $prompt_summary = array("您是专門从事".$professional_field."的".$character_name."...",
  156. "表名:{".$table_name."}...",
  157. "响应规则,请按以下步骤处理...");
  158. $data = array(
  159. "complete_prompt"=>$promptFormat,
  160. "prompt_summary"=>$prompt_summary
  161. );
  162. common::echo_json_encode(200,$data);
  163. exit();
  164. }
  165. if($operate == "test_with_ds_claude"){
  166. $ai_method = $_POST["test_ai_method"];
  167. $systemPrompt = $_POST["prompt"];
  168. $message = $_POST["test_question"];
  169. $model = $ai_method == 'DS' ? "deepseek" : "claude";
  170. //question_date request_time
  171. $request_question_time = date("Y-m-d H:i:s");
  172. $question_time = date("H:i:s");
  173. $item_value = common::excuteOneSql("select item_value from public.config where item = 'AIAPISetting'");
  174. $config = json_decode($item_value,true);
  175. $response = AIClientFactory::create($model, $config[$model], $systemPrompt, $message, $history = []);
  176. $response_time = date("Y-m-d H:i:s");
  177. $input_token = "";
  178. $output_token = "";
  179. $date1 = new DateTime($request_question_time);
  180. $date2 = new DateTime($response_time);
  181. $response_duration = $date2->getTimestamp() - $date1->getTimestamp();
  182. //回答问题类型,在没有超时的情况下,固定:AI回答
  183. $answer_type = "AI回答";
  184. if ($response_duration > 120){
  185. $answer_type = "回答超时";
  186. }
  187. //获取自然序列
  188. $sequence = common::getChatAiSequence();
  189. $name = $ai_method == 'DS' ? "DS" : "CD";
  190. $request_id = "R".$name."".date("Ymd").$sequence;
  191. $question_id = "Q"."".date("Ymd").$sequence;
  192. //处理一下参数
  193. $user_name = common::check_input(_getLoginName());
  194. $user_type = _isApexLogin() ? "employee" : "customer";
  195. //这里的测试,固定写自由文本
  196. $question_type = 'free text';
  197. $question_id = common::check_input($question_id);
  198. $question_content = common::check_input($message);
  199. $answer_type = common::check_input($answer_type);
  200. //记录回答展示给客户的具体内容
  201. $answer = common::check_input(common::getChatAimessage($response['message']));
  202. $ai_model = common::check_input($model);
  203. $input_token = common::check_input($input_token);
  204. $request_content = common::check_input($response['data']);
  205. $ai_response_content = common::check_input($response['full_response']);
  206. $output_token = common::check_input($output_token);
  207. $sql = "INSERT INTO public.kln_robot_chat_log( question_id, user_name, user_type, question_type, question_content,
  208. answer_type, answer, answer_satisfication, answer_duration, question_date,
  209. question_time, request_id, ai_model, request_content, input_token,
  210. ai_response_content, output_token, request_time, response_time,
  211. response_duration)
  212. VALUES ('$question_id', '$user_name', '$user_type', '$question_type', '$question_content',
  213. '$answer_type', '$answer', '', '$response_duration', '$request_question_time',
  214. '$question_time', '$request_id', '$ai_model', '$input_token', '$request_content',
  215. '$ai_response_content', '$output_token', '$request_question_time', '$response_time',
  216. '$response_duration');";
  217. $rs = common::excuteUpdateSql($sql);
  218. if (!$rs) {
  219. $data = array("msg" => "AI Chat Save Error");
  220. common::echo_json_encode(200,$data);
  221. exit();
  222. }
  223. error_log($response['message']);
  224. // $sql ="";
  225. // //用户权限
  226. // $sqlWhere = ' and ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  227. // $sql .= $sqlWhere;
  228. // $rs = common::excuteListSql($sql);
  229. $rs = $response;
  230. common::echo_json_encode(200,$rs);
  231. exit();
  232. }
  233. }
  234. public function dealPromptFormatAndVue($configuration){
  235. //tableDat-VUE
  236. $tableData = array();
  237. $table_structure_text="[";
  238. $table_structure_configuration = json_decode($configuration['table_structure_configuration'],true);
  239. foreach($table_structure_configuration as $tk =>$tv){
  240. $tableData[] = $tv;
  241. $table_structure_text .='{
  242. "name": "'.$tv["name"].'",
  243. "type": "'.$tv["type"].'",
  244. "description": "'.$tv["description"].'",
  245. "exampledata": "'.$tv["exampledata"].'",
  246. }';
  247. if(count($table_structure_configuration)-1 > $tk){
  248. $table_structure_text .=",";
  249. }
  250. $table_structure_text .=common::splicedLlineBreaks();
  251. }
  252. $table_structure_text.="]";
  253. //stepData -VUE
  254. $stepData = array();
  255. $response_rule_text = "";
  256. $response_rule_configuration = json_decode($configuration['response_rule_configuration'],true);
  257. foreach($response_rule_configuration as $rk =>$rv){
  258. $tempTable = array();
  259. $tempTable["description"] = $rv["description"];
  260. $stepData[] = $tempTable;
  261. $response_rule_text .=($rk+1).'.'.$rv["description"];
  262. $response_rule_text .=common::splicedLlineBreaks();
  263. }
  264. //formatList -VUE
  265. $output_format_text = "{";
  266. $output_format_configuration = json_decode($configuration['output_format_configuration'],true);
  267. $formatListType = $output_format_configuration['output_type'];
  268. $formatList = empty($output_format_configuration['data']) ? array(): $output_format_configuration['data'];
  269. foreach($formatList as $ok =>$ov){
  270. $output_format_text .="\"".$ov['name']."\"".": "."\"".$ov['describe']."\"";
  271. $output_format_text .=common::splicedLlineBreaks();
  272. }
  273. $output_format_text .= "}";
  274. $promptFormat = $this->getCompletePromptFormat();
  275. $promptFormat = str_replace('<{professional_field}>', $configuration['character_name'], $promptFormat);
  276. $promptFormat = str_replace('<{character_name}>', $configuration['character_name'], $promptFormat);
  277. $promptFormat = str_replace('<{main_tasks}>', $configuration['main_tasks'], $promptFormat);
  278. $promptFormat = str_replace('<{table}>', $configuration['table_name'], $promptFormat);
  279. $promptFormat = str_replace('<{table_structure_configuration}>', $table_structure_text, $promptFormat);
  280. $promptFormat = str_replace('<{response_rule_configuration}>', $response_rule_text, $promptFormat);
  281. $promptFormat = str_replace('<{number}>', count($response_rule_configuration)+1, $promptFormat);
  282. $promptFormat = str_replace('<{output_type}>', $formatListType, $promptFormat);
  283. $promptFormat = str_replace('<{output_format_configuration}>', $output_format_text, $promptFormat);
  284. return array("vuedata"=>array("tableData"=>$tableData,"stepData"=>$stepData,"formatList"=>$formatList,"formatListType"=>$formatListType),
  285. "promptFormat" =>$promptFormat);
  286. }
  287. public function getChangedLog($id){
  288. $changeLogList = array();
  289. $configurationArr = common::excuteListSql("select id, character_name,professional_field,main_tasks,table_name,table_description,
  290. created_by,TO_CHAR(created_time, 'YYYY-mm-dd HH24:MI:SS') as created_time,
  291. table_structure_configuration,response_rule_configuration,output_format_configuration,fixed_problem_configuration
  292. from public.kln_robot_prompt_configuration_log where ref_id = '$id' order by id desc");
  293. foreach($configurationArr as $ca){
  294. $data = $this->dealPromptFormatAndVue($ca);
  295. $temp =array();
  296. $temp["time"] = $ca['created_time']." Prompt";
  297. $temp["person"] ="提交人:".$ca['created_by'];
  298. $temp["text"] = $data['promptFormat'];
  299. $changeLogList[] = $temp;
  300. }
  301. return $changeLogList;
  302. }
  303. public function getCompletePromptFormat() {
  304. $formatTpl = "
  305. 您是专门从<{professional_field}>的 <{character_name}>,请始终以<{output_type}>格式响应。您的主要任务是<{main_tasks}>
  306. 表名:<{table}>
  307. 表结构: \"columns\": <{table_structure_configuration}>
  308. 响应规则,请按以下步骤处理:
  309. <{response_rule_configuration}>
  310. <{number}>. 请用以下<{output_type}>格式回复:
  311. <{output_format_configuration}>";
  312. return $formatTpl;
  313. }
  314. }
  315. ?>