xref: /plugin/aichat/helper.php (revision 0de7e020fcc340c97acd36e48cdb20a9d43528b6)
1<?php
2
3use dokuwiki\Extension\CLIPlugin;
4use dokuwiki\Extension\Plugin;
5use dokuwiki\plugin\aichat\AIChat;
6use dokuwiki\plugin\aichat\Chunk;
7use dokuwiki\plugin\aichat\Embeddings;
8use dokuwiki\plugin\aichat\Model\ChatInterface;
9use dokuwiki\plugin\aichat\Model\EmbeddingInterface;
10use dokuwiki\plugin\aichat\ModelFactory;
11use dokuwiki\plugin\aichat\Storage\AbstractStorage;
12
13/**
14 * DokuWiki Plugin aichat (Helper Component)
15 *
16 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
17 * @author  Andreas Gohr <gohr@cosmocode.de>
18 */
19class helper_plugin_aichat extends Plugin
20{
21    /** @var ModelFactory */
22    public $factory;
23
24    /** @var CLIPlugin $logger */
25    protected $logger;
26
27    /** @var Embeddings */
28    protected $embeddings;
29    /** @var AbstractStorage */
30    protected $storage;
31
32    /** @var array where to store meta data on the last run */
33    protected $runDataFile;
34
35
36    /**
37     * Constructor. Initializes vendor autoloader
38     */
39    public function __construct()
40    {
41        require_once __DIR__ . '/vendor/autoload.php'; // FIXME obsolete from Kaos onwards
42        global $conf;
43        $this->runDataFile = $conf['metadir'] . '/aichat__run.json';
44        $this->loadConfig();
45        $this->factory = new ModelFactory($this->conf);
46    }
47
48    /**
49     * Use the given CLI plugin for logging
50     *
51     * @param CLIPlugin $logger
52     * @return void
53     */
54    public function setLogger($logger)
55    {
56        $this->logger = $logger;
57    }
58
59    /**
60     * Update the configuration
61     *
62     * @param array $config
63     * @return void
64     */
65    public function updateConfig(array $config)
66    {
67        $this->conf = array_merge($this->conf, $config);
68        $this->factory->updateConfig($config);
69    }
70
71    /**
72     * Check if the current user is allowed to use the plugin (if it has been restricted)
73     *
74     * @return bool
75     */
76    public function userMayAccess()
77    {
78        global $auth;
79        global $USERINFO;
80        global $INPUT;
81
82        if (!$auth) return true;
83        if (!$this->getConf('restrict')) return true;
84        if (!isset($USERINFO)) return false;
85
86        return auth_isMember($this->getConf('restrict'), $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']);
87    }
88
89    /**
90     * Access the Chat Model
91     *
92     * @return ChatInterface
93     */
94    public function getChatModel()
95    {
96        return $this->factory->getChatModel();
97    }
98
99    /**
100     * @return ChatInterface
101     */
102    public function getRephraseModel()
103    {
104        return $this->factory->getRephraseModel();
105    }
106
107    /**
108     * Access the Embedding Model
109     *
110     * @return EmbeddingInterface
111     */
112    public function getEmbeddingModel()
113    {
114        return $this->factory->getEmbeddingModel();
115    }
116
117    /**
118     * Access the Embeddings interface
119     *
120     * @return Embeddings
121     */
122    public function getEmbeddings()
123    {
124        if ($this->embeddings instanceof Embeddings) {
125            return $this->embeddings;
126        }
127
128        $this->embeddings = new Embeddings(
129            $this->getChatModel(),
130            $this->getEmbeddingModel(),
131            $this->getStorage(),
132            $this->conf
133        );
134        if ($this->logger) {
135            $this->embeddings->setLogger($this->logger);
136        }
137
138        return $this->embeddings;
139    }
140
141    /**
142     * Access the Storage interface
143     *
144     * @return AbstractStorage
145     */
146    public function getStorage()
147    {
148        if ($this->storage instanceof AbstractStorage) {
149            return $this->storage;
150        }
151
152        $class = '\\dokuwiki\\plugin\\aichat\\Storage\\' . $this->getConf('storage') . 'Storage';
153        $this->storage = new $class($this->conf);
154
155        if ($this->logger) {
156            $this->storage->setLogger($this->logger);
157        }
158
159        return $this->storage;
160    }
161
162    /**
163     * Ask a question with a chat history
164     *
165     * @param string $question
166     * @param array[] $history The chat history [[user, ai], [user, ai], ...]
167     * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources]
168     * @throws Exception
169     */
170    public function askChatQuestion($question, $history = [])
171    {
172        if ($history && $this->getConf('rephraseHistory') > 0) {
173            $standaloneQuestion = $this->rephraseChatQuestion($question, $history);
174        } else {
175            $standaloneQuestion = $question;
176        }
177        return $this->askQuestion($standaloneQuestion, $history);
178    }
179
180    /**
181     * Ask a single standalone question
182     *
183     * @param string $question
184     * @param array $history [user, ai] of the previous question
185     * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources]
186     * @throws Exception
187     */
188    public function askQuestion($question, $history = [])
189    {
190        $similar = $this->getEmbeddings()->getSimilarChunks($question, $this->getLanguageLimit());
191        if ($similar) {
192            $context = implode(
193                "\n",
194                array_map(static fn(Chunk $chunk) => "\n```\n" . $chunk->getText() . "\n```\n", $similar)
195            );
196            $prompt = $this->getPrompt('question', [
197                'context' => $context,
198                'question' => $question,
199            ]);
200        } else {
201            $prompt = $this->getPrompt('noanswer', [
202                'question' => $question,
203            ]);
204            $history = [];
205        }
206
207        $messages = $this->prepareMessages(
208            $this->getChatModel(),
209            $prompt,
210            $history,
211            $this->getConf('chatHistory')
212        );
213        $answer = $this->getChatModel()->getAnswer($messages);
214
215        return [
216            'question' => $question,
217            'answer' => $answer,
218            'sources' => $similar,
219        ];
220    }
221
222    /**
223     * Rephrase a question into a standalone question based on the chat history
224     *
225     * @param string $question The original user question
226     * @param array[] $history The chat history [[user, ai], [user, ai], ...]
227     * @return string The rephrased question
228     * @throws Exception
229     */
230    public function rephraseChatQuestion($question, $history)
231    {
232        $prompt = $this->getPrompt('rephrase', [
233            'question' => $question,
234        ]);
235        $messages = $this->prepareMessages(
236            $this->getRephraseModel(),
237            $prompt,
238            $history,
239            $this->getConf('rephraseHistory')
240        );
241        return $this->getRephraseModel()->getAnswer($messages);
242    }
243
244    /**
245     * Prepare the messages for the AI
246     *
247     * @param ChatInterface $model The used model
248     * @param string $promptedQuestion The user question embedded in a prompt
249     * @param array[] $history The chat history [[user, ai], [user, ai], ...]
250     * @param int $historySize The maximum number of messages to use from the history
251     * @return array An OpenAI compatible array of messages
252     */
253    protected function prepareMessages(
254        ChatInterface $model,
255        string        $promptedQuestion,
256        array         $history,
257        int           $historySize
258    ): array
259    {
260        // calculate the space for context
261        $remainingContext = $model->getMaxInputTokenLength();
262        $remainingContext -= $this->countTokens($promptedQuestion);
263        $safetyMargin = $remainingContext * 0.05; // 5% safety margin
264        $remainingContext -= $safetyMargin;
265        // FIXME we may want to also have an upper limit for the history and not always use the full context
266
267        $messages = $this->historyMessages($history, $remainingContext, $historySize);
268        $messages[] = [
269            'role' => 'user',
270            'content' => $promptedQuestion
271        ];
272        return $messages;
273    }
274
275    /**
276     * Create an array of OpenAI compatible messages from the given history
277     *
278     * Only as many messages are used as fit into the token limit
279     *
280     * @param array[] $history The chat history [[user, ai], [user, ai], ...]
281     * @param int $tokenLimit The maximum number of tokens to use
282     * @param int $sizeLimit The maximum number of messages to use
283     * @return array
284     */
285    protected function historyMessages(array $history, int $tokenLimit, int $sizeLimit): array
286    {
287        $remainingContext = $tokenLimit;
288
289        $messages = [];
290        $history = array_reverse($history);
291        $history = array_slice($history, 0, $sizeLimit);
292        foreach ($history as $row) {
293            $length = $this->countTokens($row[0] . $row[1]);
294            if ($length > $remainingContext) {
295                break;
296            }
297            $remainingContext -= $length;
298
299            $messages[] = [
300                'role' => 'assistant',
301                'content' => $row[1]
302            ];
303            $messages[] = [
304                'role' => 'user',
305                'content' => $row[0]
306            ];
307        }
308        return array_reverse($messages);
309    }
310
311    /**
312     * Get an aproximation of the token count for the given text
313     *
314     * @param $text
315     * @return int
316     */
317    protected function countTokens($text)
318    {
319        return count($this->getEmbeddings()->getTokenEncoder()->encode($text));
320    }
321
322    /**
323     * Load the given prompt template and fill in the variables
324     *
325     * @param string $type
326     * @param string[] $vars
327     * @return string
328     */
329    protected function getPrompt($type, $vars = [])
330    {
331        $template = file_get_contents($this->localFN($type, 'prompt'));
332        $vars['language'] = $this->getLanguagePrompt();
333
334        $replace = [];
335        foreach ($vars as $key => $val) {
336            $replace['{{' . strtoupper($key) . '}}'] = $val;
337        }
338
339        return strtr($template, $replace);
340    }
341
342    /**
343     * Construct the prompt to define the answer language
344     *
345     * @return string
346     */
347    protected function getLanguagePrompt()
348    {
349        global $conf;
350        $isoLangnames = include(__DIR__ . '/lang/languages.php');
351
352        $currentLang = $isoLangnames[$conf['lang']] ?? 'English';
353
354        if ($this->getConf('preferUIlanguage') > AIChat::LANG_AUTO_ALL) {
355            if (isset($isoLangnames[$conf['lang']])) {
356                $languagePrompt = 'Always answer in ' . $isoLangnames[$conf['lang']] . '.';
357                return $languagePrompt;
358            }
359        }
360
361        $languagePrompt = 'Always answer in the user\'s language. ' .
362            "If you are unsure about the language, speak $currentLang.";
363        return $languagePrompt;
364    }
365
366    /**
367     * Should sources be limited to current language?
368     *
369     * @return string The current language code or empty string
370     */
371    public function getLanguageLimit()
372    {
373        if ($this->getConf('preferUIlanguage') >= AIChat::LANG_UI_LIMITED) {
374            global $conf;
375            return $conf['lang'];
376        } else {
377            return '';
378        }
379    }
380
381    /**
382     * Store info about the last run
383     *
384     * @param array $data
385     * @return void
386     */
387    public function setRunData(array $data)
388    {
389        file_put_contents($this->runDataFile, json_encode($data, JSON_PRETTY_PRINT));
390    }
391
392    /**
393     * Get info about the last run
394     *
395     * @return array
396     */
397    public function getRunData()
398    {
399        if (!file_exists($this->runDataFile)) {
400            return [];
401        }
402        return json_decode(file_get_contents($this->runDataFile), true);
403    }
404}
405