xref: /plugin/aichat/helper.php (revision 441edf84da4c031892d23b5809b2adfb59c6d774)
10337f47fSAndreas Gohr<?php
20337f47fSAndreas Gohr
33379af09SAndreas Gohruse dokuwiki\Extension\CLIPlugin;
45e6dd16eSAndreas Gohruse dokuwiki\Extension\Plugin;
5e33a1d7aSAndreas Gohruse dokuwiki\plugin\aichat\AIChat;
6f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Chunk;
70337f47fSAndreas Gohruse dokuwiki\plugin\aichat\Embeddings;
8754b8394SAndreas Gohruse dokuwiki\plugin\aichat\Model\AbstractModel;
9f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Model\OpenAI\GPT35Turbo;
1001f06932SAndreas Gohruse dokuwiki\plugin\aichat\Storage\AbstractStorage;
115e6dd16eSAndreas Gohruse dokuwiki\plugin\aichat\Storage\ChromaStorage;
1213dbfc23SAndreas Gohruse dokuwiki\plugin\aichat\Storage\PineconeStorage;
13f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Storage\SQLiteStorage;
140337f47fSAndreas Gohr
150337f47fSAndreas Gohr/**
160337f47fSAndreas Gohr * DokuWiki Plugin aichat (Helper Component)
170337f47fSAndreas Gohr *
180337f47fSAndreas Gohr * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
190337f47fSAndreas Gohr * @author  Andreas Gohr <gohr@cosmocode.de>
200337f47fSAndreas Gohr */
217ebc7895Ssplitbrainclass helper_plugin_aichat extends Plugin
220337f47fSAndreas Gohr{
233379af09SAndreas Gohr    /** @var CLIPlugin $logger */
243379af09SAndreas Gohr    protected $logger;
25f6ef2e50SAndreas Gohr    /** @var AbstractModel */
26f6ef2e50SAndreas Gohr    protected $model;
270337f47fSAndreas Gohr    /** @var Embeddings */
280337f47fSAndreas Gohr    protected $embeddings;
2901f06932SAndreas Gohr    /** @var AbstractStorage */
3001f06932SAndreas Gohr    protected $storage;
310337f47fSAndreas Gohr
320337f47fSAndreas Gohr    /**
33f8d5ae01SAndreas Gohr     * Constructor. Initializes vendor autoloader
34f8d5ae01SAndreas Gohr     */
35f8d5ae01SAndreas Gohr    public function __construct()
36f8d5ae01SAndreas Gohr    {
37f8d5ae01SAndreas Gohr        require_once __DIR__ . '/vendor/autoload.php';
38f8d5ae01SAndreas Gohr    }
39f8d5ae01SAndreas Gohr
40f8d5ae01SAndreas Gohr    /**
413379af09SAndreas Gohr     * Use the given CLI plugin for logging
423379af09SAndreas Gohr     *
433379af09SAndreas Gohr     * @param CLIPlugin $logger
443379af09SAndreas Gohr     * @return void
453379af09SAndreas Gohr     */
468285fff9SAndreas Gohr    public function setLogger($logger)
478285fff9SAndreas Gohr    {
483379af09SAndreas Gohr        $this->logger = $logger;
493379af09SAndreas Gohr    }
503379af09SAndreas Gohr
513379af09SAndreas Gohr    /**
52c4127b8eSAndreas Gohr     * Check if the current user is allowed to use the plugin (if it has been restricted)
53c4127b8eSAndreas Gohr     *
54c4127b8eSAndreas Gohr     * @return bool
55c4127b8eSAndreas Gohr     */
56c4127b8eSAndreas Gohr    public function userMayAccess()
57c4127b8eSAndreas Gohr    {
58c4127b8eSAndreas Gohr        global $auth;
59c4127b8eSAndreas Gohr        global $USERINFO;
60c4127b8eSAndreas Gohr        global $INPUT;
61c4127b8eSAndreas Gohr
62c4127b8eSAndreas Gohr        if (!$auth) return true;
63c4127b8eSAndreas Gohr        if (!$this->getConf('restrict')) return true;
64c4127b8eSAndreas Gohr        if (!isset($USERINFO)) return false;
65c4127b8eSAndreas Gohr
66c4127b8eSAndreas Gohr        return auth_isMember($this->getConf('restrict'), $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']);
67c4127b8eSAndreas Gohr    }
68c4127b8eSAndreas Gohr
69c4127b8eSAndreas Gohr    /**
700337f47fSAndreas Gohr     * Access the OpenAI client
710337f47fSAndreas Gohr     *
72f6ef2e50SAndreas Gohr     * @return GPT35Turbo
730337f47fSAndreas Gohr     */
74f6ef2e50SAndreas Gohr    public function getModel()
750337f47fSAndreas Gohr    {
767ebc7895Ssplitbrain        if (!$this->model instanceof AbstractModel) {
779f6b34c4SAndreas Gohr            $class = '\\dokuwiki\\plugin\\aichat\\Model\\' . $this->getConf('model');
789f6b34c4SAndreas Gohr
799f6b34c4SAndreas Gohr            if (!class_exists($class)) {
809f6b34c4SAndreas Gohr                throw new \RuntimeException('Configured model not found: ' . $class);
819f6b34c4SAndreas Gohr            }
829f6b34c4SAndreas Gohr            // FIXME for now we only have OpenAI models, so we can hardcode the auth setup
839f6b34c4SAndreas Gohr            $this->model = new $class([
849f6b34c4SAndreas Gohr                'key' => $this->getConf('openaikey'),
859f6b34c4SAndreas Gohr                'org' => $this->getConf('openaiorg')
869f6b34c4SAndreas Gohr            ]);
879f6b34c4SAndreas Gohr        }
889f6b34c4SAndreas Gohr
89f6ef2e50SAndreas Gohr        return $this->model;
900337f47fSAndreas Gohr    }
910337f47fSAndreas Gohr
920337f47fSAndreas Gohr    /**
930337f47fSAndreas Gohr     * Access the Embeddings interface
940337f47fSAndreas Gohr     *
950337f47fSAndreas Gohr     * @return Embeddings
960337f47fSAndreas Gohr     */
970337f47fSAndreas Gohr    public function getEmbeddings()
980337f47fSAndreas Gohr    {
997ebc7895Ssplitbrain        if (!$this->embeddings instanceof Embeddings) {
10001f06932SAndreas Gohr            $this->embeddings = new Embeddings($this->getModel(), $this->getStorage());
1013379af09SAndreas Gohr            if ($this->logger) {
1023379af09SAndreas Gohr                $this->embeddings->setLogger($this->logger);
1033379af09SAndreas Gohr            }
1049f6b34c4SAndreas Gohr        }
1059f6b34c4SAndreas Gohr
1060337f47fSAndreas Gohr        return $this->embeddings;
1070337f47fSAndreas Gohr    }
1080337f47fSAndreas Gohr
1090337f47fSAndreas Gohr    /**
11001f06932SAndreas Gohr     * Access the Storage interface
11101f06932SAndreas Gohr     *
11201f06932SAndreas Gohr     * @return AbstractStorage
11301f06932SAndreas Gohr     */
11401f06932SAndreas Gohr    public function getStorage()
11501f06932SAndreas Gohr    {
1167ebc7895Ssplitbrain        if (!$this->storage instanceof AbstractStorage) {
11713dbfc23SAndreas Gohr            if ($this->getConf('pinecone_apikey')) {
11813dbfc23SAndreas Gohr                $this->storage = new PineconeStorage();
1195e6dd16eSAndreas Gohr            } elseif ($this->getConf('chroma_baseurl')) {
1205e6dd16eSAndreas Gohr                $this->storage = new ChromaStorage();
12113dbfc23SAndreas Gohr            } else {
12201f06932SAndreas Gohr                $this->storage = new SQLiteStorage();
12368b6fa79SAndreas Gohr            }
1248285fff9SAndreas Gohr
1253379af09SAndreas Gohr            if ($this->logger) {
1263379af09SAndreas Gohr                $this->storage->setLogger($this->logger);
1273379af09SAndreas Gohr            }
12801f06932SAndreas Gohr        }
12901f06932SAndreas Gohr
13001f06932SAndreas Gohr        return $this->storage;
13101f06932SAndreas Gohr    }
13201f06932SAndreas Gohr
13301f06932SAndreas Gohr    /**
1340337f47fSAndreas Gohr     * Ask a question with a chat history
1350337f47fSAndreas Gohr     *
1360337f47fSAndreas Gohr     * @param string $question
1370337f47fSAndreas Gohr     * @param array[] $history The chat history [[user, ai], [user, ai], ...]
1380337f47fSAndreas Gohr     * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources]
1390337f47fSAndreas Gohr     * @throws Exception
1400337f47fSAndreas Gohr     */
1410337f47fSAndreas Gohr    public function askChatQuestion($question, $history = [])
1420337f47fSAndreas Gohr    {
1430337f47fSAndreas Gohr        if ($history) {
1440337f47fSAndreas Gohr            $standaloneQuestion = $this->rephraseChatQuestion($question, $history);
145754b8394SAndreas Gohr            $prev = end($history);
1460337f47fSAndreas Gohr        } else {
1470337f47fSAndreas Gohr            $standaloneQuestion = $question;
148754b8394SAndreas Gohr            $prev = [];
1490337f47fSAndreas Gohr        }
150754b8394SAndreas Gohr        return $this->askQuestion($standaloneQuestion, $prev);
1510337f47fSAndreas Gohr    }
1520337f47fSAndreas Gohr
1530337f47fSAndreas Gohr    /**
1540337f47fSAndreas Gohr     * Ask a single standalone question
1550337f47fSAndreas Gohr     *
1560337f47fSAndreas Gohr     * @param string $question
157754b8394SAndreas Gohr     * @param array $previous [user, ai] of the previous question
1580337f47fSAndreas Gohr     * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources]
1590337f47fSAndreas Gohr     * @throws Exception
1600337f47fSAndreas Gohr     */
161754b8394SAndreas Gohr    public function askQuestion($question, $previous = [])
1620337f47fSAndreas Gohr    {
163e33a1d7aSAndreas Gohr        $similar = $this->getEmbeddings()->getSimilarChunks($question, $this->getLanguageLimit());
1649e81bea7SAndreas Gohr        if ($similar) {
165*441edf84SAndreas Gohr            $context = implode(
166*441edf84SAndreas Gohr                "\n",
167*441edf84SAndreas Gohr                array_map(static fn(Chunk $chunk) => "\n```\n" . $chunk->getText() . "\n```\n", $similar)
168*441edf84SAndreas Gohr            );
169219268b1SAndreas Gohr            $prompt = $this->getPrompt('question', [
170219268b1SAndreas Gohr                'context' => $context,
171219268b1SAndreas Gohr                'language' => $this->getLanguagePrompt()
172219268b1SAndreas Gohr            ]);
1739e81bea7SAndreas Gohr        } else {
1749e81bea7SAndreas Gohr            $prompt = $this->getPrompt('noanswer');
1759e81bea7SAndreas Gohr        }
17668908844SAndreas Gohr
1770337f47fSAndreas Gohr        $messages = [
1780337f47fSAndreas Gohr            [
1790337f47fSAndreas Gohr                'role' => 'system',
1800337f47fSAndreas Gohr                'content' => $prompt
1810337f47fSAndreas Gohr            ],
1820337f47fSAndreas Gohr            [
1830337f47fSAndreas Gohr                'role' => 'user',
1840337f47fSAndreas Gohr                'content' => $question
1850337f47fSAndreas Gohr            ]
1860337f47fSAndreas Gohr        ];
1870337f47fSAndreas Gohr
188754b8394SAndreas Gohr        if ($previous) {
189754b8394SAndreas Gohr            array_unshift($messages, [
190754b8394SAndreas Gohr                'role' => 'assistant',
191754b8394SAndreas Gohr                'content' => $previous[1]
192754b8394SAndreas Gohr            ]);
193754b8394SAndreas Gohr            array_unshift($messages, [
194754b8394SAndreas Gohr                'role' => 'user',
195754b8394SAndreas Gohr                'content' => $previous[0]
196754b8394SAndreas Gohr            ]);
197754b8394SAndreas Gohr        }
198754b8394SAndreas Gohr
1999f6b34c4SAndreas Gohr        $answer = $this->getModel()->getAnswer($messages);
2000337f47fSAndreas Gohr
2010337f47fSAndreas Gohr        return [
2020337f47fSAndreas Gohr            'question' => $question,
2030337f47fSAndreas Gohr            'answer' => $answer,
2040337f47fSAndreas Gohr            'sources' => $similar,
2050337f47fSAndreas Gohr        ];
2060337f47fSAndreas Gohr    }
2070337f47fSAndreas Gohr
2080337f47fSAndreas Gohr    /**
2090337f47fSAndreas Gohr     * Rephrase a question into a standalone question based on the chat history
2100337f47fSAndreas Gohr     *
2110337f47fSAndreas Gohr     * @param string $question The original user question
2120337f47fSAndreas Gohr     * @param array[] $history The chat history [[user, ai], [user, ai], ...]
2130337f47fSAndreas Gohr     * @return string The rephrased question
2140337f47fSAndreas Gohr     * @throws Exception
2150337f47fSAndreas Gohr     */
2160337f47fSAndreas Gohr    public function rephraseChatQuestion($question, $history)
2170337f47fSAndreas Gohr    {
2180337f47fSAndreas Gohr        // go back in history as far as possible without hitting the token limit
2190337f47fSAndreas Gohr        $chatHistory = '';
2200337f47fSAndreas Gohr        $history = array_reverse($history);
2210337f47fSAndreas Gohr        foreach ($history as $row) {
222f6ef2e50SAndreas Gohr            if (
2239f6b34c4SAndreas Gohr                count($this->getEmbeddings()->getTokenEncoder()->encode($chatHistory)) >
2249f6b34c4SAndreas Gohr                $this->getModel()->getMaxRephrasingTokenLength()
225f6ef2e50SAndreas Gohr            ) {
2260337f47fSAndreas Gohr                break;
2270337f47fSAndreas Gohr            }
2280337f47fSAndreas Gohr
2290337f47fSAndreas Gohr            $chatHistory =
2300337f47fSAndreas Gohr                "Human: " . $row[0] . "\n" .
2310337f47fSAndreas Gohr                "Assistant: " . $row[1] . "\n" .
2320337f47fSAndreas Gohr                $chatHistory;
2330337f47fSAndreas Gohr        }
2340337f47fSAndreas Gohr
2350337f47fSAndreas Gohr        // ask openAI to rephrase the question
2360337f47fSAndreas Gohr        $prompt = $this->getPrompt('rephrase', ['history' => $chatHistory, 'question' => $question]);
2370337f47fSAndreas Gohr        $messages = [['role' => 'user', 'content' => $prompt]];
2389f6b34c4SAndreas Gohr        return $this->getModel()->getRephrasedQuestion($messages);
2390337f47fSAndreas Gohr    }
2400337f47fSAndreas Gohr
2410337f47fSAndreas Gohr    /**
2420337f47fSAndreas Gohr     * Load the given prompt template and fill in the variables
2430337f47fSAndreas Gohr     *
2440337f47fSAndreas Gohr     * @param string $type
2450337f47fSAndreas Gohr     * @param string[] $vars
2460337f47fSAndreas Gohr     * @return string
2470337f47fSAndreas Gohr     */
2480337f47fSAndreas Gohr    protected function getPrompt($type, $vars = [])
2490337f47fSAndreas Gohr    {
2500337f47fSAndreas Gohr        $template = file_get_contents($this->localFN('prompt_' . $type));
2510337f47fSAndreas Gohr
2527ebc7895Ssplitbrain        $replace = [];
2530337f47fSAndreas Gohr        foreach ($vars as $key => $val) {
2540337f47fSAndreas Gohr            $replace['{{' . strtoupper($key) . '}}'] = $val;
2550337f47fSAndreas Gohr        }
2560337f47fSAndreas Gohr
2570337f47fSAndreas Gohr        return strtr($template, $replace);
2580337f47fSAndreas Gohr    }
259219268b1SAndreas Gohr
260219268b1SAndreas Gohr    /**
261219268b1SAndreas Gohr     * Construct the prompt to define the answer language
262219268b1SAndreas Gohr     *
263219268b1SAndreas Gohr     * @return string
264219268b1SAndreas Gohr     */
265219268b1SAndreas Gohr    protected function getLanguagePrompt()
266219268b1SAndreas Gohr    {
267219268b1SAndreas Gohr        global $conf;
268219268b1SAndreas Gohr
269e33a1d7aSAndreas Gohr        if ($this->getConf('preferUIlanguage') > AIChat::LANG_AUTO_ALL) {
270219268b1SAndreas Gohr            $isoLangnames = include(__DIR__ . '/lang/languages.php');
271219268b1SAndreas Gohr            if (isset($isoLangnames[$conf['lang']])) {
272219268b1SAndreas Gohr                $languagePrompt = 'Always answer in ' . $isoLangnames[$conf['lang']] . '.';
273219268b1SAndreas Gohr                return $languagePrompt;
274219268b1SAndreas Gohr            }
275219268b1SAndreas Gohr        }
276219268b1SAndreas Gohr
277219268b1SAndreas Gohr        $languagePrompt = 'Always answer in the user\'s language.';
278219268b1SAndreas Gohr        return $languagePrompt;
279219268b1SAndreas Gohr    }
280e33a1d7aSAndreas Gohr
281e33a1d7aSAndreas Gohr    /**
282e33a1d7aSAndreas Gohr     * Should sources be limited to current language?
283e33a1d7aSAndreas Gohr     *
284e33a1d7aSAndreas Gohr     * @return string The current language code or empty string
285e33a1d7aSAndreas Gohr     */
286e33a1d7aSAndreas Gohr    public function getLanguageLimit()
287e33a1d7aSAndreas Gohr    {
288e33a1d7aSAndreas Gohr        if ($this->getConf('preferUIlanguage') >= AIChat::LANG_UI_LIMITED) {
289e33a1d7aSAndreas Gohr            global $conf;
290e33a1d7aSAndreas Gohr            return $conf['lang'];
291e33a1d7aSAndreas Gohr        } else {
292e33a1d7aSAndreas Gohr            return '';
293e33a1d7aSAndreas Gohr        }
294e33a1d7aSAndreas Gohr    }
2950337f47fSAndreas Gohr}
296