1<?php 2 3use dokuwiki\ErrorHandler; 4use dokuwiki\plugin\aichat\backend\Chunk; 5 6/** 7 * DokuWiki Plugin aichat (Action Component) 8 * 9 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html 10 * @author Andreas Gohr <gohr@cosmocode.de> 11 */ 12class action_plugin_aichat extends \dokuwiki\Extension\ActionPlugin 13{ 14 15 /** @inheritDoc */ 16 public function register(Doku_Event_Handler $controller) 17 { 18 $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handleQuestion'); 19 20 } 21 22 23 /** 24 * Event handler for AJAX_CALL_UNKNOWN event 25 * 26 * @see https://www.dokuwiki.org/devel:events:ajax_call_unknown 27 * @param Doku_Event $event Event object 28 * @param mixed $param optional parameter passed when event was registered 29 * @return void 30 */ 31 public function handleQuestion(Doku_Event $event, $param) 32 { 33 if ($event->data !== 'aichat') return; 34 $event->preventDefault(); 35 $event->stopPropagation(); 36 global $INPUT; 37 38 $question = $INPUT->post->str('question'); 39 $history = json_decode($INPUT->post->str('history')); 40 header('Content-Type: application/json'); 41 42 try { 43 /** @var helper_plugin_aichat $helper */ 44 $helper = plugin_load('helper', 'aichat'); 45 $result = $helper->askChatQuestion($question, $history); 46 $sources = []; 47 foreach ($result['sources'] as $source) { 48 /** @var Chunk $source */ 49 $sources[wl($source->getPage())] = p_get_first_heading($source->getPage()) ?: $source->getPage(); 50 } 51 echo json_encode([ 52 'question' => $result['question'], 53 'answer' => $result['answer'], 54 'sources' => $sources, 55 ]); 56 57 if ($this->getConf('logging')) { 58 \dokuwiki\Logger::getInstance('aichat')->log( 59 $question, 60 [ 61 'interpretation' => $result['question'], 62 'answer' => $result['answer'], 63 'sources' => $sources, 64 'ip' => $INPUT->server->str('REMOTE_ADDR'), 65 'user' => $INPUT->server->str('REMOTE_USER'), 66 'stats' => $helper->getOpenAI()->getUsageStats() 67 ] 68 ); 69 } 70 } catch (\Exception $e) { 71 ErrorHandler::logException($e); 72 echo json_encode([ 73 'question' => $question, 74 'answer' => 'An error occurred. More info may be available in the error log. ' . $e->getMessage(), 75 'sources' => [], 76 ]); 77 } 78 } 79 80} 81 82