xref: /plugin/aichat/helper.php (revision 9f6b34c4eab8e8478b8540a3880c4bbeacb98e9d)
10337f47fSAndreas Gohr<?php
20337f47fSAndreas Gohr
3f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Model\AbstractModel;
4f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Chunk;
50337f47fSAndreas Gohruse dokuwiki\plugin\aichat\Embeddings;
6f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Model\OpenAI\GPT35Turbo;
7f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Storage\SQLiteStorage;
80337f47fSAndreas Gohr
90337f47fSAndreas Gohrrequire_once __DIR__ . '/vendor/autoload.php';
100337f47fSAndreas Gohr
110337f47fSAndreas Gohr/**
120337f47fSAndreas Gohr * DokuWiki Plugin aichat (Helper Component)
130337f47fSAndreas Gohr *
140337f47fSAndreas Gohr * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
150337f47fSAndreas Gohr * @author  Andreas Gohr <gohr@cosmocode.de>
160337f47fSAndreas Gohr */
170337f47fSAndreas Gohrclass helper_plugin_aichat extends \dokuwiki\Extension\Plugin
180337f47fSAndreas Gohr{
19f6ef2e50SAndreas Gohr    /** @var AbstractModel */
20f6ef2e50SAndreas Gohr    protected $model;
210337f47fSAndreas Gohr    /** @var Embeddings */
220337f47fSAndreas Gohr    protected $embeddings;
230337f47fSAndreas Gohr
240337f47fSAndreas Gohr    /**
25c4127b8eSAndreas Gohr     * Check if the current user is allowed to use the plugin (if it has been restricted)
26c4127b8eSAndreas Gohr     *
27c4127b8eSAndreas Gohr     * @return bool
28c4127b8eSAndreas Gohr     */
29c4127b8eSAndreas Gohr    public function userMayAccess()
30c4127b8eSAndreas Gohr    {
31c4127b8eSAndreas Gohr        global $auth;
32c4127b8eSAndreas Gohr        global $USERINFO;
33c4127b8eSAndreas Gohr        global $INPUT;
34c4127b8eSAndreas Gohr
35c4127b8eSAndreas Gohr        if (!$auth) return true;
36c4127b8eSAndreas Gohr        if (!$this->getConf('restrict')) return true;
37c4127b8eSAndreas Gohr        if (!isset($USERINFO)) return false;
38c4127b8eSAndreas Gohr
39c4127b8eSAndreas Gohr        return auth_isMember($this->getConf('restrict'), $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']);
40c4127b8eSAndreas Gohr    }
41c4127b8eSAndreas Gohr
42c4127b8eSAndreas Gohr    /**
430337f47fSAndreas Gohr     * Access the OpenAI client
440337f47fSAndreas Gohr     *
45f6ef2e50SAndreas Gohr     * @return GPT35Turbo
460337f47fSAndreas Gohr     */
47f6ef2e50SAndreas Gohr    public function getModel()
480337f47fSAndreas Gohr    {
49*9f6b34c4SAndreas Gohr        if ($this->model === null) {
50*9f6b34c4SAndreas Gohr            $class = '\\dokuwiki\\plugin\\aichat\\Model\\' . $this->getConf('model');
51*9f6b34c4SAndreas Gohr
52*9f6b34c4SAndreas Gohr            if (!class_exists($class)) {
53*9f6b34c4SAndreas Gohr                throw new \RuntimeException('Configured model not found: ' . $class);
54*9f6b34c4SAndreas Gohr            }
55*9f6b34c4SAndreas Gohr            // FIXME for now we only have OpenAI models, so we can hardcode the auth setup
56*9f6b34c4SAndreas Gohr            $this->model = new $class([
57*9f6b34c4SAndreas Gohr                'key' => $this->getConf('openaikey'),
58*9f6b34c4SAndreas Gohr                'org' => $this->getConf('openaiorg')
59*9f6b34c4SAndreas Gohr            ]);
60*9f6b34c4SAndreas Gohr        }
61*9f6b34c4SAndreas Gohr
62f6ef2e50SAndreas Gohr        return $this->model;
630337f47fSAndreas Gohr    }
640337f47fSAndreas Gohr
650337f47fSAndreas Gohr    /**
660337f47fSAndreas Gohr     * Access the Embeddings interface
670337f47fSAndreas Gohr     *
680337f47fSAndreas Gohr     * @return Embeddings
690337f47fSAndreas Gohr     */
700337f47fSAndreas Gohr    public function getEmbeddings()
710337f47fSAndreas Gohr    {
72*9f6b34c4SAndreas Gohr        if ($this->embeddings === null) {
73*9f6b34c4SAndreas Gohr            // FIXME we currently have only one storage backend, so we can hardcode it
74*9f6b34c4SAndreas Gohr            $this->embeddings = new Embeddings($this->getModel(), new SQLiteStorage());
75*9f6b34c4SAndreas Gohr        }
76*9f6b34c4SAndreas Gohr
770337f47fSAndreas Gohr        return $this->embeddings;
780337f47fSAndreas Gohr    }
790337f47fSAndreas Gohr
800337f47fSAndreas Gohr    /**
810337f47fSAndreas Gohr     * Ask a question with a chat history
820337f47fSAndreas Gohr     *
830337f47fSAndreas Gohr     * @param string $question
840337f47fSAndreas Gohr     * @param array[] $history The chat history [[user, ai], [user, ai], ...]
850337f47fSAndreas Gohr     * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources]
860337f47fSAndreas Gohr     * @throws Exception
870337f47fSAndreas Gohr     */
880337f47fSAndreas Gohr    public function askChatQuestion($question, $history = [])
890337f47fSAndreas Gohr    {
900337f47fSAndreas Gohr        if ($history) {
910337f47fSAndreas Gohr            $standaloneQuestion = $this->rephraseChatQuestion($question, $history);
920337f47fSAndreas Gohr        } else {
930337f47fSAndreas Gohr            $standaloneQuestion = $question;
940337f47fSAndreas Gohr        }
950337f47fSAndreas Gohr        return $this->askQuestion($standaloneQuestion);
960337f47fSAndreas Gohr    }
970337f47fSAndreas Gohr
980337f47fSAndreas Gohr    /**
990337f47fSAndreas Gohr     * Ask a single standalone question
1000337f47fSAndreas Gohr     *
1010337f47fSAndreas Gohr     * @param string $question
1020337f47fSAndreas Gohr     * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources]
1030337f47fSAndreas Gohr     * @throws Exception
1040337f47fSAndreas Gohr     */
1050337f47fSAndreas Gohr    public function askQuestion($question)
1060337f47fSAndreas Gohr    {
107*9f6b34c4SAndreas Gohr        $similar = $this->getEmbeddings()->getSimilarChunks($question);
1089e81bea7SAndreas Gohr        if ($similar) {
10955392016SAndreas Gohr            $context = implode("\n", array_map(function (Chunk $chunk) {
11068908844SAndreas Gohr                return "\n```\n" . $chunk->getText() . "\n```\n";
11155392016SAndreas Gohr            }, $similar));
1120337f47fSAndreas Gohr            $prompt = $this->getPrompt('question', ['context' => $context]);
1139e81bea7SAndreas Gohr        } else {
1149e81bea7SAndreas Gohr            $prompt = $this->getPrompt('noanswer');
1159e81bea7SAndreas Gohr        }
11668908844SAndreas Gohr
1170337f47fSAndreas Gohr        $messages = [
1180337f47fSAndreas Gohr            [
1190337f47fSAndreas Gohr                'role' => 'system',
1200337f47fSAndreas Gohr                'content' => $prompt
1210337f47fSAndreas Gohr            ],
1220337f47fSAndreas Gohr            [
1230337f47fSAndreas Gohr                'role' => 'user',
1240337f47fSAndreas Gohr                'content' => $question
1250337f47fSAndreas Gohr            ]
1260337f47fSAndreas Gohr        ];
1270337f47fSAndreas Gohr
128*9f6b34c4SAndreas Gohr        $answer = $this->getModel()->getAnswer($messages);
1290337f47fSAndreas Gohr
1300337f47fSAndreas Gohr        return [
1310337f47fSAndreas Gohr            'question' => $question,
1320337f47fSAndreas Gohr            'answer' => $answer,
1330337f47fSAndreas Gohr            'sources' => $similar,
1340337f47fSAndreas Gohr        ];
1350337f47fSAndreas Gohr    }
1360337f47fSAndreas Gohr
1370337f47fSAndreas Gohr    /**
1380337f47fSAndreas Gohr     * Rephrase a question into a standalone question based on the chat history
1390337f47fSAndreas Gohr     *
1400337f47fSAndreas Gohr     * @param string $question The original user question
1410337f47fSAndreas Gohr     * @param array[] $history The chat history [[user, ai], [user, ai], ...]
1420337f47fSAndreas Gohr     * @return string The rephrased question
1430337f47fSAndreas Gohr     * @throws Exception
1440337f47fSAndreas Gohr     */
1450337f47fSAndreas Gohr    public function rephraseChatQuestion($question, $history)
1460337f47fSAndreas Gohr    {
1470337f47fSAndreas Gohr        // go back in history as far as possible without hitting the token limit
1480337f47fSAndreas Gohr        $chatHistory = '';
1490337f47fSAndreas Gohr        $history = array_reverse($history);
1500337f47fSAndreas Gohr        foreach ($history as $row) {
151f6ef2e50SAndreas Gohr            if (
152*9f6b34c4SAndreas Gohr                count($this->getEmbeddings()->getTokenEncoder()->encode($chatHistory)) >
153*9f6b34c4SAndreas Gohr                $this->getModel()->getMaxRephrasingTokenLength()
154f6ef2e50SAndreas Gohr            ) {
1550337f47fSAndreas Gohr                break;
1560337f47fSAndreas Gohr            }
1570337f47fSAndreas Gohr
1580337f47fSAndreas Gohr            $chatHistory =
1590337f47fSAndreas Gohr                "Human: " . $row[0] . "\n" .
1600337f47fSAndreas Gohr                "Assistant: " . $row[1] . "\n" .
1610337f47fSAndreas Gohr                $chatHistory;
1620337f47fSAndreas Gohr        }
1630337f47fSAndreas Gohr
1640337f47fSAndreas Gohr        // ask openAI to rephrase the question
1650337f47fSAndreas Gohr        $prompt = $this->getPrompt('rephrase', ['history' => $chatHistory, 'question' => $question]);
1660337f47fSAndreas Gohr        $messages = [['role' => 'user', 'content' => $prompt]];
167*9f6b34c4SAndreas Gohr        return $this->getModel()->getRephrasedQuestion($messages);
1680337f47fSAndreas Gohr    }
1690337f47fSAndreas Gohr
1700337f47fSAndreas Gohr    /**
1710337f47fSAndreas Gohr     * Load the given prompt template and fill in the variables
1720337f47fSAndreas Gohr     *
1730337f47fSAndreas Gohr     * @param string $type
1740337f47fSAndreas Gohr     * @param string[] $vars
1750337f47fSAndreas Gohr     * @return string
1760337f47fSAndreas Gohr     */
1770337f47fSAndreas Gohr    protected function getPrompt($type, $vars = [])
1780337f47fSAndreas Gohr    {
1790337f47fSAndreas Gohr        $template = file_get_contents($this->localFN('prompt_' . $type));
1800337f47fSAndreas Gohr
1810337f47fSAndreas Gohr        $replace = array();
1820337f47fSAndreas Gohr        foreach ($vars as $key => $val) {
1830337f47fSAndreas Gohr            $replace['{{' . strtoupper($key) . '}}'] = $val;
1840337f47fSAndreas Gohr        }
1850337f47fSAndreas Gohr
1860337f47fSAndreas Gohr        return strtr($template, $replace);
1870337f47fSAndreas Gohr    }
1880337f47fSAndreas Gohr}
1890337f47fSAndreas Gohr
190