1<?php 2 3use dokuwiki\Extension\CLIPlugin; 4use dokuwiki\plugin\aichat\Chunk; 5use dokuwiki\Search\Indexer; 6use splitbrain\phpcli\Colors; 7use splitbrain\phpcli\Options; 8use splitbrain\phpcli\TableFormatter; 9 10/** 11 * DokuWiki Plugin aichat (CLI Component) 12 * 13 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html 14 * @author Andreas Gohr <gohr@cosmocode.de> 15 */ 16class cli_plugin_aichat extends CLIPlugin 17{ 18 /** @var helper_plugin_aichat */ 19 protected $helper; 20 21 public function __construct($autocatch = true) 22 { 23 parent::__construct($autocatch); 24 $this->helper = plugin_load('helper', 'aichat'); 25 $this->helper->setLogger($this); 26 } 27 28 /** @inheritDoc */ 29 protected function setup(Options $options) 30 { 31 $options->useCompactHelp(); 32 33 $options->setHelp( 34 'Manage and query the AI chatbot data. Please note that calls to your LLM provider will be made. ' . 35 'This may incur costs.' 36 ); 37 38 $options->registerCommand( 39 'embed', 40 'Create embeddings for all pages. This skips pages that already have embeddings' 41 ); 42 $options->registerOption( 43 'clear', 44 'Clear all existing embeddings before creating new ones', 45 'c', 46 false, 47 'embed' 48 ); 49 50 $options->registerCommand('maintenance', 'Run storage maintenance. Refert to the documentation for details.'); 51 52 $options->registerCommand('similar', 'Search for similar pages'); 53 $options->registerArgument('query', 'Look up chunks similar to this query', true, 'similar'); 54 55 $options->registerCommand('ask', 'Ask a question'); 56 $options->registerArgument('question', 'The question to ask', true, 'ask'); 57 58 $options->registerCommand('chat', 'Start an interactive chat session'); 59 60 $options->registerCommand('info', 'Get Info about the vector storage'); 61 62 $options->registerCommand('split', 'Split a page into chunks (for debugging)'); 63 $options->registerArgument('page', 'The page to split', true, 'split'); 64 65 $options->registerCommand('page', 'Check if chunks for a given page are available (for debugging)'); 66 $options->registerArgument('page', 'The page to check', true, 'page'); 67 $options->registerOption('dump', 'Dump the chunks', 'd', false, 'page'); 68 69 $options->registerCommand('tsv', 'Create TSV files for visualizing at http://projector.tensorflow.org/' . 70 ' Not supported on all storages.'); 71 $options->registerArgument('vector.tsv', 'The vector file', false, 'tsv'); 72 $options->registerArgument('meta.tsv', 'The meta file', false, 'tsv'); 73 } 74 75 /** @inheritDoc */ 76 protected function main(Options $options) 77 { 78 ini_set('memory_limit', -1); 79 switch ($options->getCmd()) { 80 case 'embed': 81 $this->createEmbeddings($options->getOpt('clear')); 82 break; 83 case 'maintenance': 84 $this->runMaintenance(); 85 break; 86 case 'similar': 87 $this->similar($options->getArgs()[0]); 88 break; 89 case 'ask': 90 $this->ask($options->getArgs()[0]); 91 break; 92 case 'chat': 93 $this->chat(); 94 break; 95 case 'split': 96 $this->split($options->getArgs()[0]); 97 break; 98 case 'page': 99 $this->page($options->getArgs()[0], $options->getOpt('dump')); 100 break; 101 case 'info': 102 $this->showinfo(); 103 break; 104 case 'tsv': 105 $args = $options->getArgs(); 106 $vector = $args[0] ?? 'vector.tsv'; 107 $meta = $args[1] ?? 'meta.tsv'; 108 $this->tsv($vector, $meta); 109 break; 110 default: 111 echo $options->help(); 112 } 113 } 114 115 /** 116 * @return void 117 */ 118 protected function showinfo() 119 { 120 $stats = [ 121 'model' => $this->getConf('model'), 122 ]; 123 $stats = array_merge($stats, $this->helper->getStorage()->statistics()); 124 $this->printTable($stats); 125 } 126 127 /** 128 * Print key value data as tabular data 129 * 130 * @param array $data 131 * @param int $level 132 * @return void 133 */ 134 protected function printTable($data, $level = 0) 135 { 136 $tf = new TableFormatter($this->colors); 137 foreach ($data as $key => $value) { 138 if (is_array($value)) { 139 echo $tf->format( 140 [$level * 2, 15, '*'], 141 ['', $key, ''], 142 [Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE] 143 ); 144 $this->printTable($value, $level + 1); 145 } else { 146 echo $tf->format( 147 [$level * 2, 15, '*'], 148 ['', $key, $value], 149 [Colors::C_LIGHTBLUE, Colors::C_LIGHTBLUE, Colors::C_LIGHTGRAY] 150 ); 151 } 152 } 153 } 154 155 /** 156 * Check chunk availability for a given page 157 * 158 * @param string $page 159 * @return void 160 */ 161 protected function page($page, $dump = false) 162 { 163 $indexer = new Indexer(); 164 $pages = $indexer->getPages(); 165 $pos = array_search(cleanID($page), $pages); 166 167 if ($pos === false) { 168 $this->error('Page not found'); 169 return; 170 } 171 172 $storage = $this->helper->getStorage(); 173 $chunks = $storage->getPageChunks($page, $pos * 100); 174 if ($chunks) { 175 $this->success('Found ' . count($chunks) . ' chunks'); 176 if ($dump) { 177 echo json_encode($chunks, JSON_PRETTY_PRINT); 178 } 179 } else { 180 $this->error('No chunks found'); 181 } 182 } 183 184 /** 185 * Split the given page into chunks and print them 186 * 187 * @param string $page 188 * @return void 189 * @throws Exception 190 */ 191 protected function split($page) 192 { 193 $text = rawWiki($page); 194 $chunks = $this->helper->getEmbeddings()->splitIntoChunks($text); 195 foreach ($chunks as $chunk) { 196 echo $chunk; 197 echo "\n"; 198 $this->colors->ptln('--------------------------------', Colors::C_LIGHTPURPLE); 199 } 200 $this->success('Split into ' . count($chunks) . ' chunks'); 201 } 202 203 /** 204 * Interactive Chat Session 205 * 206 * @return void 207 * @throws Exception 208 */ 209 protected function chat() 210 { 211 $history = []; 212 while ($q = $this->readLine('Your Question')) { 213 $this->helper->getModel()->resetUsageStats(); 214 $result = $this->helper->askChatQuestion($q, $history); 215 $this->colors->ptln("Interpretation: {$result['question']}", Colors::C_LIGHTPURPLE); 216 $history[] = [$result['question'], $result['answer']]; 217 $this->printAnswer($result); 218 } 219 } 220 221 /** 222 * Handle a single, standalone question 223 * 224 * @param string $query 225 * @return void 226 * @throws Exception 227 */ 228 protected function ask($query) 229 { 230 $result = $this->helper->askQuestion($query); 231 $this->printAnswer($result); 232 } 233 234 /** 235 * Get the pages that are similar to the query 236 * 237 * @param string $query 238 * @return void 239 */ 240 protected function similar($query) 241 { 242 $langlimit = $this->helper->getLanguageLimit(); 243 if ($langlimit) { 244 $this->info('Limiting results to {lang}', ['lang' => $langlimit]); 245 } 246 247 $sources = $this->helper->getEmbeddings()->getSimilarChunks($query, $langlimit); 248 $this->printSources($sources); 249 } 250 251 /** 252 * Run the maintenance tasks 253 * 254 * @return void 255 */ 256 protected function runMaintenance() 257 { 258 $start = time(); 259 $this->helper->getStorage()->runMaintenance(); 260 $this->notice('Peak memory used: {memory}', ['memory' => filesize_h(memory_get_peak_usage(true))]); 261 $this->notice('Spent time: {time}min', ['time' => round((time() - $start) / 60, 2)]); 262 } 263 264 /** 265 * Recreate chunks and embeddings for all pages 266 * 267 * @return void 268 */ 269 protected function createEmbeddings($clear) 270 { 271 [$skipRE, $matchRE] = $this->getRegexps(); 272 273 $start = time(); 274 $this->helper->getEmbeddings()->createNewIndex($skipRE, $matchRE, $clear); 275 $this->notice('Peak memory used: {memory}', ['memory' => filesize_h(memory_get_peak_usage(true))]); 276 $this->notice('Spent time: {time}min', ['time' => round((time() - $start) / 60, 2)]); 277 } 278 279 /** 280 * Dump TSV files for debugging 281 * 282 * @return void 283 */ 284 protected function tsv($vector, $meta) 285 { 286 287 $storage = $this->helper->getStorage(); 288 $storage->dumpTSV($vector, $meta); 289 $this->success('written to ' . $vector . ' and ' . $meta); 290 } 291 292 /** 293 * Print the given detailed answer in a nice way 294 * 295 * @param array $answer 296 * @return void 297 */ 298 protected function printAnswer($answer) 299 { 300 $this->colors->ptln($answer['answer'], Colors::C_LIGHTCYAN); 301 echo "\n"; 302 $this->printSources($answer['sources']); 303 echo "\n"; 304 $this->printUsage(); 305 } 306 307 /** 308 * Print the given sources 309 * 310 * @param Chunk[] $sources 311 * @return void 312 */ 313 protected function printSources($sources) 314 { 315 foreach ($sources as $source) { 316 /** @var Chunk $source */ 317 $this->colors->ptln( 318 "\t" . $source->getPage() . ' ' . $source->getId() . ' (' . $source->getScore() . ')', 319 Colors::C_LIGHTBLUE 320 ); 321 } 322 } 323 324 /** 325 * Print the usage statistics for OpenAI 326 * 327 * @return void 328 */ 329 protected function printUsage() 330 { 331 $this->info( 332 'Made {requests} requests in {time}s to Model. Used {tokens} tokens for about ${cost}.', 333 $this->helper->getModel()->getUsageStats() 334 ); 335 } 336 337 /** 338 * Interactively ask for a value from the user 339 * 340 * @param string $prompt 341 * @return string 342 */ 343 protected function readLine($prompt) 344 { 345 $value = ''; 346 347 while ($value === '') { 348 echo $prompt; 349 echo ': '; 350 351 $fh = fopen('php://stdin', 'r'); 352 $value = trim(fgets($fh)); 353 fclose($fh); 354 } 355 356 return $value; 357 } 358 359 /** 360 * Read the skip and match regex from the config 361 * 362 * Ensures the regular expressions are valid 363 * 364 * @return string[] [$skipRE, $matchRE] 365 */ 366 protected function getRegexps() 367 { 368 $skip = $this->getConf('skipRegex'); 369 $skipRE = ''; 370 $match = $this->getConf('matchRegex'); 371 $matchRE = ''; 372 373 if ($skip) { 374 $skipRE = '/' . $skip . '/'; 375 if (@preg_match($skipRE, '') === false) { 376 $this->error(preg_last_error_msg()); 377 $this->error('Invalid regular expression in $conf[\'skipRegex\']. Ignored.'); 378 $skipRE = ''; 379 } else { 380 $this->success('Skipping pages matching ' . $skipRE); 381 } 382 } 383 384 if ($match) { 385 $matchRE = '/' . $match . '/'; 386 if (@preg_match($matchRE, '') === false) { 387 $this->error(preg_last_error_msg()); 388 $this->error('Invalid regular expression in $conf[\'matchRegex\']. Ignored.'); 389 $matchRE = ''; 390 } else { 391 $this->success('Only indexing pages matching ' . $matchRE); 392 } 393 } 394 return [$skipRE, $matchRE]; 395 } 396} 397