xref: /plugin/aichat/action.php (revision bddd899cfd072ee6cc5aab9bb9d767fea8dd1115)
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        } catch (\Exception $e) {
57            ErrorHandler::logException($e);
58            echo json_encode([
59                'question' => $question,
60                'answer' => 'An error occurred. More info may be available in the error log. ' . $e->getMessage(),
61                'sources' => [],
62            ]);
63        }
64    }
65
66}
67
68