xref: /plugin/aichat/helper.php (revision 754b83949a3b9c186281d57d1189bd37032e0788)
10337f47fSAndreas Gohr<?php
20337f47fSAndreas Gohr
33379af09SAndreas Gohruse dokuwiki\Extension\CLIPlugin;
4f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Chunk;
50337f47fSAndreas Gohruse dokuwiki\plugin\aichat\Embeddings;
6*754b8394SAndreas Gohruse dokuwiki\plugin\aichat\Model\AbstractModel;
7f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Model\OpenAI\GPT35Turbo;
801f06932SAndreas Gohruse dokuwiki\plugin\aichat\Storage\AbstractStorage;
913dbfc23SAndreas Gohruse dokuwiki\plugin\aichat\Storage\PineconeStorage;
10f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Storage\SQLiteStorage;
110337f47fSAndreas Gohr
120337f47fSAndreas Gohrrequire_once __DIR__ . '/vendor/autoload.php';
130337f47fSAndreas Gohr
140337f47fSAndreas Gohr/**
150337f47fSAndreas Gohr * DokuWiki Plugin aichat (Helper Component)
160337f47fSAndreas Gohr *
170337f47fSAndreas Gohr * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
180337f47fSAndreas Gohr * @author  Andreas Gohr <gohr@cosmocode.de>
190337f47fSAndreas Gohr */
200337f47fSAndreas Gohrclass helper_plugin_aichat extends \dokuwiki\Extension\Plugin
210337f47fSAndreas Gohr{
223379af09SAndreas Gohr    /** @var CLIPlugin $logger */
233379af09SAndreas Gohr    protected $logger;
24f6ef2e50SAndreas Gohr    /** @var AbstractModel */
25f6ef2e50SAndreas Gohr    protected $model;
260337f47fSAndreas Gohr    /** @var Embeddings */
270337f47fSAndreas Gohr    protected $embeddings;
2801f06932SAndreas Gohr    /** @var AbstractStorage */
2901f06932SAndreas Gohr    protected $storage;
300337f47fSAndreas Gohr
310337f47fSAndreas Gohr    /**
323379af09SAndreas Gohr     * Use the given CLI plugin for logging
333379af09SAndreas Gohr     *
343379af09SAndreas Gohr     * @param CLIPlugin $logger
353379af09SAndreas Gohr     * @return void
363379af09SAndreas Gohr     */
378285fff9SAndreas Gohr    public function setLogger($logger)
388285fff9SAndreas Gohr    {
393379af09SAndreas Gohr        $this->logger = $logger;
403379af09SAndreas Gohr    }
413379af09SAndreas Gohr
423379af09SAndreas Gohr    /**
43c4127b8eSAndreas Gohr     * Check if the current user is allowed to use the plugin (if it has been restricted)
44c4127b8eSAndreas Gohr     *
45c4127b8eSAndreas Gohr     * @return bool
46c4127b8eSAndreas Gohr     */
47c4127b8eSAndreas Gohr    public function userMayAccess()
48c4127b8eSAndreas Gohr    {
49c4127b8eSAndreas Gohr        global $auth;
50c4127b8eSAndreas Gohr        global $USERINFO;
51c4127b8eSAndreas Gohr        global $INPUT;
52c4127b8eSAndreas Gohr
53c4127b8eSAndreas Gohr        if (!$auth) return true;
54c4127b8eSAndreas Gohr        if (!$this->getConf('restrict')) return true;
55c4127b8eSAndreas Gohr        if (!isset($USERINFO)) return false;
56c4127b8eSAndreas Gohr
57c4127b8eSAndreas Gohr        return auth_isMember($this->getConf('restrict'), $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']);
58c4127b8eSAndreas Gohr    }
59c4127b8eSAndreas Gohr
60c4127b8eSAndreas Gohr    /**
610337f47fSAndreas Gohr     * Access the OpenAI client
620337f47fSAndreas Gohr     *
63f6ef2e50SAndreas Gohr     * @return GPT35Turbo
640337f47fSAndreas Gohr     */
65f6ef2e50SAndreas Gohr    public function getModel()
660337f47fSAndreas Gohr    {
679f6b34c4SAndreas Gohr        if ($this->model === null) {
689f6b34c4SAndreas Gohr            $class = '\\dokuwiki\\plugin\\aichat\\Model\\' . $this->getConf('model');
699f6b34c4SAndreas Gohr
709f6b34c4SAndreas Gohr            if (!class_exists($class)) {
719f6b34c4SAndreas Gohr                throw new \RuntimeException('Configured model not found: ' . $class);
729f6b34c4SAndreas Gohr            }
739f6b34c4SAndreas Gohr            // FIXME for now we only have OpenAI models, so we can hardcode the auth setup
749f6b34c4SAndreas Gohr            $this->model = new $class([
759f6b34c4SAndreas Gohr                'key' => $this->getConf('openaikey'),
769f6b34c4SAndreas Gohr                'org' => $this->getConf('openaiorg')
779f6b34c4SAndreas Gohr            ]);
789f6b34c4SAndreas Gohr        }
799f6b34c4SAndreas Gohr
80f6ef2e50SAndreas Gohr        return $this->model;
810337f47fSAndreas Gohr    }
820337f47fSAndreas Gohr
830337f47fSAndreas Gohr    /**
840337f47fSAndreas Gohr     * Access the Embeddings interface
850337f47fSAndreas Gohr     *
860337f47fSAndreas Gohr     * @return Embeddings
870337f47fSAndreas Gohr     */
880337f47fSAndreas Gohr    public function getEmbeddings()
890337f47fSAndreas Gohr    {
909f6b34c4SAndreas Gohr        if ($this->embeddings === null) {
9101f06932SAndreas Gohr            $this->embeddings = new Embeddings($this->getModel(), $this->getStorage());
923379af09SAndreas Gohr            if ($this->logger) {
933379af09SAndreas Gohr                $this->embeddings->setLogger($this->logger);
943379af09SAndreas Gohr            }
959f6b34c4SAndreas Gohr        }
969f6b34c4SAndreas Gohr
970337f47fSAndreas Gohr        return $this->embeddings;
980337f47fSAndreas Gohr    }
990337f47fSAndreas Gohr
1000337f47fSAndreas Gohr    /**
10101f06932SAndreas Gohr     * Access the Storage interface
10201f06932SAndreas Gohr     *
10301f06932SAndreas Gohr     * @return AbstractStorage
10401f06932SAndreas Gohr     */
10501f06932SAndreas Gohr    public function getStorage()
10601f06932SAndreas Gohr    {
10701f06932SAndreas Gohr        if ($this->storage === null) {
10813dbfc23SAndreas Gohr            if ($this->getConf('pinecone_apikey')) {
10913dbfc23SAndreas Gohr                $this->storage = new PineconeStorage();
11013dbfc23SAndreas Gohr            } else {
11101f06932SAndreas Gohr                $this->storage = new SQLiteStorage();
11268b6fa79SAndreas Gohr            }
1138285fff9SAndreas Gohr
1143379af09SAndreas Gohr            if ($this->logger) {
1153379af09SAndreas Gohr                $this->storage->setLogger($this->logger);
1163379af09SAndreas Gohr            }
11701f06932SAndreas Gohr        }
11801f06932SAndreas Gohr
11901f06932SAndreas Gohr        return $this->storage;
12001f06932SAndreas Gohr    }
12101f06932SAndreas Gohr
12201f06932SAndreas Gohr    /**
1230337f47fSAndreas Gohr     * Ask a question with a chat history
1240337f47fSAndreas Gohr     *
1250337f47fSAndreas Gohr     * @param string $question
1260337f47fSAndreas Gohr     * @param array[] $history The chat history [[user, ai], [user, ai], ...]
1270337f47fSAndreas Gohr     * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources]
1280337f47fSAndreas Gohr     * @throws Exception
1290337f47fSAndreas Gohr     */
1300337f47fSAndreas Gohr    public function askChatQuestion($question, $history = [])
1310337f47fSAndreas Gohr    {
1320337f47fSAndreas Gohr        if ($history) {
1330337f47fSAndreas Gohr            $standaloneQuestion = $this->rephraseChatQuestion($question, $history);
134*754b8394SAndreas Gohr            $prev = end($history);
1350337f47fSAndreas Gohr        } else {
1360337f47fSAndreas Gohr            $standaloneQuestion = $question;
137*754b8394SAndreas Gohr            $prev = [];
1380337f47fSAndreas Gohr        }
139*754b8394SAndreas Gohr        return $this->askQuestion($standaloneQuestion, $prev);
1400337f47fSAndreas Gohr    }
1410337f47fSAndreas Gohr
1420337f47fSAndreas Gohr    /**
1430337f47fSAndreas Gohr     * Ask a single standalone question
1440337f47fSAndreas Gohr     *
1450337f47fSAndreas Gohr     * @param string $question
146*754b8394SAndreas Gohr     * @param array $previous [user, ai] of the previous question
1470337f47fSAndreas Gohr     * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources]
1480337f47fSAndreas Gohr     * @throws Exception
1490337f47fSAndreas Gohr     */
150*754b8394SAndreas Gohr    public function askQuestion($question, $previous = [])
1510337f47fSAndreas Gohr    {
1529f6b34c4SAndreas Gohr        $similar = $this->getEmbeddings()->getSimilarChunks($question);
1539e81bea7SAndreas Gohr        if ($similar) {
15455392016SAndreas Gohr            $context = implode("\n", array_map(function (Chunk $chunk) {
15568908844SAndreas Gohr                return "\n```\n" . $chunk->getText() . "\n```\n";
15655392016SAndreas Gohr            }, $similar));
157219268b1SAndreas Gohr            $prompt = $this->getPrompt('question', [
158219268b1SAndreas Gohr                'context' => $context,
159219268b1SAndreas Gohr                'language' => $this->getLanguagePrompt()
160219268b1SAndreas Gohr            ]);
1619e81bea7SAndreas Gohr        } else {
1629e81bea7SAndreas Gohr            $prompt = $this->getPrompt('noanswer');
1639e81bea7SAndreas Gohr        }
16468908844SAndreas Gohr
1650337f47fSAndreas Gohr        $messages = [
1660337f47fSAndreas Gohr            [
1670337f47fSAndreas Gohr                'role' => 'system',
1680337f47fSAndreas Gohr                'content' => $prompt
1690337f47fSAndreas Gohr            ],
1700337f47fSAndreas Gohr            [
1710337f47fSAndreas Gohr                'role' => 'user',
1720337f47fSAndreas Gohr                'content' => $question
1730337f47fSAndreas Gohr            ]
1740337f47fSAndreas Gohr        ];
1750337f47fSAndreas Gohr
176*754b8394SAndreas Gohr        if ($previous) {
177*754b8394SAndreas Gohr            array_unshift($messages, [
178*754b8394SAndreas Gohr                'role' => 'assistant',
179*754b8394SAndreas Gohr                'content' => $previous[1]
180*754b8394SAndreas Gohr            ]);
181*754b8394SAndreas Gohr            array_unshift($messages, [
182*754b8394SAndreas Gohr                'role' => 'user',
183*754b8394SAndreas Gohr                'content' => $previous[0]
184*754b8394SAndreas Gohr            ]);
185*754b8394SAndreas Gohr        }
186*754b8394SAndreas Gohr
1879f6b34c4SAndreas Gohr        $answer = $this->getModel()->getAnswer($messages);
1880337f47fSAndreas Gohr
1890337f47fSAndreas Gohr        return [
1900337f47fSAndreas Gohr            'question' => $question,
1910337f47fSAndreas Gohr            'answer' => $answer,
1920337f47fSAndreas Gohr            'sources' => $similar,
1930337f47fSAndreas Gohr        ];
1940337f47fSAndreas Gohr    }
1950337f47fSAndreas Gohr
1960337f47fSAndreas Gohr    /**
1970337f47fSAndreas Gohr     * Rephrase a question into a standalone question based on the chat history
1980337f47fSAndreas Gohr     *
1990337f47fSAndreas Gohr     * @param string $question The original user question
2000337f47fSAndreas Gohr     * @param array[] $history The chat history [[user, ai], [user, ai], ...]
2010337f47fSAndreas Gohr     * @return string The rephrased question
2020337f47fSAndreas Gohr     * @throws Exception
2030337f47fSAndreas Gohr     */
2040337f47fSAndreas Gohr    public function rephraseChatQuestion($question, $history)
2050337f47fSAndreas Gohr    {
2060337f47fSAndreas Gohr        // go back in history as far as possible without hitting the token limit
2070337f47fSAndreas Gohr        $chatHistory = '';
2080337f47fSAndreas Gohr        $history = array_reverse($history);
2090337f47fSAndreas Gohr        foreach ($history as $row) {
210f6ef2e50SAndreas Gohr            if (
2119f6b34c4SAndreas Gohr                count($this->getEmbeddings()->getTokenEncoder()->encode($chatHistory)) >
2129f6b34c4SAndreas Gohr                $this->getModel()->getMaxRephrasingTokenLength()
213f6ef2e50SAndreas Gohr            ) {
2140337f47fSAndreas Gohr                break;
2150337f47fSAndreas Gohr            }
2160337f47fSAndreas Gohr
2170337f47fSAndreas Gohr            $chatHistory =
2180337f47fSAndreas Gohr                "Human: " . $row[0] . "\n" .
2190337f47fSAndreas Gohr                "Assistant: " . $row[1] . "\n" .
2200337f47fSAndreas Gohr                $chatHistory;
2210337f47fSAndreas Gohr        }
2220337f47fSAndreas Gohr
2230337f47fSAndreas Gohr        // ask openAI to rephrase the question
2240337f47fSAndreas Gohr        $prompt = $this->getPrompt('rephrase', ['history' => $chatHistory, 'question' => $question]);
2250337f47fSAndreas Gohr        $messages = [['role' => 'user', 'content' => $prompt]];
2269f6b34c4SAndreas Gohr        return $this->getModel()->getRephrasedQuestion($messages);
2270337f47fSAndreas Gohr    }
2280337f47fSAndreas Gohr
2290337f47fSAndreas Gohr    /**
2300337f47fSAndreas Gohr     * Load the given prompt template and fill in the variables
2310337f47fSAndreas Gohr     *
2320337f47fSAndreas Gohr     * @param string $type
2330337f47fSAndreas Gohr     * @param string[] $vars
2340337f47fSAndreas Gohr     * @return string
2350337f47fSAndreas Gohr     */
2360337f47fSAndreas Gohr    protected function getPrompt($type, $vars = [])
2370337f47fSAndreas Gohr    {
2380337f47fSAndreas Gohr        $template = file_get_contents($this->localFN('prompt_' . $type));
2390337f47fSAndreas Gohr
2400337f47fSAndreas Gohr        $replace = array();
2410337f47fSAndreas Gohr        foreach ($vars as $key => $val) {
2420337f47fSAndreas Gohr            $replace['{{' . strtoupper($key) . '}}'] = $val;
2430337f47fSAndreas Gohr        }
2440337f47fSAndreas Gohr
2450337f47fSAndreas Gohr        return strtr($template, $replace);
2460337f47fSAndreas Gohr    }
247219268b1SAndreas Gohr
248219268b1SAndreas Gohr    /**
249219268b1SAndreas Gohr     * Construct the prompt to define the answer language
250219268b1SAndreas Gohr     *
251219268b1SAndreas Gohr     * @return string
252219268b1SAndreas Gohr     */
253219268b1SAndreas Gohr    protected function getLanguagePrompt()
254219268b1SAndreas Gohr    {
255219268b1SAndreas Gohr        global $conf;
256219268b1SAndreas Gohr
257219268b1SAndreas Gohr        if ($this->getConf('preferUIlanguage')) {
258219268b1SAndreas Gohr            $isoLangnames = include(__DIR__ . '/lang/languages.php');
259219268b1SAndreas Gohr            if (isset($isoLangnames[$conf['lang']])) {
260219268b1SAndreas Gohr                $languagePrompt = 'Always answer in ' . $isoLangnames[$conf['lang']] . '.';
261219268b1SAndreas Gohr                return $languagePrompt;
262219268b1SAndreas Gohr            }
263219268b1SAndreas Gohr        }
264219268b1SAndreas Gohr
265219268b1SAndreas Gohr        $languagePrompt = 'Always answer in the user\'s language.';
266219268b1SAndreas Gohr        return $languagePrompt;
267219268b1SAndreas Gohr    }
2680337f47fSAndreas Gohr}
2690337f47fSAndreas Gohr
270