robot.class.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  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. //分担查询
  193. include ONLINE_ROOT . 'libs' . DS . 'map_config.ini.php';
  194. $ai_method = $_POST["test_ai_method"];
  195. $systemPrompt = $_POST["prompt"];
  196. $message = $_POST["test_question"];
  197. $model = $ai_method == 'DS' ? "deepseek" : "claude";
  198. //question_date request_time
  199. $request_question_time = date("Y-m-d H:i:s");
  200. $question_time = date("H:i:s");
  201. $item_value = common::excuteOneSql("select item_value from public.config where item = 'AIAPISetting'");
  202. $config = json_decode($item_value,true);
  203. $response = AIClientFactory::create($model, $config[$model], $systemPrompt, $message, $history = []);
  204. $response_time = date("Y-m-d H:i:s");
  205. $input_token = "";
  206. $output_token = "";
  207. $date1 = new DateTime($request_question_time);
  208. $date2 = new DateTime($response_time);
  209. $response_duration = $date2->getTimestamp() - $date1->getTimestamp();
  210. //回答问题类型,在没有超时的情况下,固定:AI回答
  211. $answer_type = "AI回答";
  212. if ($response_duration > 120){
  213. $answer_type = "回答超时";
  214. }
  215. //获取自然序列
  216. $sequence = common::getChatAiSequence();
  217. $name = $ai_method == 'DS' ? "DS" : "CD";
  218. $request_id = "R".$name."".date("Ymd").$sequence;
  219. $question_id = "Q"."".date("Ymd").$sequence;
  220. //处理一下参数
  221. $user_name = common::check_input(_getLoginName());
  222. $user_type = _isApexLogin() ? "employee" : "customer";
  223. //这里的测试,固定写自由文本
  224. $question_type = 'free text';
  225. $question_id = common::check_input($question_id);
  226. $question_content = common::check_input($message);
  227. $answer_type = common::check_input($answer_type);
  228. //记录回答展示给客户的具体内容
  229. $answer = common::check_input(common::getChatAimessage($response['message']));
  230. $ai_model = common::check_input($model);
  231. $input_token = common::check_input($input_token);
  232. $request_content = common::check_input(json_encode($response['data']));
  233. $ai_response_content = common::check_input(json_encode($response['full_response']));
  234. $output_token = common::check_input($output_token);
  235. $answer_template = "";
  236. $message = json_decode(common::getChatAimessage($response['message']),true);
  237. if($message["can_query"] == "true" && !empty($message["sql"])){
  238. $reference = $message["reference"];
  239. $answer_template = common::check_input($message["reference"]);
  240. $sql = $message["sql"];
  241. //拆分sql 存在多条的情况
  242. $sqlArr = explode(";", $sql);
  243. //给所有sql 拼接用户权限
  244. $sqlWhere = ' ' . common::searchExtendHand_KLN("ocean", $_SESSION["ONLINE_USER"]);
  245. //先不考虑总数,处理有难度
  246. foreach($sqlArr as $_sql){
  247. if(empty($_sql)){
  248. continue;
  249. }
  250. //根据public.kln_ocean 和 WHERE 的位置关系,带入权限
  251. $new_sql = utils::modifyString($_sql,$sqlWhere);
  252. //处理limit 超过10 先限制10
  253. $new_sql = utils::processLimitClause($new_sql);
  254. //$rs = common::excuteListSql($new_sql);
  255. $rs = $mapdb->GetAll($new_sql) or ( (!$mapdb->ErrorMsg()) or error_log(common::dbLog($mapdb, $new_sql), 0));
  256. $reference = utils::replacementsMultiline($rs,$reference);
  257. }
  258. //有就去掉{{#each hbol_list}}\n {{/each}}
  259. $reference = preg_replace([
  260. '/\{\{[^}]+\}\}\n/', // 匹配开始标签及换行
  261. '/\{\{\/[^}]+\}\}/' // 匹配结束标签
  262. ], '', $reference);
  263. //$reference = $reference.$message["reference"];
  264. $answer = $reference;
  265. //$response['message'] = json_decode(common::getChatAimessage($response['message']),true);
  266. //$answer = $response;
  267. }else{
  268. $answer = $message["response"];
  269. }
  270. //最后插入数据
  271. $sql = "INSERT INTO public.kln_robot_chat_log( question_id, user_name, user_type, question_type, question_content,
  272. answer_type, answer, answer_satisfication, answer_duration,answer_template, question_date,
  273. question_time, request_id, ai_model, request_content, input_token,
  274. ai_response_content, output_token, request_time, response_time,
  275. response_duration)
  276. VALUES ('$question_id', '$user_name', '$user_type', '$question_type', '$question_content',
  277. '$answer_type', '".common::check_input($answer)."', '', '$response_duration','$answer_template','$request_question_time',
  278. '$question_time', '$request_id', '$ai_model','$request_content', '$input_token',
  279. '$ai_response_content', '$output_token', '$request_question_time', '$response_time',
  280. '$response_duration');";
  281. $rs = common::excuteUpdateSql($sql);
  282. if (!$rs) {
  283. $data = array("msg" => "AI Chat Save Error");
  284. common::echo_json_encode(200,$data);
  285. exit();
  286. }
  287. $return = array("type"=>"markdown","data" =>$answer);
  288. common::echo_json_encode(200,$return);
  289. exit();
  290. }
  291. if ($operate == "download"){
  292. $sql = common::deCode($_REQUEST['tmp_search'], 'D');
  293. if(!empty($sql)){
  294. $rs = common::excuteListSql($sql);
  295. }
  296. common::echo_json_encode(200,array("msg"=>"success","Data" => $rs));
  297. exit;
  298. }
  299. }
  300. public function dealPromptFormatAndVue($configuration){
  301. //tableDat-VUE
  302. $tableData = array();
  303. $table_structure_text="[";
  304. $table_structure_configuration = json_decode($configuration['table_structure_configuration'],true);
  305. foreach($table_structure_configuration as $tk =>$tv){
  306. $tableData[] = $tv;
  307. $table_structure_text .='{
  308. "name": "'.$tv["name"].'",
  309. "type": "'.$tv["type"].'",
  310. "description": "'.$tv["description"].'",
  311. "exampledata": "'.$tv["exampledata"].'",
  312. }';
  313. if(count($table_structure_configuration)-1 > $tk){
  314. $table_structure_text .=",";
  315. }
  316. $table_structure_text .=common::splicedLlineBreaks();
  317. }
  318. $table_structure_text.="]";
  319. //stepData -VUE
  320. $stepData = array();
  321. $response_rule_text = "";
  322. $response_rule_configuration = json_decode($configuration['response_rule_configuration'],true);
  323. foreach($response_rule_configuration as $rk =>$rv){
  324. $tempTable = array();
  325. $tempTable["description"] = $rv["description"];
  326. $stepData[] = $tempTable;
  327. $response_rule_text .=($rk+1).'.'.$rv["description"];
  328. $response_rule_text .=common::splicedLlineBreaks();
  329. }
  330. //formatList -VUE
  331. $output_format_text = "{";
  332. $output_format_configuration = json_decode($configuration['output_format_configuration'],true);
  333. $formatListType = $output_format_configuration['output_type'];
  334. $formatList = empty($output_format_configuration['data']) ? array(): $output_format_configuration['data'];
  335. foreach($formatList as $ok =>$ov){
  336. $output_format_text .="\"".$ov['name']."\"".": "."\"".$ov['describe']."\"";
  337. $output_format_text .=common::splicedLlineBreaks();
  338. }
  339. $output_format_text .= "}";
  340. $promptFormat = $this->getCompletePromptFormat();
  341. $promptFormat = str_replace('<{professional_field}>', $configuration['character_name'], $promptFormat);
  342. $promptFormat = str_replace('<{character_name}>', $configuration['character_name'], $promptFormat);
  343. $promptFormat = str_replace('<{main_tasks}>', $configuration['main_tasks'], $promptFormat);
  344. $promptFormat = str_replace('<{table}>', $configuration['table_name'], $promptFormat);
  345. $promptFormat = str_replace('<{table_structure_configuration}>', $table_structure_text, $promptFormat);
  346. $promptFormat = str_replace('<{response_rule_configuration}>', $response_rule_text, $promptFormat);
  347. $promptFormat = str_replace('<{number}>', count($response_rule_configuration)+1, $promptFormat);
  348. $promptFormat = str_replace('<{output_type}>', $formatListType, $promptFormat);
  349. $promptFormat = str_replace('<{output_format_configuration}>', $output_format_text, $promptFormat);
  350. return array("vuedata"=>array("tableData"=>$tableData,"stepData"=>$stepData,"formatList"=>$formatList,"formatListType"=>$formatListType),
  351. "promptFormat" =>$promptFormat);
  352. }
  353. public function getChangedLog($id){
  354. $changeLogList = array();
  355. $configurationArr = common::excuteListSql("select id, character_name,professional_field,main_tasks,table_name,table_description,
  356. created_by,TO_CHAR(created_time, 'YYYY-mm-dd HH24:MI:SS') as created_time,
  357. table_structure_configuration,response_rule_configuration,output_format_configuration,fixed_problem_configuration
  358. from public.kln_robot_prompt_configuration_log where ref_id = '$id' order by id desc");
  359. foreach($configurationArr as $ca){
  360. $data = $this->dealPromptFormatAndVue($ca);
  361. $temp =array();
  362. $temp["time"] = $ca['created_time']." Prompt";
  363. $temp["person"] ="提交人:".$ca['created_by'];
  364. $temp["text"] = $data['promptFormat'];
  365. $changeLogList[] = $temp;
  366. }
  367. return $changeLogList;
  368. }
  369. public function getCompletePromptFormat() {
  370. $formatTpl = "
  371. 您是专门从<{professional_field}>的 <{character_name}>,请始终以<{output_type}>格式响应。您的主要任务是<{main_tasks}>
  372. 表名:<{table}>
  373. 表结构: \"columns\": <{table_structure_configuration}>
  374. 响应规则,请按以下步骤处理:
  375. <{response_rule_configuration}>
  376. <{number}>. 请用以下<{output_type}>格式回复:
  377. <{output_format_configuration}>";
  378. return $formatTpl;
  379. }
  380. }
  381. ?>