robot.class.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  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_chat() {
  25. $operate = utils::_get('operate');
  26. $operate = strtolower($operate);
  27. if (empty($operate)) {
  28. $column = column::getInstance()->getDisplayColumn('Robot_Chat_Search');
  29. $OperationTableColumns = column::getInstance()->tableColumns('Robot_Chat_Search',$column);
  30. $data['OperationTableColumns'] = $OperationTableColumns;
  31. common::echo_json_encode(200,$data);
  32. exit();
  33. }
  34. if ($operate == "search") {
  35. //$this->_operation_search();
  36. }
  37. if ($operate == "excel") {
  38. $sql = common::deCode($_POST ['tmp_search'], 'D');
  39. $sql = substr($sql, 0, strripos($sql, " limit"));
  40. if(!empty($sql)){
  41. $rss = common::excuteListSql($sql);
  42. }
  43. foreach($rss as $key =>$val){
  44. $rss[$key]['Operation Time'] = $rss[$key]['_operation_time'];
  45. }
  46. common::echo_json_encode(200,array("msg"=>"success","Data" => $rss));
  47. exit;
  48. }
  49. }
  50. public function robot_prompt_configuration() {
  51. $operate = utils::_get('operate');
  52. $operate = strtolower($operate);
  53. if (empty($operate)) {
  54. //查询所有配置信息 目前只有一个表一个数据
  55. $configuration = common::excuteObjectSql("select id, character_name,professional_field,main_tasks,table_name,table_description,
  56. table_structure_configuration,response_rule_configuration,output_format_configuration,fixed_problem_configuration
  57. from public.kln_robot_prompt_configuration where id = 1");
  58. $PromptAndVue = $this->dealPromptFormatAndVue($configuration);
  59. //tableDat-VUE
  60. $tableData = $PromptAndVue["vuedata"]["tableData"];
  61. //stepData -VUE
  62. $stepData = $PromptAndVue["vuedata"]["stepData"];
  63. //formatList -VUE
  64. $formatListType = $PromptAndVue["vuedata"]["formatListType"];
  65. $formatList = $PromptAndVue["vuedata"]["formatList"];
  66. //promptFormat
  67. $promptFormat =$PromptAndVue["promptFormat"];
  68. //获取历史变更记录
  69. $old_configuration = $this->getChangedLog($configuration["id"]);
  70. $id = $configuration['id'];
  71. $character_name = $configuration['character_name'];
  72. $professional_field = $configuration['professional_field'];
  73. $main_tasks = $configuration['main_tasks'];
  74. $table_name = $configuration['table_name'];
  75. $table_description = $configuration['table_description'];
  76. $prompt_summary = array("您是专門从事".$professional_field."的".$character_name."...",
  77. "表名:{".$table_name."}...",
  78. "响应规则,请按以下步骤处理...");
  79. $data = array(
  80. "id"=>$id,
  81. "character_name"=>$character_name,
  82. "professional_field"=>$professional_field,
  83. "main_tasks"=>$main_tasks,
  84. "table_name"=>$table_name,
  85. "table_description"=>$table_description,
  86. "tableData"=>$tableData,
  87. "stepData"=>$stepData,
  88. "formatList"=>$formatList,
  89. "formatListType"=>$formatListType,
  90. "complete_prompt"=>$promptFormat,
  91. "prompt_summary"=>$prompt_summary,
  92. "prompt_log_record"=>$old_configuration
  93. );
  94. $data = utils::arrayRemoveNull($data);
  95. common::echo_json_encode(200,$data);
  96. exit();
  97. }
  98. if ($operate == "save") {
  99. $id =common::check_input($_POST['id']);
  100. $character_name = common::check_input($_POST['role_name']);
  101. $professional_field = common::check_input($_POST['professional_field']);
  102. $main_tasks = common::check_input($_POST['main_tasks']);
  103. $table_name = common::check_input($_POST['table_name']);
  104. $table_description = common::check_input($_POST['table_description']);
  105. $outputvalue = common::check_input($_POST['outputvalue']);
  106. $tableDataList = $_POST['tableDataList'];
  107. $stepData = $_POST['stepData'];
  108. $formatList = $_POST['formatList'];
  109. $table_structure_configuration = common::check_input(json_encode($tableDataList));
  110. $response_rule_configuration = common::check_input(json_encode($stepData));
  111. $output_data = array("output_type"=>$outputvalue,"data"=>$formatList);
  112. $output_format_configuration = common::check_input(json_encode($output_data));
  113. if(empty($id)){
  114. $sql = "INSERT INTO public.kln_robot_prompt_configuration(
  115. character_name, professional_field, main_tasks, table_name,
  116. table_description, table_structure_configuration, response_rule_configuration,
  117. output_format_configuration, created_by, created_time)
  118. VALUES ('$character_name', '$professional_field', '$main_tasks', '$table_name',
  119. '$table_description', '$table_structure_configuration', '$response_rule_configuration',
  120. '$output_format_configuration', '"._getLoginName()."', now());";
  121. }else{
  122. $sql = "update public.kln_robot_prompt_configuration
  123. set character_name = '$character_name',professional_field ='$professional_field', main_tasks = '$main_tasks',
  124. table_name = '$table_name',table_description = '$table_description',
  125. table_structure_configuration = '$table_structure_configuration',
  126. response_rule_configuration = '$response_rule_configuration',
  127. output_format_configuration = '$output_format_configuration'
  128. where id = '$id';";
  129. //插入变更日志记录
  130. $sql .= "INSERT INTO public.kln_robot_prompt_configuration_log(ref_id, character_name, professional_field, main_tasks, table_name,
  131. table_description, table_structure_configuration, response_rule_configuration,
  132. output_format_configuration, created_by, created_time)
  133. VALUES ('$id','$character_name', '$professional_field', '$main_tasks', '$table_name',
  134. '$table_description', '$table_structure_configuration', '$response_rule_configuration',
  135. '$output_format_configuration', '"._getLoginName()."', now());";
  136. }
  137. error_log($sql);
  138. $rs = common::excuteUpdateSql($sql);
  139. if (!$rs) {
  140. $data = array("msg" => "save Error");
  141. } else {
  142. $data = array("msg" => "save Successful");
  143. }
  144. $data = array("msg" => "save Successful");
  145. common::echo_json_encode(200,$data);
  146. exit();
  147. }
  148. if($operate == "preview_propmpt_witout_save"){
  149. $character_name = common::check_input($_POST['role_name']);
  150. $professional_field = common::check_input($_POST['professional_field']);
  151. $main_tasks = common::check_input($_POST['main_tasks']);
  152. $table_name = common::check_input($_POST['table_name']);
  153. $table_description = common::check_input($_POST['table_description']);
  154. $outputvalue = common::check_input($_POST['outputvalue']);
  155. $tableDataList = $_POST['tableDataList'];
  156. $stepData = $_POST['stepData'];
  157. $formatList = $_POST['formatList'];
  158. $table_structure_configuration = common::check_input(json_encode($tableDataList));
  159. $response_rule_configuration = common::check_input(json_encode($stepData));
  160. $output_data = array("output_type"=>$outputvalue,"data"=>$formatList);
  161. $output_format_configuration = common::check_input(json_encode($output_data));
  162. //组合拼接需要的数据
  163. $configuration = array("character_name"=>$character_name,
  164. "professional_field"=>$professional_field,
  165. "main_tasks"=>$main_tasks,
  166. "table_name"=>$table_name,
  167. "table_description"=>$table_description,
  168. "professional_field"=>$professional_field,
  169. "table_structure_configuration"=>$table_structure_configuration,
  170. "response_rule_configuration" =>$response_rule_configuration,
  171. "output_format_configuration" =>$output_format_configuration
  172. );
  173. $PromptAndVue = $this->dealPromptFormatAndVue($configuration);
  174. //promptFormat
  175. $promptFormat =$PromptAndVue["promptFormat"];
  176. $character_name = empty($configuration['character_name']) ? "" :$configuration['character_name'];
  177. $professional_field = empty($configuration['professional_field']) ? "" :$configuration['professional_field'];
  178. $main_tasks = empty($configuration['main_tasks']) ? "" :$configuration['main_tasks'];
  179. $table_name = empty($configuration['table_name']) ? "" :$configuration['table_name'];
  180. $table_description = empty($configuration['table_description']) ? "" :$configuration['table_description'];
  181. $prompt_summary = array("您是专門从事".$professional_field."的".$character_name."...",
  182. "表名:{".$table_name."}...",
  183. "响应规则,请按以下步骤处理...");
  184. $data = array(
  185. "complete_prompt"=>$promptFormat,
  186. "prompt_summary"=>$prompt_summary
  187. );
  188. common::echo_json_encode(200,$data);
  189. exit();
  190. }
  191. if($operate == "test_with_ds_claude"){
  192. $ai_method = $_POST["test_ai_method"];
  193. $systemPrompt = $_POST["prompt"];
  194. $message = $_POST["test_question"];
  195. $model = $ai_method == 'DS' ? "deepseek" : "claude";
  196. //question_date request_time
  197. $request_question_time = date("Y-m-d H:i:s");
  198. $question_time = date("H:i:s");
  199. $item_value = common::excuteOneSql("select item_value from public.config where item = 'AIAPISetting'");
  200. $config = json_decode($item_value,true);
  201. $response = AIClientFactory::create($model, $config[$model], $systemPrompt, $message, $history = []);
  202. $response_time = date("Y-m-d H:i:s");
  203. $input_token = "";
  204. $output_token = "";
  205. $date1 = new DateTime($request_question_time);
  206. $date2 = new DateTime($response_time);
  207. $response_duration = $date2->getTimestamp() - $date1->getTimestamp();
  208. //回答问题类型,在没有超时的情况下,固定:AI回答
  209. $answer_type = "AI回答";
  210. if ($response_duration > 120){
  211. $answer_type = "回答超时";
  212. }
  213. //获取自然序列
  214. $sequence = common::getChatAiSequence();
  215. $name = $ai_method == 'DS' ? "DS" : "CD";
  216. $request_id = "R".$name."".date("Ymd").$sequence;
  217. $question_id = "Q"."".date("Ymd").$sequence;
  218. //处理一下参数
  219. $user_name = common::check_input(_getLoginName());
  220. $user_type = _isApexLogin() ? "employee" : "customer";
  221. //这里的测试,固定写自由文本
  222. $question_type = 'free text';
  223. $question_id = common::check_input($question_id);
  224. $question_content = common::check_input($message);
  225. $answer_type = common::check_input($answer_type);
  226. //记录回答展示给客户的具体内容
  227. $answer = common::check_input(common::getChatAimessage($response['message']));
  228. $ai_model = common::check_input($model);
  229. $input_token = common::check_input($input_token);
  230. $request_content = common::check_input(json_encode($response['data']));
  231. $ai_response_content = common::check_input(json_encode($response['full_response']));
  232. $output_token = common::check_input($output_token);
  233. $answer_template = "";
  234. $message = json_decode(common::getChatAimessage($response['message']),true);
  235. if($message["can_query"] == "true" && !empty($message["sql"])){
  236. $reference = $message["reference"];
  237. $answer_template = common::check_input($message["reference"]);
  238. $sql = $message["sql"];
  239. //拆分sql 存在多条的情况
  240. $sqlArr = explode(";", $sql);
  241. //给所有sql 拼接用户权限
  242. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  243. //先不考虑总数,处理有难度
  244. foreach($sqlArr as $_sql){
  245. if(empty($_sql)){
  246. continue;
  247. }
  248. //根据public.kln_ocean 和 WHERE 的位置关系,带入权限
  249. $new_sql = utils::modifyString($_sql,$sqlWhere);
  250. //处理limit 超过10 先限制10
  251. $new_sql = utils::processLimitClause($new_sql);
  252. $rs = common::excuteListSql($new_sql);
  253. $reference = utils::replacementsMultiline($rs,$reference);
  254. }
  255. //有就去掉{{#each hbol_list}}\n {{/each}}
  256. $reference = preg_replace([
  257. '/\{\{[^}]+\}\}\n/', // 匹配开始标签及换行
  258. '/\{\{\/[^}]+\}\}/' // 匹配结束标签
  259. ], '', $reference);
  260. //$reference = $reference.$message["reference"];
  261. $answer = $reference;
  262. //$response['message'] = json_decode(common::getChatAimessage($response['message']),true);
  263. //$answer = $response;
  264. }else{
  265. $answer = $message["response"];
  266. }
  267. //最后插入数据
  268. $sql = "INSERT INTO public.kln_robot_chat_log( question_id, user_name, user_type, question_type, question_content,
  269. answer_type, answer, answer_satisfication, answer_duration,answer_template, question_date,
  270. question_time, request_id, ai_model, request_content, input_token,
  271. ai_response_content, output_token, request_time, response_time,
  272. response_duration)
  273. VALUES ('$question_id', '$user_name', '$user_type', '$question_type', '$question_content',
  274. '$answer_type', '".common::check_input($answer)."', '', '$response_duration','$answer_template','$request_question_time',
  275. '$question_time', '$request_id', '$ai_model','$request_content', '$input_token',
  276. '$ai_response_content', '$output_token', '$request_question_time', '$response_time',
  277. '$response_duration');";
  278. $rs = common::excuteUpdateSql($sql);
  279. if (!$rs) {
  280. $data = array("msg" => "AI Chat Save Error");
  281. common::echo_json_encode(200,$data);
  282. exit();
  283. }
  284. $return = array("type"=>"markdown","data" =>$answer);
  285. common::echo_json_encode(200,$return);
  286. exit();
  287. }
  288. if ($operate == "download"){
  289. $sql = common::deCode($_REQUEST['tmp_search'], 'D');
  290. if(!empty($sql)){
  291. $rs = common::excuteListSql($sql);
  292. }
  293. common::echo_json_encode(200,array("msg"=>"success","Data" => $rs));
  294. exit;
  295. }
  296. }
  297. public function dealPromptFormatAndVue($configuration){
  298. //tableDat-VUE
  299. $tableData = array();
  300. $table_structure_text="[";
  301. $table_structure_configuration = json_decode($configuration['table_structure_configuration'],true);
  302. foreach($table_structure_configuration as $tk =>$tv){
  303. $tableData[] = $tv;
  304. $table_structure_text .='{
  305. "name": "'.$tv["name"].'",
  306. "type": "'.$tv["type"].'",
  307. "description": "'.$tv["description"].'",
  308. "exampledata": "'.$tv["exampledata"].'",
  309. }';
  310. if(count($table_structure_configuration)-1 > $tk){
  311. $table_structure_text .=",";
  312. }
  313. $table_structure_text .=common::splicedLlineBreaks();
  314. }
  315. $table_structure_text.="]";
  316. //stepData -VUE
  317. $stepData = array();
  318. $response_rule_text = "";
  319. $response_rule_configuration = json_decode($configuration['response_rule_configuration'],true);
  320. foreach($response_rule_configuration as $rk =>$rv){
  321. $tempTable = array();
  322. $tempTable["description"] = $rv["description"];
  323. $stepData[] = $tempTable;
  324. $response_rule_text .=($rk+1).'.'.$rv["description"];
  325. $response_rule_text .=common::splicedLlineBreaks();
  326. }
  327. //formatList -VUE
  328. $output_format_text = "{";
  329. $output_format_configuration = json_decode($configuration['output_format_configuration'],true);
  330. $formatListType = $output_format_configuration['output_type'];
  331. $formatList = empty($output_format_configuration['data']) ? array(): $output_format_configuration['data'];
  332. foreach($formatList as $ok =>$ov){
  333. $output_format_text .="\"".$ov['name']."\"".": "."\"".$ov['describe']."\"";
  334. $output_format_text .=common::splicedLlineBreaks();
  335. }
  336. $output_format_text .= "}";
  337. $promptFormat = $this->getCompletePromptFormat();
  338. $promptFormat = str_replace('<{professional_field}>', $configuration['character_name'], $promptFormat);
  339. $promptFormat = str_replace('<{character_name}>', $configuration['character_name'], $promptFormat);
  340. $promptFormat = str_replace('<{main_tasks}>', $configuration['main_tasks'], $promptFormat);
  341. $promptFormat = str_replace('<{table}>', $configuration['table_name'], $promptFormat);
  342. $promptFormat = str_replace('<{table_structure_configuration}>', $table_structure_text, $promptFormat);
  343. $promptFormat = str_replace('<{response_rule_configuration}>', $response_rule_text, $promptFormat);
  344. $promptFormat = str_replace('<{number}>', count($response_rule_configuration)+1, $promptFormat);
  345. $promptFormat = str_replace('<{output_type}>', $formatListType, $promptFormat);
  346. $promptFormat = str_replace('<{output_format_configuration}>', $output_format_text, $promptFormat);
  347. return array("vuedata"=>array("tableData"=>$tableData,"stepData"=>$stepData,"formatList"=>$formatList,"formatListType"=>$formatListType),
  348. "promptFormat" =>$promptFormat);
  349. }
  350. public function getChangedLog($id){
  351. $changeLogList = array();
  352. $configurationArr = common::excuteListSql("select id, character_name,professional_field,main_tasks,table_name,table_description,
  353. created_by,TO_CHAR(created_time, 'YYYY-mm-dd HH24:MI:SS') as created_time,
  354. table_structure_configuration,response_rule_configuration,output_format_configuration,fixed_problem_configuration
  355. from public.kln_robot_prompt_configuration_log where ref_id = '$id' order by id desc");
  356. foreach($configurationArr as $ca){
  357. $data = $this->dealPromptFormatAndVue($ca);
  358. $temp =array();
  359. $temp["time"] = $ca['created_time']." Prompt";
  360. $temp["person"] ="提交人:".$ca['created_by'];
  361. $temp["text"] = $data['promptFormat'];
  362. $changeLogList[] = $temp;
  363. }
  364. return $changeLogList;
  365. }
  366. public function getCompletePromptFormat() {
  367. $formatTpl = "
  368. 您是专门从<{professional_field}>的 <{character_name}>,请始终以<{output_type}>格式响应。您的主要任务是<{main_tasks}>
  369. 表名:<{table}>
  370. 表结构: \"columns\": <{table_structure_configuration}>
  371. 响应规则,请按以下步骤处理:
  372. <{response_rule_configuration}>
  373. <{number}>. 请用以下<{output_type}>格式回复:
  374. <{output_format_configuration}>";
  375. return $formatTpl;
  376. }
  377. }
  378. ?>