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; 13*4c0099a8SAndreas Gohruse dokuwiki\plugin\aichat\Storage\QdrantStorage; 14f6ef2e50SAndreas Gohruse dokuwiki\plugin\aichat\Storage\SQLiteStorage; 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 */ 227ebc7895Ssplitbrainclass 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 /** 34f8d5ae01SAndreas Gohr * Constructor. Initializes vendor autoloader 35f8d5ae01SAndreas Gohr */ 36f8d5ae01SAndreas Gohr public function __construct() 37f8d5ae01SAndreas Gohr { 38f8d5ae01SAndreas Gohr require_once __DIR__ . '/vendor/autoload.php'; 39f8d5ae01SAndreas Gohr } 40f8d5ae01SAndreas Gohr 41f8d5ae01SAndreas Gohr /** 423379af09SAndreas Gohr * Use the given CLI plugin for logging 433379af09SAndreas Gohr * 443379af09SAndreas Gohr * @param CLIPlugin $logger 453379af09SAndreas Gohr * @return void 463379af09SAndreas Gohr */ 478285fff9SAndreas Gohr public function setLogger($logger) 488285fff9SAndreas Gohr { 493379af09SAndreas Gohr $this->logger = $logger; 503379af09SAndreas Gohr } 513379af09SAndreas Gohr 523379af09SAndreas Gohr /** 53c4127b8eSAndreas Gohr * Check if the current user is allowed to use the plugin (if it has been restricted) 54c4127b8eSAndreas Gohr * 55c4127b8eSAndreas Gohr * @return bool 56c4127b8eSAndreas Gohr */ 57c4127b8eSAndreas Gohr public function userMayAccess() 58c4127b8eSAndreas Gohr { 59c4127b8eSAndreas Gohr global $auth; 60c4127b8eSAndreas Gohr global $USERINFO; 61c4127b8eSAndreas Gohr global $INPUT; 62c4127b8eSAndreas Gohr 63c4127b8eSAndreas Gohr if (!$auth) return true; 64c4127b8eSAndreas Gohr if (!$this->getConf('restrict')) return true; 65c4127b8eSAndreas Gohr if (!isset($USERINFO)) return false; 66c4127b8eSAndreas Gohr 67c4127b8eSAndreas Gohr return auth_isMember($this->getConf('restrict'), $INPUT->server->str('REMOTE_USER'), $USERINFO['grps']); 68c4127b8eSAndreas Gohr } 69c4127b8eSAndreas Gohr 70c4127b8eSAndreas Gohr /** 710337f47fSAndreas Gohr * Access the OpenAI client 720337f47fSAndreas Gohr * 73f6ef2e50SAndreas Gohr * @return GPT35Turbo 740337f47fSAndreas Gohr */ 75f6ef2e50SAndreas Gohr public function getModel() 760337f47fSAndreas Gohr { 777ebc7895Ssplitbrain if (!$this->model instanceof AbstractModel) { 789f6b34c4SAndreas Gohr $class = '\\dokuwiki\\plugin\\aichat\\Model\\' . $this->getConf('model'); 799f6b34c4SAndreas Gohr 809f6b34c4SAndreas Gohr if (!class_exists($class)) { 819f6b34c4SAndreas Gohr throw new \RuntimeException('Configured model not found: ' . $class); 829f6b34c4SAndreas Gohr } 839f6b34c4SAndreas Gohr // FIXME for now we only have OpenAI models, so we can hardcode the auth setup 849f6b34c4SAndreas Gohr $this->model = new $class([ 859f6b34c4SAndreas Gohr 'key' => $this->getConf('openaikey'), 869f6b34c4SAndreas Gohr 'org' => $this->getConf('openaiorg') 879f6b34c4SAndreas Gohr ]); 889f6b34c4SAndreas Gohr } 899f6b34c4SAndreas Gohr 90f6ef2e50SAndreas Gohr return $this->model; 910337f47fSAndreas Gohr } 920337f47fSAndreas Gohr 930337f47fSAndreas Gohr /** 940337f47fSAndreas Gohr * Access the Embeddings interface 950337f47fSAndreas Gohr * 960337f47fSAndreas Gohr * @return Embeddings 970337f47fSAndreas Gohr */ 980337f47fSAndreas Gohr public function getEmbeddings() 990337f47fSAndreas Gohr { 1007ebc7895Ssplitbrain if (!$this->embeddings instanceof Embeddings) { 10101f06932SAndreas Gohr $this->embeddings = new Embeddings($this->getModel(), $this->getStorage()); 1023379af09SAndreas Gohr if ($this->logger) { 1033379af09SAndreas Gohr $this->embeddings->setLogger($this->logger); 1043379af09SAndreas Gohr } 1059f6b34c4SAndreas Gohr } 1069f6b34c4SAndreas Gohr 1070337f47fSAndreas Gohr return $this->embeddings; 1080337f47fSAndreas Gohr } 1090337f47fSAndreas Gohr 1100337f47fSAndreas Gohr /** 11101f06932SAndreas Gohr * Access the Storage interface 11201f06932SAndreas Gohr * 11301f06932SAndreas Gohr * @return AbstractStorage 11401f06932SAndreas Gohr */ 11501f06932SAndreas Gohr public function getStorage() 11601f06932SAndreas Gohr { 1177ebc7895Ssplitbrain if (!$this->storage instanceof AbstractStorage) { 11813dbfc23SAndreas Gohr if ($this->getConf('pinecone_apikey')) { 11913dbfc23SAndreas Gohr $this->storage = new PineconeStorage(); 1205e6dd16eSAndreas Gohr } elseif ($this->getConf('chroma_baseurl')) { 1215e6dd16eSAndreas Gohr $this->storage = new ChromaStorage(); 122*4c0099a8SAndreas Gohr } elseif ($this->getConf('qdrant_baseurl')) { 123*4c0099a8SAndreas Gohr $this->storage = new QdrantStorage(); 12413dbfc23SAndreas Gohr } else { 12501f06932SAndreas Gohr $this->storage = new SQLiteStorage(); 12668b6fa79SAndreas Gohr } 1278285fff9SAndreas Gohr 1283379af09SAndreas Gohr if ($this->logger) { 1293379af09SAndreas Gohr $this->storage->setLogger($this->logger); 1303379af09SAndreas Gohr } 13101f06932SAndreas Gohr } 13201f06932SAndreas Gohr 13301f06932SAndreas Gohr return $this->storage; 13401f06932SAndreas Gohr } 13501f06932SAndreas Gohr 13601f06932SAndreas Gohr /** 1370337f47fSAndreas Gohr * Ask a question with a chat history 1380337f47fSAndreas Gohr * 1390337f47fSAndreas Gohr * @param string $question 1400337f47fSAndreas Gohr * @param array[] $history The chat history [[user, ai], [user, ai], ...] 1410337f47fSAndreas Gohr * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources] 1420337f47fSAndreas Gohr * @throws Exception 1430337f47fSAndreas Gohr */ 1440337f47fSAndreas Gohr public function askChatQuestion($question, $history = []) 1450337f47fSAndreas Gohr { 1460337f47fSAndreas Gohr if ($history) { 1470337f47fSAndreas Gohr $standaloneQuestion = $this->rephraseChatQuestion($question, $history); 148754b8394SAndreas Gohr $prev = end($history); 1490337f47fSAndreas Gohr } else { 1500337f47fSAndreas Gohr $standaloneQuestion = $question; 151754b8394SAndreas Gohr $prev = []; 1520337f47fSAndreas Gohr } 153754b8394SAndreas Gohr return $this->askQuestion($standaloneQuestion, $prev); 1540337f47fSAndreas Gohr } 1550337f47fSAndreas Gohr 1560337f47fSAndreas Gohr /** 1570337f47fSAndreas Gohr * Ask a single standalone question 1580337f47fSAndreas Gohr * 1590337f47fSAndreas Gohr * @param string $question 160754b8394SAndreas Gohr * @param array $previous [user, ai] of the previous question 1610337f47fSAndreas Gohr * @return array ['question' => $question, 'answer' => $answer, 'sources' => $sources] 1620337f47fSAndreas Gohr * @throws Exception 1630337f47fSAndreas Gohr */ 164754b8394SAndreas Gohr public function askQuestion($question, $previous = []) 1650337f47fSAndreas Gohr { 166e33a1d7aSAndreas Gohr $similar = $this->getEmbeddings()->getSimilarChunks($question, $this->getLanguageLimit()); 1679e81bea7SAndreas Gohr if ($similar) { 168441edf84SAndreas Gohr $context = implode( 169441edf84SAndreas Gohr "\n", 170441edf84SAndreas Gohr array_map(static fn(Chunk $chunk) => "\n```\n" . $chunk->getText() . "\n```\n", $similar) 171441edf84SAndreas Gohr ); 172219268b1SAndreas Gohr $prompt = $this->getPrompt('question', [ 173219268b1SAndreas Gohr 'context' => $context, 174219268b1SAndreas Gohr 'language' => $this->getLanguagePrompt() 175219268b1SAndreas Gohr ]); 1769e81bea7SAndreas Gohr } else { 1779e81bea7SAndreas Gohr $prompt = $this->getPrompt('noanswer'); 1789e81bea7SAndreas Gohr } 17968908844SAndreas Gohr 1800337f47fSAndreas Gohr $messages = [ 1810337f47fSAndreas Gohr [ 1820337f47fSAndreas Gohr 'role' => 'system', 1830337f47fSAndreas Gohr 'content' => $prompt 1840337f47fSAndreas Gohr ], 1850337f47fSAndreas Gohr [ 1860337f47fSAndreas Gohr 'role' => 'user', 1870337f47fSAndreas Gohr 'content' => $question 1880337f47fSAndreas Gohr ] 1890337f47fSAndreas Gohr ]; 1900337f47fSAndreas Gohr 191754b8394SAndreas Gohr if ($previous) { 192754b8394SAndreas Gohr array_unshift($messages, [ 193754b8394SAndreas Gohr 'role' => 'assistant', 194754b8394SAndreas Gohr 'content' => $previous[1] 195754b8394SAndreas Gohr ]); 196754b8394SAndreas Gohr array_unshift($messages, [ 197754b8394SAndreas Gohr 'role' => 'user', 198754b8394SAndreas Gohr 'content' => $previous[0] 199754b8394SAndreas Gohr ]); 200754b8394SAndreas Gohr } 201754b8394SAndreas Gohr 2029f6b34c4SAndreas Gohr $answer = $this->getModel()->getAnswer($messages); 2030337f47fSAndreas Gohr 2040337f47fSAndreas Gohr return [ 2050337f47fSAndreas Gohr 'question' => $question, 2060337f47fSAndreas Gohr 'answer' => $answer, 2070337f47fSAndreas Gohr 'sources' => $similar, 2080337f47fSAndreas Gohr ]; 2090337f47fSAndreas Gohr } 2100337f47fSAndreas Gohr 2110337f47fSAndreas Gohr /** 2120337f47fSAndreas Gohr * Rephrase a question into a standalone question based on the chat history 2130337f47fSAndreas Gohr * 2140337f47fSAndreas Gohr * @param string $question The original user question 2150337f47fSAndreas Gohr * @param array[] $history The chat history [[user, ai], [user, ai], ...] 2160337f47fSAndreas Gohr * @return string The rephrased question 2170337f47fSAndreas Gohr * @throws Exception 2180337f47fSAndreas Gohr */ 2190337f47fSAndreas Gohr public function rephraseChatQuestion($question, $history) 2200337f47fSAndreas Gohr { 2210337f47fSAndreas Gohr // go back in history as far as possible without hitting the token limit 2220337f47fSAndreas Gohr $chatHistory = ''; 2230337f47fSAndreas Gohr $history = array_reverse($history); 2240337f47fSAndreas Gohr foreach ($history as $row) { 225f6ef2e50SAndreas Gohr if ( 2269f6b34c4SAndreas Gohr count($this->getEmbeddings()->getTokenEncoder()->encode($chatHistory)) > 2279f6b34c4SAndreas Gohr $this->getModel()->getMaxRephrasingTokenLength() 228f6ef2e50SAndreas Gohr ) { 2290337f47fSAndreas Gohr break; 2300337f47fSAndreas Gohr } 2310337f47fSAndreas Gohr 2320337f47fSAndreas Gohr $chatHistory = 2330337f47fSAndreas Gohr "Human: " . $row[0] . "\n" . 2340337f47fSAndreas Gohr "Assistant: " . $row[1] . "\n" . 2350337f47fSAndreas Gohr $chatHistory; 2360337f47fSAndreas Gohr } 2370337f47fSAndreas Gohr 2380337f47fSAndreas Gohr // ask openAI to rephrase the question 2390337f47fSAndreas Gohr $prompt = $this->getPrompt('rephrase', ['history' => $chatHistory, 'question' => $question]); 2400337f47fSAndreas Gohr $messages = [['role' => 'user', 'content' => $prompt]]; 2419f6b34c4SAndreas Gohr return $this->getModel()->getRephrasedQuestion($messages); 2420337f47fSAndreas Gohr } 2430337f47fSAndreas Gohr 2440337f47fSAndreas Gohr /** 2450337f47fSAndreas Gohr * Load the given prompt template and fill in the variables 2460337f47fSAndreas Gohr * 2470337f47fSAndreas Gohr * @param string $type 2480337f47fSAndreas Gohr * @param string[] $vars 2490337f47fSAndreas Gohr * @return string 2500337f47fSAndreas Gohr */ 2510337f47fSAndreas Gohr protected function getPrompt($type, $vars = []) 2520337f47fSAndreas Gohr { 2530337f47fSAndreas Gohr $template = file_get_contents($this->localFN('prompt_' . $type)); 2540337f47fSAndreas Gohr 2557ebc7895Ssplitbrain $replace = []; 2560337f47fSAndreas Gohr foreach ($vars as $key => $val) { 2570337f47fSAndreas Gohr $replace['{{' . strtoupper($key) . '}}'] = $val; 2580337f47fSAndreas Gohr } 2590337f47fSAndreas Gohr 2600337f47fSAndreas Gohr return strtr($template, $replace); 2610337f47fSAndreas Gohr } 262219268b1SAndreas Gohr 263219268b1SAndreas Gohr /** 264219268b1SAndreas Gohr * Construct the prompt to define the answer language 265219268b1SAndreas Gohr * 266219268b1SAndreas Gohr * @return string 267219268b1SAndreas Gohr */ 268219268b1SAndreas Gohr protected function getLanguagePrompt() 269219268b1SAndreas Gohr { 270219268b1SAndreas Gohr global $conf; 271219268b1SAndreas Gohr 272e33a1d7aSAndreas Gohr if ($this->getConf('preferUIlanguage') > AIChat::LANG_AUTO_ALL) { 273219268b1SAndreas Gohr $isoLangnames = include(__DIR__ . '/lang/languages.php'); 274219268b1SAndreas Gohr if (isset($isoLangnames[$conf['lang']])) { 275219268b1SAndreas Gohr $languagePrompt = 'Always answer in ' . $isoLangnames[$conf['lang']] . '.'; 276219268b1SAndreas Gohr return $languagePrompt; 277219268b1SAndreas Gohr } 278219268b1SAndreas Gohr } 279219268b1SAndreas Gohr 280219268b1SAndreas Gohr $languagePrompt = 'Always answer in the user\'s language.'; 281219268b1SAndreas Gohr return $languagePrompt; 282219268b1SAndreas Gohr } 283e33a1d7aSAndreas Gohr 284e33a1d7aSAndreas Gohr /** 285e33a1d7aSAndreas Gohr * Should sources be limited to current language? 286e33a1d7aSAndreas Gohr * 287e33a1d7aSAndreas Gohr * @return string The current language code or empty string 288e33a1d7aSAndreas Gohr */ 289e33a1d7aSAndreas Gohr public function getLanguageLimit() 290e33a1d7aSAndreas Gohr { 291e33a1d7aSAndreas Gohr if ($this->getConf('preferUIlanguage') >= AIChat::LANG_UI_LIMITED) { 292e33a1d7aSAndreas Gohr global $conf; 293e33a1d7aSAndreas Gohr return $conf['lang']; 294e33a1d7aSAndreas Gohr } else { 295e33a1d7aSAndreas Gohr return ''; 296e33a1d7aSAndreas Gohr } 297e33a1d7aSAndreas Gohr } 2980337f47fSAndreas Gohr} 299