10337f47fSAndreas Gohr<?php 20337f47fSAndreas Gohr 33379af09SAndreas Gohruse dokuwiki\Extension\CLIPlugin; 4*e33a1d7aSAndreas Gohruse dokuwiki\plugin\aichat\AIChat; 5f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Chunk; 60337f47fSAndreas Gohruse dokuwiki\plugin\aichat\Embeddings; 7754b8394SAndreas Gohruse dokuwiki\plugin\aichat\Model\AbstractModel; 8f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Model\OpenAI\GPT35Turbo; 901f06932SAndreas Gohruse dokuwiki\plugin\aichat\Storage\AbstractStorage; 1013dbfc23SAndreas Gohruse dokuwiki\plugin\aichat\Storage\PineconeStorage; 11f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Storage\SQLiteStorage; 120337f47fSAndreas Gohr 130337f47fSAndreas Gohrrequire_once __DIR__ . '/vendor/autoload.php'; 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 */ 210337f47fSAndreas Gohrclass helper_plugin_aichat extends \dokuwiki\Extension\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 /** 333379af09SAndreas Gohr * Use the given CLI plugin for logging 343379af09SAndreas Gohr * 353379af09SAndreas Gohr * @param CLIPlugin $logger 363379af09SAndreas Gohr * @return void 373379af09SAndreas Gohr */ 388285fff9SAndreas Gohr public function setLogger($logger) 398285fff9SAndreas Gohr { 403379af09SAndreas Gohr $this->logger = $logger; 413379af09SAndreas Gohr } 423379af09SAndreas Gohr 433379af09SAndreas Gohr /** 44c4127b8eSAndreas Gohr * Check if the current user is allowed to use the plugin (if it has been restricted) 45c4127b8eSAndreas Gohr * 46c4127b8eSAndreas Gohr * @return bool 47c4127b8eSAndreas Gohr */ 48c4127b8eSAndreas Gohr public function userMayAccess() 49c4127b8eSAndreas Gohr { 50c4127b8eSAndreas Gohr global $auth; 51c4127b8eSAndreas Gohr global $USERINFO; 52c4127b8eSAndreas Gohr global $INPUT; 53c4127b8eSAndreas Gohr 54c4127b8eSAndreas Gohr if (!$auth) return true; 55c4127b8eSAndreas Gohr if (!$this->getConf('restrict')) return true; 56c4127b8eSAndreas Gohr if (!isset($USERINFO)) return false; 57c4127b8eSAndreas Gohr 58c4127b8eSAndreas Gohr return auth_isMember($this->getConf('restrict'), $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']); 59c4127b8eSAndreas Gohr } 60c4127b8eSAndreas Gohr 61c4127b8eSAndreas Gohr /** 620337f47fSAndreas Gohr * Access the OpenAI client 630337f47fSAndreas Gohr * 64f6ef2e50SAndreas Gohr * @return GPT35Turbo 650337f47fSAndreas Gohr */ 66f6ef2e50SAndreas Gohr public function getModel() 670337f47fSAndreas Gohr { 689f6b34c4SAndreas Gohr if ($this->model === null) { 699f6b34c4SAndreas Gohr $class = '\\dokuwiki\\plugin\\aichat\\Model\\' . $this->getConf('model'); 709f6b34c4SAndreas Gohr 719f6b34c4SAndreas Gohr if (!class_exists($class)) { 729f6b34c4SAndreas Gohr throw new \RuntimeException('Configured model not found: ' . $class); 739f6b34c4SAndreas Gohr } 749f6b34c4SAndreas Gohr // FIXME for now we only have OpenAI models, so we can hardcode the auth setup 759f6b34c4SAndreas Gohr $this->model = new $class([ 769f6b34c4SAndreas Gohr 'key' => $this->getConf('openaikey'), 779f6b34c4SAndreas Gohr 'org' => $this->getConf('openaiorg') 789f6b34c4SAndreas Gohr ]); 799f6b34c4SAndreas Gohr } 809f6b34c4SAndreas Gohr 81f6ef2e50SAndreas Gohr return $this->model; 820337f47fSAndreas Gohr } 830337f47fSAndreas Gohr 840337f47fSAndreas Gohr /** 850337f47fSAndreas Gohr * Access the Embeddings interface 860337f47fSAndreas Gohr * 870337f47fSAndreas Gohr * @return Embeddings 880337f47fSAndreas Gohr */ 890337f47fSAndreas Gohr public function getEmbeddings() 900337f47fSAndreas Gohr { 919f6b34c4SAndreas Gohr if ($this->embeddings === null) { 9201f06932SAndreas Gohr $this->embeddings = new Embeddings($this->getModel(), $this->getStorage()); 933379af09SAndreas Gohr if ($this->logger) { 943379af09SAndreas Gohr $this->embeddings->setLogger($this->logger); 953379af09SAndreas Gohr } 969f6b34c4SAndreas Gohr } 979f6b34c4SAndreas Gohr 980337f47fSAndreas Gohr return $this->embeddings; 990337f47fSAndreas Gohr } 1000337f47fSAndreas Gohr 1010337f47fSAndreas Gohr /** 10201f06932SAndreas Gohr * Access the Storage interface 10301f06932SAndreas Gohr * 10401f06932SAndreas Gohr * @return AbstractStorage 10501f06932SAndreas Gohr */ 10601f06932SAndreas Gohr public function getStorage() 10701f06932SAndreas Gohr { 10801f06932SAndreas Gohr if ($this->storage === null) { 10913dbfc23SAndreas Gohr if ($this->getConf('pinecone_apikey')) { 11013dbfc23SAndreas Gohr $this->storage = new PineconeStorage(); 11113dbfc23SAndreas Gohr } else { 11201f06932SAndreas Gohr $this->storage = new SQLiteStorage(); 11368b6fa79SAndreas Gohr } 1148285fff9SAndreas Gohr 1153379af09SAndreas Gohr if ($this->logger) { 1163379af09SAndreas Gohr $this->storage->setLogger($this->logger); 1173379af09SAndreas Gohr } 11801f06932SAndreas Gohr } 11901f06932SAndreas Gohr 12001f06932SAndreas Gohr return $this->storage; 12101f06932SAndreas Gohr } 12201f06932SAndreas Gohr 12301f06932SAndreas Gohr /** 1240337f47fSAndreas Gohr * Ask a question with a chat history 1250337f47fSAndreas Gohr * 1260337f47fSAndreas Gohr * @param string $question 1270337f47fSAndreas Gohr * @param array[] $history The chat history [[user, ai], [user, ai], ...] 1280337f47fSAndreas Gohr * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources] 1290337f47fSAndreas Gohr * @throws Exception 1300337f47fSAndreas Gohr */ 1310337f47fSAndreas Gohr public function askChatQuestion($question, $history = []) 1320337f47fSAndreas Gohr { 1330337f47fSAndreas Gohr if ($history) { 1340337f47fSAndreas Gohr $standaloneQuestion = $this->rephraseChatQuestion($question, $history); 135754b8394SAndreas Gohr $prev = end($history); 1360337f47fSAndreas Gohr } else { 1370337f47fSAndreas Gohr $standaloneQuestion = $question; 138754b8394SAndreas Gohr $prev = []; 1390337f47fSAndreas Gohr } 140754b8394SAndreas Gohr return $this->askQuestion($standaloneQuestion, $prev); 1410337f47fSAndreas Gohr } 1420337f47fSAndreas Gohr 1430337f47fSAndreas Gohr /** 1440337f47fSAndreas Gohr * Ask a single standalone question 1450337f47fSAndreas Gohr * 1460337f47fSAndreas Gohr * @param string $question 147754b8394SAndreas Gohr * @param array $previous [user, ai] of the previous question 1480337f47fSAndreas Gohr * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources] 1490337f47fSAndreas Gohr * @throws Exception 1500337f47fSAndreas Gohr */ 151754b8394SAndreas Gohr public function askQuestion($question, $previous = []) 1520337f47fSAndreas Gohr { 153*e33a1d7aSAndreas Gohr $similar = $this->getEmbeddings()->getSimilarChunks($question, $this->getLanguageLimit()); 1549e81bea7SAndreas Gohr if ($similar) { 15555392016SAndreas Gohr $context = implode("\n", array_map(function (Chunk $chunk) { 15668908844SAndreas Gohr return "\n```\n" . $chunk->getText() . "\n```\n"; 15755392016SAndreas Gohr }, $similar)); 158219268b1SAndreas Gohr $prompt = $this->getPrompt('question', [ 159219268b1SAndreas Gohr 'context' => $context, 160219268b1SAndreas Gohr 'language' => $this->getLanguagePrompt() 161219268b1SAndreas Gohr ]); 1629e81bea7SAndreas Gohr } else { 1639e81bea7SAndreas Gohr $prompt = $this->getPrompt('noanswer'); 1649e81bea7SAndreas Gohr } 16568908844SAndreas Gohr 1660337f47fSAndreas Gohr $messages = [ 1670337f47fSAndreas Gohr [ 1680337f47fSAndreas Gohr 'role' => 'system', 1690337f47fSAndreas Gohr 'content' => $prompt 1700337f47fSAndreas Gohr ], 1710337f47fSAndreas Gohr [ 1720337f47fSAndreas Gohr 'role' => 'user', 1730337f47fSAndreas Gohr 'content' => $question 1740337f47fSAndreas Gohr ] 1750337f47fSAndreas Gohr ]; 1760337f47fSAndreas Gohr 177754b8394SAndreas Gohr if ($previous) { 178754b8394SAndreas Gohr array_unshift($messages, [ 179754b8394SAndreas Gohr 'role' => 'assistant', 180754b8394SAndreas Gohr 'content' => $previous[1] 181754b8394SAndreas Gohr ]); 182754b8394SAndreas Gohr array_unshift($messages, [ 183754b8394SAndreas Gohr 'role' => 'user', 184754b8394SAndreas Gohr 'content' => $previous[0] 185754b8394SAndreas Gohr ]); 186754b8394SAndreas Gohr } 187754b8394SAndreas Gohr 1889f6b34c4SAndreas Gohr $answer = $this->getModel()->getAnswer($messages); 1890337f47fSAndreas Gohr 1900337f47fSAndreas Gohr return [ 1910337f47fSAndreas Gohr 'question' => $question, 1920337f47fSAndreas Gohr 'answer' => $answer, 1930337f47fSAndreas Gohr 'sources' => $similar, 1940337f47fSAndreas Gohr ]; 1950337f47fSAndreas Gohr } 1960337f47fSAndreas Gohr 1970337f47fSAndreas Gohr /** 1980337f47fSAndreas Gohr * Rephrase a question into a standalone question based on the chat history 1990337f47fSAndreas Gohr * 2000337f47fSAndreas Gohr * @param string $question The original user question 2010337f47fSAndreas Gohr * @param array[] $history The chat history [[user, ai], [user, ai], ...] 2020337f47fSAndreas Gohr * @return string The rephrased question 2030337f47fSAndreas Gohr * @throws Exception 2040337f47fSAndreas Gohr */ 2050337f47fSAndreas Gohr public function rephraseChatQuestion($question, $history) 2060337f47fSAndreas Gohr { 2070337f47fSAndreas Gohr // go back in history as far as possible without hitting the token limit 2080337f47fSAndreas Gohr $chatHistory = ''; 2090337f47fSAndreas Gohr $history = array_reverse($history); 2100337f47fSAndreas Gohr foreach ($history as $row) { 211f6ef2e50SAndreas Gohr if ( 2129f6b34c4SAndreas Gohr count($this->getEmbeddings()->getTokenEncoder()->encode($chatHistory)) > 2139f6b34c4SAndreas Gohr $this->getModel()->getMaxRephrasingTokenLength() 214f6ef2e50SAndreas Gohr ) { 2150337f47fSAndreas Gohr break; 2160337f47fSAndreas Gohr } 2170337f47fSAndreas Gohr 2180337f47fSAndreas Gohr $chatHistory = 2190337f47fSAndreas Gohr "Human: " . $row[0] . "\n" . 2200337f47fSAndreas Gohr "Assistant: " . $row[1] . "\n" . 2210337f47fSAndreas Gohr $chatHistory; 2220337f47fSAndreas Gohr } 2230337f47fSAndreas Gohr 2240337f47fSAndreas Gohr // ask openAI to rephrase the question 2250337f47fSAndreas Gohr $prompt = $this->getPrompt('rephrase', ['history' => $chatHistory, 'question' => $question]); 2260337f47fSAndreas Gohr $messages = [['role' => 'user', 'content' => $prompt]]; 2279f6b34c4SAndreas Gohr return $this->getModel()->getRephrasedQuestion($messages); 2280337f47fSAndreas Gohr } 2290337f47fSAndreas Gohr 2300337f47fSAndreas Gohr /** 2310337f47fSAndreas Gohr * Load the given prompt template and fill in the variables 2320337f47fSAndreas Gohr * 2330337f47fSAndreas Gohr * @param string $type 2340337f47fSAndreas Gohr * @param string[] $vars 2350337f47fSAndreas Gohr * @return string 2360337f47fSAndreas Gohr */ 2370337f47fSAndreas Gohr protected function getPrompt($type, $vars = []) 2380337f47fSAndreas Gohr { 2390337f47fSAndreas Gohr $template = file_get_contents($this->localFN('prompt_' . $type)); 2400337f47fSAndreas Gohr 2410337f47fSAndreas Gohr $replace = array(); 2420337f47fSAndreas Gohr foreach ($vars as $key => $val) { 2430337f47fSAndreas Gohr $replace['{{' . strtoupper($key) . '}}'] = $val; 2440337f47fSAndreas Gohr } 2450337f47fSAndreas Gohr 2460337f47fSAndreas Gohr return strtr($template, $replace); 2470337f47fSAndreas Gohr } 248219268b1SAndreas Gohr 249219268b1SAndreas Gohr /** 250219268b1SAndreas Gohr * Construct the prompt to define the answer language 251219268b1SAndreas Gohr * 252219268b1SAndreas Gohr * @return string 253219268b1SAndreas Gohr */ 254219268b1SAndreas Gohr protected function getLanguagePrompt() 255219268b1SAndreas Gohr { 256219268b1SAndreas Gohr global $conf; 257219268b1SAndreas Gohr 258*e33a1d7aSAndreas Gohr if ($this->getConf('preferUIlanguage') > AIChat::LANG_AUTO_ALL) { 259219268b1SAndreas Gohr $isoLangnames = include(__DIR__ . '/lang/languages.php'); 260219268b1SAndreas Gohr if (isset($isoLangnames[$conf['lang']])) { 261219268b1SAndreas Gohr $languagePrompt = 'Always answer in ' . $isoLangnames[$conf['lang']] . '.'; 262219268b1SAndreas Gohr return $languagePrompt; 263219268b1SAndreas Gohr } 264219268b1SAndreas Gohr } 265219268b1SAndreas Gohr 266219268b1SAndreas Gohr $languagePrompt = 'Always answer in the user\'s language.'; 267219268b1SAndreas Gohr return $languagePrompt; 268219268b1SAndreas Gohr } 269*e33a1d7aSAndreas Gohr 270*e33a1d7aSAndreas Gohr /** 271*e33a1d7aSAndreas Gohr * Should sources be limited to current language? 272*e33a1d7aSAndreas Gohr * 273*e33a1d7aSAndreas Gohr * @return string The current language code or empty string 274*e33a1d7aSAndreas Gohr */ 275*e33a1d7aSAndreas Gohr public function getLanguageLimit() 276*e33a1d7aSAndreas Gohr { 277*e33a1d7aSAndreas Gohr if ($this->getConf('preferUIlanguage') >= AIChat::LANG_UI_LIMITED) { 278*e33a1d7aSAndreas Gohr global $conf; 279*e33a1d7aSAndreas Gohr return $conf['lang']; 280*e33a1d7aSAndreas Gohr } else { 281*e33a1d7aSAndreas Gohr return ''; 282*e33a1d7aSAndreas Gohr } 283*e33a1d7aSAndreas Gohr } 2840337f47fSAndreas Gohr} 2850337f47fSAndreas Gohr 286