10337f47fSAndreas Gohr<?php 20337f47fSAndreas Gohr 3*7ebc7895Ssplitbrainuse dokuwiki\Extension\Plugin; 43379af09SAndreas Gohruse dokuwiki\Extension\CLIPlugin; 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; 1113dbfc23SAndreas Gohruse dokuwiki\plugin\aichat\Storage\PineconeStorage; 12f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Storage\SQLiteStorage; 130337f47fSAndreas Gohr 140337f47fSAndreas Gohrrequire_once __DIR__ . '/vendor/autoload.php'; 150337f47fSAndreas Gohr 160337f47fSAndreas Gohr/** 170337f47fSAndreas Gohr * DokuWiki Plugin aichat (Helper Component) 180337f47fSAndreas Gohr * 190337f47fSAndreas Gohr * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html 200337f47fSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de> 210337f47fSAndreas Gohr */ 22*7ebc7895Ssplitbrainclass helper_plugin_aichat extends Plugin 230337f47fSAndreas Gohr{ 243379af09SAndreas Gohr /** @var CLIPlugin $logger */ 253379af09SAndreas Gohr protected $logger; 26f6ef2e50SAndreas Gohr /** @var AbstractModel */ 27f6ef2e50SAndreas Gohr protected $model; 280337f47fSAndreas Gohr /** @var Embeddings */ 290337f47fSAndreas Gohr protected $embeddings; 3001f06932SAndreas Gohr /** @var AbstractStorage */ 3101f06932SAndreas Gohr protected $storage; 320337f47fSAndreas Gohr 330337f47fSAndreas Gohr /** 343379af09SAndreas Gohr * Use the given CLI plugin for logging 353379af09SAndreas Gohr * 363379af09SAndreas Gohr * @param CLIPlugin $logger 373379af09SAndreas Gohr * @return void 383379af09SAndreas Gohr */ 398285fff9SAndreas Gohr public function setLogger($logger) 408285fff9SAndreas Gohr { 413379af09SAndreas Gohr $this->logger = $logger; 423379af09SAndreas Gohr } 433379af09SAndreas Gohr 443379af09SAndreas Gohr /** 45c4127b8eSAndreas Gohr * Check if the current user is allowed to use the plugin (if it has been restricted) 46c4127b8eSAndreas Gohr * 47c4127b8eSAndreas Gohr * @return bool 48c4127b8eSAndreas Gohr */ 49c4127b8eSAndreas Gohr public function userMayAccess() 50c4127b8eSAndreas Gohr { 51c4127b8eSAndreas Gohr global $auth; 52c4127b8eSAndreas Gohr global $USERINFO; 53c4127b8eSAndreas Gohr global $INPUT; 54c4127b8eSAndreas Gohr 55c4127b8eSAndreas Gohr if (!$auth) return true; 56c4127b8eSAndreas Gohr if (!$this->getConf('restrict')) return true; 57c4127b8eSAndreas Gohr if (!isset($USERINFO)) return false; 58c4127b8eSAndreas Gohr 59c4127b8eSAndreas Gohr return auth_isMember($this->getConf('restrict'), $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']); 60c4127b8eSAndreas Gohr } 61c4127b8eSAndreas Gohr 62c4127b8eSAndreas Gohr /** 630337f47fSAndreas Gohr * Access the OpenAI client 640337f47fSAndreas Gohr * 65f6ef2e50SAndreas Gohr * @return GPT35Turbo 660337f47fSAndreas Gohr */ 67f6ef2e50SAndreas Gohr public function getModel() 680337f47fSAndreas Gohr { 69*7ebc7895Ssplitbrain if (!$this->model instanceof AbstractModel) { 709f6b34c4SAndreas Gohr $class = '\\dokuwiki\\plugin\\aichat\\Model\\' . $this->getConf('model'); 719f6b34c4SAndreas Gohr 729f6b34c4SAndreas Gohr if (!class_exists($class)) { 739f6b34c4SAndreas Gohr throw new \RuntimeException('Configured model not found: ' . $class); 749f6b34c4SAndreas Gohr } 759f6b34c4SAndreas Gohr // FIXME for now we only have OpenAI models, so we can hardcode the auth setup 769f6b34c4SAndreas Gohr $this->model = new $class([ 779f6b34c4SAndreas Gohr 'key' => $this->getConf('openaikey'), 789f6b34c4SAndreas Gohr 'org' => $this->getConf('openaiorg') 799f6b34c4SAndreas Gohr ]); 809f6b34c4SAndreas Gohr } 819f6b34c4SAndreas Gohr 82f6ef2e50SAndreas Gohr return $this->model; 830337f47fSAndreas Gohr } 840337f47fSAndreas Gohr 850337f47fSAndreas Gohr /** 860337f47fSAndreas Gohr * Access the Embeddings interface 870337f47fSAndreas Gohr * 880337f47fSAndreas Gohr * @return Embeddings 890337f47fSAndreas Gohr */ 900337f47fSAndreas Gohr public function getEmbeddings() 910337f47fSAndreas Gohr { 92*7ebc7895Ssplitbrain if (!$this->embeddings instanceof Embeddings) { 9301f06932SAndreas Gohr $this->embeddings = new Embeddings($this->getModel(), $this->getStorage()); 943379af09SAndreas Gohr if ($this->logger) { 953379af09SAndreas Gohr $this->embeddings->setLogger($this->logger); 963379af09SAndreas Gohr } 979f6b34c4SAndreas Gohr } 989f6b34c4SAndreas Gohr 990337f47fSAndreas Gohr return $this->embeddings; 1000337f47fSAndreas Gohr } 1010337f47fSAndreas Gohr 1020337f47fSAndreas Gohr /** 10301f06932SAndreas Gohr * Access the Storage interface 10401f06932SAndreas Gohr * 10501f06932SAndreas Gohr * @return AbstractStorage 10601f06932SAndreas Gohr */ 10701f06932SAndreas Gohr public function getStorage() 10801f06932SAndreas Gohr { 109*7ebc7895Ssplitbrain if (!$this->storage instanceof AbstractStorage) { 11013dbfc23SAndreas Gohr if ($this->getConf('pinecone_apikey')) { 11113dbfc23SAndreas Gohr $this->storage = new PineconeStorage(); 11213dbfc23SAndreas Gohr } else { 11301f06932SAndreas Gohr $this->storage = new SQLiteStorage(); 11468b6fa79SAndreas Gohr } 1158285fff9SAndreas Gohr 1163379af09SAndreas Gohr if ($this->logger) { 1173379af09SAndreas Gohr $this->storage->setLogger($this->logger); 1183379af09SAndreas Gohr } 11901f06932SAndreas Gohr } 12001f06932SAndreas Gohr 12101f06932SAndreas Gohr return $this->storage; 12201f06932SAndreas Gohr } 12301f06932SAndreas Gohr 12401f06932SAndreas Gohr /** 1250337f47fSAndreas Gohr * Ask a question with a chat history 1260337f47fSAndreas Gohr * 1270337f47fSAndreas Gohr * @param string $question 1280337f47fSAndreas Gohr * @param array[] $history The chat history [[user, ai], [user, ai], ...] 1290337f47fSAndreas Gohr * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources] 1300337f47fSAndreas Gohr * @throws Exception 1310337f47fSAndreas Gohr */ 1320337f47fSAndreas Gohr public function askChatQuestion($question, $history = []) 1330337f47fSAndreas Gohr { 1340337f47fSAndreas Gohr if ($history) { 1350337f47fSAndreas Gohr $standaloneQuestion = $this->rephraseChatQuestion($question, $history); 136754b8394SAndreas Gohr $prev = end($history); 1370337f47fSAndreas Gohr } else { 1380337f47fSAndreas Gohr $standaloneQuestion = $question; 139754b8394SAndreas Gohr $prev = []; 1400337f47fSAndreas Gohr } 141754b8394SAndreas Gohr return $this->askQuestion($standaloneQuestion, $prev); 1420337f47fSAndreas Gohr } 1430337f47fSAndreas Gohr 1440337f47fSAndreas Gohr /** 1450337f47fSAndreas Gohr * Ask a single standalone question 1460337f47fSAndreas Gohr * 1470337f47fSAndreas Gohr * @param string $question 148754b8394SAndreas Gohr * @param array $previous [user, ai] of the previous question 1490337f47fSAndreas Gohr * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources] 1500337f47fSAndreas Gohr * @throws Exception 1510337f47fSAndreas Gohr */ 152754b8394SAndreas Gohr public function askQuestion($question, $previous = []) 1530337f47fSAndreas Gohr { 154e33a1d7aSAndreas Gohr $similar = $this->getEmbeddings()->getSimilarChunks($question, $this->getLanguageLimit()); 1559e81bea7SAndreas Gohr if ($similar) { 15655392016SAndreas Gohr $context = implode("\n", array_map(function (Chunk $chunk) { 15768908844SAndreas Gohr return "\n```\n" . $chunk->getText() . "\n```\n"; 15855392016SAndreas Gohr }, $similar)); 159219268b1SAndreas Gohr $prompt = $this->getPrompt('question', [ 160219268b1SAndreas Gohr 'context' => $context, 161219268b1SAndreas Gohr 'language' => $this->getLanguagePrompt() 162219268b1SAndreas Gohr ]); 1639e81bea7SAndreas Gohr } else { 1649e81bea7SAndreas Gohr $prompt = $this->getPrompt('noanswer'); 1659e81bea7SAndreas Gohr } 16668908844SAndreas Gohr 1670337f47fSAndreas Gohr $messages = [ 1680337f47fSAndreas Gohr [ 1690337f47fSAndreas Gohr 'role' => 'system', 1700337f47fSAndreas Gohr 'content' => $prompt 1710337f47fSAndreas Gohr ], 1720337f47fSAndreas Gohr [ 1730337f47fSAndreas Gohr 'role' => 'user', 1740337f47fSAndreas Gohr 'content' => $question 1750337f47fSAndreas Gohr ] 1760337f47fSAndreas Gohr ]; 1770337f47fSAndreas Gohr 178754b8394SAndreas Gohr if ($previous) { 179754b8394SAndreas Gohr array_unshift($messages, [ 180754b8394SAndreas Gohr 'role' => 'assistant', 181754b8394SAndreas Gohr 'content' => $previous[1] 182754b8394SAndreas Gohr ]); 183754b8394SAndreas Gohr array_unshift($messages, [ 184754b8394SAndreas Gohr 'role' => 'user', 185754b8394SAndreas Gohr 'content' => $previous[0] 186754b8394SAndreas Gohr ]); 187754b8394SAndreas Gohr } 188754b8394SAndreas Gohr 1899f6b34c4SAndreas Gohr $answer = $this->getModel()->getAnswer($messages); 1900337f47fSAndreas Gohr 1910337f47fSAndreas Gohr return [ 1920337f47fSAndreas Gohr 'question' => $question, 1930337f47fSAndreas Gohr 'answer' => $answer, 1940337f47fSAndreas Gohr 'sources' => $similar, 1950337f47fSAndreas Gohr ]; 1960337f47fSAndreas Gohr } 1970337f47fSAndreas Gohr 1980337f47fSAndreas Gohr /** 1990337f47fSAndreas Gohr * Rephrase a question into a standalone question based on the chat history 2000337f47fSAndreas Gohr * 2010337f47fSAndreas Gohr * @param string $question The original user question 2020337f47fSAndreas Gohr * @param array[] $history The chat history [[user, ai], [user, ai], ...] 2030337f47fSAndreas Gohr * @return string The rephrased question 2040337f47fSAndreas Gohr * @throws Exception 2050337f47fSAndreas Gohr */ 2060337f47fSAndreas Gohr public function rephraseChatQuestion($question, $history) 2070337f47fSAndreas Gohr { 2080337f47fSAndreas Gohr // go back in history as far as possible without hitting the token limit 2090337f47fSAndreas Gohr $chatHistory = ''; 2100337f47fSAndreas Gohr $history = array_reverse($history); 2110337f47fSAndreas Gohr foreach ($history as $row) { 212f6ef2e50SAndreas Gohr if ( 2139f6b34c4SAndreas Gohr count($this->getEmbeddings()->getTokenEncoder()->encode($chatHistory)) > 2149f6b34c4SAndreas Gohr $this->getModel()->getMaxRephrasingTokenLength() 215f6ef2e50SAndreas Gohr ) { 2160337f47fSAndreas Gohr break; 2170337f47fSAndreas Gohr } 2180337f47fSAndreas Gohr 2190337f47fSAndreas Gohr $chatHistory = 2200337f47fSAndreas Gohr "Human: " . $row[0] . "\n" . 2210337f47fSAndreas Gohr "Assistant: " . $row[1] . "\n" . 2220337f47fSAndreas Gohr $chatHistory; 2230337f47fSAndreas Gohr } 2240337f47fSAndreas Gohr 2250337f47fSAndreas Gohr // ask openAI to rephrase the question 2260337f47fSAndreas Gohr $prompt = $this->getPrompt('rephrase', ['history' => $chatHistory, 'question' => $question]); 2270337f47fSAndreas Gohr $messages = [['role' => 'user', 'content' => $prompt]]; 2289f6b34c4SAndreas Gohr return $this->getModel()->getRephrasedQuestion($messages); 2290337f47fSAndreas Gohr } 2300337f47fSAndreas Gohr 2310337f47fSAndreas Gohr /** 2320337f47fSAndreas Gohr * Load the given prompt template and fill in the variables 2330337f47fSAndreas Gohr * 2340337f47fSAndreas Gohr * @param string $type 2350337f47fSAndreas Gohr * @param string[] $vars 2360337f47fSAndreas Gohr * @return string 2370337f47fSAndreas Gohr */ 2380337f47fSAndreas Gohr protected function getPrompt($type, $vars = []) 2390337f47fSAndreas Gohr { 2400337f47fSAndreas Gohr $template = file_get_contents($this->localFN('prompt_' . $type)); 2410337f47fSAndreas Gohr 242*7ebc7895Ssplitbrain $replace = []; 2430337f47fSAndreas Gohr foreach ($vars as $key => $val) { 2440337f47fSAndreas Gohr $replace['{{' . strtoupper($key) . '}}'] = $val; 2450337f47fSAndreas Gohr } 2460337f47fSAndreas Gohr 2470337f47fSAndreas Gohr return strtr($template, $replace); 2480337f47fSAndreas Gohr } 249219268b1SAndreas Gohr 250219268b1SAndreas Gohr /** 251219268b1SAndreas Gohr * Construct the prompt to define the answer language 252219268b1SAndreas Gohr * 253219268b1SAndreas Gohr * @return string 254219268b1SAndreas Gohr */ 255219268b1SAndreas Gohr protected function getLanguagePrompt() 256219268b1SAndreas Gohr { 257219268b1SAndreas Gohr global $conf; 258219268b1SAndreas Gohr 259e33a1d7aSAndreas Gohr if ($this->getConf('preferUIlanguage') > AIChat::LANG_AUTO_ALL) { 260219268b1SAndreas Gohr $isoLangnames = include(__DIR__ . '/lang/languages.php'); 261219268b1SAndreas Gohr if (isset($isoLangnames[$conf['lang']])) { 262219268b1SAndreas Gohr $languagePrompt = 'Always answer in ' . $isoLangnames[$conf['lang']] . '.'; 263219268b1SAndreas Gohr return $languagePrompt; 264219268b1SAndreas Gohr } 265219268b1SAndreas Gohr } 266219268b1SAndreas Gohr 267219268b1SAndreas Gohr $languagePrompt = 'Always answer in the user\'s language.'; 268219268b1SAndreas Gohr return $languagePrompt; 269219268b1SAndreas Gohr } 270e33a1d7aSAndreas Gohr 271e33a1d7aSAndreas Gohr /** 272e33a1d7aSAndreas Gohr * Should sources be limited to current language? 273e33a1d7aSAndreas Gohr * 274e33a1d7aSAndreas Gohr * @return string The current language code or empty string 275e33a1d7aSAndreas Gohr */ 276e33a1d7aSAndreas Gohr public function getLanguageLimit() 277e33a1d7aSAndreas Gohr { 278e33a1d7aSAndreas Gohr if ($this->getConf('preferUIlanguage') >= AIChat::LANG_UI_LIMITED) { 279e33a1d7aSAndreas Gohr global $conf; 280e33a1d7aSAndreas Gohr return $conf['lang']; 281e33a1d7aSAndreas Gohr } else { 282e33a1d7aSAndreas Gohr return ''; 283e33a1d7aSAndreas Gohr } 284e33a1d7aSAndreas Gohr } 2850337f47fSAndreas Gohr} 286